Esempio n. 1
0
    void gridData_OnAction(string actionName, object actionArgument)
    {
        switch (actionName.ToLower())
        {
        case "edit":
            URLHelper.Redirect("Product_Edit_Frameset.aspx?productid=" + ValidationHelper.GetInteger(actionArgument, 0) + "&siteId=" + SelectSite.SiteID);
            break;

        case "delete":
            int     skuId  = ValidationHelper.GetInteger(actionArgument, 0);
            SKUInfo skuObj = SKUInfoProvider.GetSKUInfo(skuId);

            // Check module permissions
            if (!ECommerceContext.IsUserAuthorizedToModifySKU(skuObj))
            {
                if (skuObj.IsGlobal)
                {
                    RedirectToAccessDenied("CMS.Ecommerce", "EcommerceGlobalModify");
                }
                else
                {
                    RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyProducts");
                }
            }

            // Check dependencies
            if (SKUInfoProvider.CheckDependencies(skuId))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Ecommerce.DeleteDisabled");
                return;
            }

            SKUInfoProvider.DeleteSKUInfo(skuObj);

            break;
        }
    }
Esempio n. 2
0
    /// <summary>
    /// Returns amount of saved money based on the difference between product seller price and product retail price.
    /// </summary>
    /// <param name="discounts">Indicates if discounts should be applied to the seller price before the saved amount is calculated</param>
    /// <param name="taxes">Indicates if taxes should be applied to both retail price and seller price before the saved amount is calculated</param>
    /// <param name="column1">Name of the column from which the seller price is retrieved, if empty SKUPrice column is used</param>
    /// <param name="column2">Name of the column from which the retail price is retrieved, if empty SKURetailPrice column is used</param>
    /// <param name="percentage">True - result is percentage, False - result is in the current currency</param>
    public static double GetSKUPriceSaving(SKUInfo sku, bool discounts, bool taxes, string column1, string column2, bool percentage)
    {
        // Do not process
        if (sku == null)
        {
            return(0);
        }

        // Ensure columns
        column1 = string.IsNullOrEmpty(column1) ? "SKUPrice" : column1;
        column2 = string.IsNullOrEmpty(column2) ? "SKURetailPrice" : column2;

        // Prices
        double price       = SKUInfoProvider.GetSKUPrice(sku, null, discounts, taxes, false, column1);
        double retailPrice = SKUInfoProvider.GetSKUPrice(sku, null, false, taxes, false, column2);

        // Saved amount
        double savedAmount = retailPrice - price;

        // When seller price is greater than retail price
        if (((price > 0) && (savedAmount < 0)) || ((price < 0) && (savedAmount > 0)))
        {
            // Zero saved amount
            savedAmount = 0;
        }
        else if (percentage)
        {
            // Percentage saved amount
            savedAmount = ((retailPrice == 0) ? 0 : Math.Round(100 * savedAmount / retailPrice));
        }
        else if (ECommerceContext.CurrentShoppingCart != null)
        {
            // If shopping cart is in context - apply exchange rates
            savedAmount = ECommerceContext.CurrentShoppingCart.ApplyExchangeRate(savedAmount);
        }

        return(savedAmount);
    }
Esempio n. 3
0
    /// <summary>
    /// Get Skudetails
    /// </summary>
    /// <param name="productsDetails"></param>
    /// <returns></returns>
    public List <SKUInfo> GetSkuDetails(List <CampaignsProduct> productsDetails)
    {
        List <SKUInfo> skuDetails = new List <SKUInfo>();

        try
        {
            List <int> skuIds = productsDetails.Select(x => x.NodeSKUID).ToList <int>();
            if (!DataHelper.DataSourceIsEmpty(skuIds))
            {
                skuDetails = SKUInfoProvider.GetSKUs()
                             .WhereIn("SKUID", skuIds)
                             .And()
                             .WhereEquals("SKUEnabled", true)
                             .Columns("SKUProductCustomerReferenceNumber,SKUNumber,SKUName,SKUPrice,SKUEnabled,SKUImagePath,SKUAvailableItems,SKUID,SKUDescription")
                             .ToList();
            }
        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("Get Sku Details", "GetSkuDetails()", ex, CurrentSite.SiteID, ex.Message);
        }
        return(skuDetails);
    }
Esempio n. 4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Content", "ContentProduct.TaxClasses"))
        {
            RedirectToCMSDeskUIElementAccessDenied("CMS.Content", "ContentProduct.TaxClasses");
        }

        if (this.Node != null)
        {
            sku = SKUInfoProvider.GetSKUInfo(productId);

            EditedObject = sku;

            if (sku != null)
            {
                // Check site ID
                CheckProductSiteID(sku.SKUSiteID);

                taxForm.ProductID = productId;
                this.taxForm.UniSelector.OnSelectionChanged += UniSelector_OnSelectionChanged;
            }
        }
    }
    /// <summary>
    /// Preloads uniSelector and selects actual data.
    /// </summary>
    /// <param name="forceReload">Force reload</param>
    protected void PreloadUniSelector(bool forceReload)
    {
        if (!RequestHelper.IsPostBack())
        {
            // Get assigned products
            string where = "SKUID IN (SELECT SKUID FROM COM_SKUOptionCategory WHERE CategoryID = " + categoryId + ")";

            where = SqlHelper.AddWhereCondition(where, GetPartialWhereCondition());

            // Preload data to uniSelector and save them
            DataSet ds = SKUInfoProvider.GetSKUs().Column("SKUID").Where(where);
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                uniSelector.Value = UniSelectorData = TextHelper.Join(";", DataHelper.GetStringValues((ds).Tables[0], "SKUID"));
            }
        }

        if (forceReload)
        {
            UniSelectorData = ValidationHelper.GetString(uniSelector.Value, string.Empty);
            uniSelector.Reload(true);
        }
    }
Esempio n. 6
0
        /// <summary>
        /// Returns an enumerable collection of all variants of the given product.
        /// </summary>
        /// <param name="productId">SKU object identifier of the variant's parent product.</param>
        /// <returns>Collection of product variants. See <see cref="Variant"/> for detailed information.</returns>
        public IEnumerable <Variant> GetByProductId(int productId)
        {
            var variantSKUs = VariantHelper.GetVariants(productId).OnSite(SiteID).ToList();

            // Get the used option IDs for the variants
            var variantOptions = VariantOptionInfoProvider.GetVariantOptions()
                                 .WhereIn("VariantSKUID", variantSKUs.Select(s => s.SKUID).ToList())
                                 .ToList();

            // Pre-load option SKUs for the variants
            var options = SKUInfoProvider.GetSKUs()
                          .WhereIn("SKUID", variantOptions.Select(v => v.OptionSKUID).ToList())
                          .ToList();

            // Create variants with the options
            return(variantSKUs.Select(sku => new Variant(
                                          sku,
                                          new ProductAttributeSet(variantOptions
                                                                  .Where(o => o.VariantSKUID == sku.SKUID)
                                                                  .Select(o => options.First(s => s.SKUID == o.OptionSKUID))
                                                                  .ToArray())
                                          )));
        }
Esempio n. 7
0
        /// <summary>
        /// Returns a collection of option categories used in a product's variants.
        /// </summary>
        /// <param name="productId">SKU identifier of the variant's parent product.</param>
        /// <returns>Collection of option categories used in a product's variants. See <see cref="ProductOptionCategory"/> for detailed information.</returns>
        public IEnumerable <ProductOptionCategory> GetVariantOptionCategories(int productId)
        {
            // Get a list of option categories
            var optionCategoriesList = VariantHelper.GetProductVariantsCategories(productId).ToList();

            // Get all variant's options
            var variantOptionIDs = VariantOptionInfoProvider.GetVariantOptions()
                                   .WhereIn("VariantSKUID", VariantHelper.GetVariants(productId).Column("SKUID"))
                                   .Column("OptionSKUID");

            var variantOptionsList = SKUInfoProvider.GetSKUs()
                                     .WhereIn("SKUID", variantOptionIDs)
                                     .OrderBy("SKUOrder")
                                     .ToList();

            // Create option categories with selectable variant options
            return(optionCategoriesList.Select(cat =>
                                               new ProductOptionCategory(
                                                   cat,
                                                   variantOptionsList.Where(o => o.SKUOptionCategoryID == cat.CategoryID)
                                                   )
                                               ));
        }
        private SKUTreeNode GetProductForSKU(int skuID)
        {
            var sku = SKUInfoProvider.GetSKUInfo(skuID);

            if ((sku == null) || sku.IsProductOption)
            {
                return(null);
            }

            if (sku.IsProductVariant)
            {
                skuID = sku.SKUParentSKUID;
            }

            var node = DocumentHelper.GetDocuments()
                       .Published()
                       .OnSite(sku.SKUSiteID)
                       .CombineWithDefaultCulture()
                       .WhereEquals("NodeSKUID", skuID)
                       .FirstOrDefault();

            return(node as SKUTreeNode);
        }
    private void CheckPermissions()
    {
        // Check module permissions
        bool globalCategory = (OptionCategoryEditElem.CategorySiteID <= 0);

        if (productID > 0)
        {
            var  skuInfo   = SKUInfoProvider.GetSKUInfo(productID);
            bool globalSKU = skuInfo.IsGlobal;

            // Check product permissions
            if (!ECommerceContext.IsUserAuthorizedToModifySKU(globalSKU))
            {
                if (globalSKU)
                {
                    RedirectToAccessDenied(ModuleName.ECOMMERCE, EcommercePermissions.ECOMMERCE_MODIFYGLOBAL);
                }
                else
                {
                    RedirectToAccessDenied(ModuleName.ECOMMERCE, "EcommerceModify OR ModifyProducts");
                }
            }
        }

        // Check product option category permissions
        if (!ECommerceContext.IsUserAuthorizedToModifyOptionCategory(globalCategory))
        {
            if (globalCategory)
            {
                RedirectToAccessDenied(ModuleName.ECOMMERCE, EcommercePermissions.ECOMMERCE_MODIFYGLOBAL);
            }
            else
            {
                RedirectToAccessDenied(ModuleName.ECOMMERCE, "EcommerceModify OR ModifyProducts");
            }
        }
    }
Esempio n. 10
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get current product info
        var product = SKUInfoProvider.GetSKUInfo(ProductID);

        if (product != null)
        {
            // Allow site selector for global admins
            if (!MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin))
            {
                filterDocuments.LoadSites = false;
                filterDocuments.SitesPlaceHolder.Visible = false;
            }

            // Get no data message text
            string productNameLocalized = ResHelper.LocalizeString(product.SKUName);
            string noDataMessage        = string.Format(GetString("ProductDocuments.Documents.nodata"), HTMLHelper.HTMLEncode(productNameLocalized));
            if (filterDocuments.FilterIsSet)
            {
                noDataMessage = GetString("ProductDocuments.Documents.noresults");
            }
            else if (filterDocuments.SelectedSite != TreeProvider.ALL_SITES)
            {
                SiteInfo si = SiteInfoProvider.GetSiteInfo(filterDocuments.SelectedSite);
                if (si != null)
                {
                    noDataMessage = string.Format(GetString("ProductDocuments.Documents.nodataforsite"), HTMLHelper.HTMLEncode(productNameLocalized), HTMLHelper.HTMLEncode(si.DisplayName));
                }
            }

            // Init documents control
            docElem.ZeroRowsText = noDataMessage;
            docElem.SiteName     = filterDocuments.SelectedSite;
            docElem.UniGrid.OnBeforeDataReload += UniGrid_OnBeforeDataReload;
            docElem.UniGrid.OnAfterDataReload  += UniGrid_OnAfterDataReload;
        }
    }
Esempio n. 11
0
    protected void RemoveTaxClassFromProduct()
    {
        // Prepare the parameters
        //  string where = "SKUName LIKE N'MyNew%'";
        SKUInfo product = null;

        // Get the tax class
        TaxClassInfo taxClass = TaxClassInfoProvider.GetTaxClassInfo("VAT", SiteContext.CurrentSiteName);
        // TaxClassInfo taxClass1 = TaxClassInfoProvider.GetTaxClassInfo("VAT", CMSContext.CurrentSiteName);

        // Get the product
        DataSet products = SKUInfoProvider.GetSKUs(null, null);

        if (!DataHelper.DataSourceIsEmpty(products))
        {
            // product = new SKUInfo(products.Tables[0].Rows[0]);
            // }
            int nb = products.Tables[0].Rows.Count;
            for (int i = 0; i < nb; i++)
            {
                DataRow row = products.Tables[0].Rows[i];
                product = new SKUInfo(row);
                if ((product != null) && (taxClass != null))
                {
                    // Get the tax class added to product
                    SKUTaxClassInfo skuTaxClass = SKUTaxClassInfoProvider.GetSKUTaxClassInfo(taxClass.TaxClassID, product.SKUID);

                    // Remove tax class from product
                    SKUTaxClassInfoProvider.DeleteSKUTaxClassInfo(skuTaxClass);
                }


                // }
            }
        }
    }
Esempio n. 12
0
    protected void ugVariants_OnAction(string actionName, object actionArgument)
    {
        int variantID = ValidationHelper.GetInteger(actionArgument, 0);

        switch (actionName.ToLowerCSafe())
        {
        case "edit":
            string url = "~/CMSModules/Ecommerce/Pages/Tools/Products/Product_Edit_Variant_Edit.aspx";
            url = URLHelper.AddParameterToUrl(url, "variantid", variantID.ToString());
            url = URLHelper.AddParameterToUrl(url, "productId", ProductID.ToString());
            url = URLHelper.AddParameterToUrl(url, "dialog", QueryHelper.GetString("dialog", "0"));
            URLHelper.Redirect(url);
            break;

        case "delete":

            // Check modify permission for parent product
            CheckProductModifyAndRedirect(Product);

            SKUInfo variantInfo = SKUInfoProvider.GetSKUInfo(variantID);

            if (variantInfo == null)
            {
                break;
            }

            // Try to delete variant and display warning in case it was disabled
            if (!DeleteVariant(variantInfo))
            {
                // Inform user that variant was disabled
                ShowWarning(GetString("com.product.edit.disableonevariant"));
            }

            break;
        }
    }
Esempio n. 13
0
    /// <summary>
    /// Adds items to the cart
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void lnkAddToCart_Command(object sender, CommandEventArgs e)
    {
        try
        {
            ProductSKUID      = ValidationHelper.GetInteger(e.CommandArgument, default(int));
            hdnClickSKU.Value = ProductSKUID.ToString();
            SKUInfo product = SKUInfoProvider.GetSKUInfo(ProductSKUID);
            if (product != null && ProductType == (int)ProductsType.GeneralInventory && (string.IsNullOrWhiteSpace(product.SKUNumber) || product.SKUNumber.Equals("00000")))
            {
                Response.Cookies["status"].Value    = QueryStringStatus.InvalidProduct;
                Response.Cookies["status"].HttpOnly = false;
                return;
            }
            dialog_Add_To_Cart.Attributes.Add("class", "dialog active");
            btnClose.InnerText  = CartCloseText;
            lblPopUpHeader.Text = ResHelper.GetString("KDA.AddToCart.Popup.HeaderText");
            var hasBusinessUnit = CheckPersonHasBusinessUnit();
            if (!DataHelper.DataSourceIsEmpty(product))
            {
                switch (ProductType)
                {
                case (int)ProductsType.GeneralInventory:
                    BindGeneralInventory(product, hasBusinessUnit);
                    break;

                case (int)ProductsType.PreBuy:
                    BindPreBuy(product, hasBusinessUnit);
                    break;
                }
            }
        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("Add items to cart", "lnkAddToCart_Click()", ex, CurrentSite.SiteID, ex.Message);
        }
    }
Esempio n. 14
0
        /// <summary>
        /// Loads data (SKU options) to the selection control.
        /// </summary>
        private void LoadSKUOptions()
        {
            // Only for none-text types
            if (this.SelectionControl != null)
            {
                // Bind data
                DataSet ds = SKUInfoProvider.GetSKUOptions(this.OptionCategoryId, true);

                if (this.SelectionControl is TextBoxWithLabel)
                {
                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        DataRow dr = ds.Tables[0].Rows[0];
                        TextOptionSKUID = ValidationHelper.GetInteger(ds.Tables[0].Rows[0]["SKUID"], 0);

                        if (this.OptionCategory.CategoryDisplayPrice)
                        {
                            TextBoxWithLabel tb = this.SelectionControl as TextBoxWithLabel;
                            tb.LabelText = GetPrice(dr);
                        }
                    }
                }
                else
                {
                    ((ListControl)this.SelectionControl).DataSource = ds;
                    this.SelectionControl.DataBind();

                    // Add '(none)' record when it is allowed
                    if ((this.OptionCategory != null) && (this.OptionCategory.CategoryDefaultRecord != ""))
                    {
                        ListItem noneRecord = new ListItem(this.OptionCategory.CategoryDefaultRecord, "0");
                        ((ListControl)this.SelectionControl).Items.Insert(0, noneRecord);
                    }
                }
            }
        }
Esempio n. 15
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Set help topic
        CurrentMaster.HeaderActions.HelpTopicName = "CMS_Ecommerce_Products_TaxClasses";

        if (Node != null)
        {
            sku = SKUInfoProvider.GetSKUInfo(Node.NodeSKUID);

            EditedObject = sku;

            if (sku != null)
            {
                // Check site ID
                CheckProductSiteID(sku.SKUSiteID);

                taxForm.ProductID = sku.SKUID;
                taxForm.UniSelector.OnSelectionChanged += UniSelector_OnSelectionChanged;
            }
        }

        // Mark selected tab
        UIContext.ProductTab = ProductTabEnum.TaxClasses;
    }
Esempio n. 16
0
 protected void btnUpdateCRN_Click(object sender, EventArgs e)
 {
     try
     {
         int rCount   = 0;
         var products = SKUInfoProvider.GetSKUs()
                        .WhereEquals("SKUSiteID", SiteContext.CurrentSiteID);
         foreach (SKUInfo modifyProduct in products)
         {
             if (String.IsNullOrEmpty(modifyProduct.GetValue("SKUProductCustomerReferenceNumber", string.Empty)))
             {
                 modifyProduct.SetValue("SKUProductCustomerReferenceNumber", modifyProduct.SKUNumber);
                 SKUInfoProvider.SetSKUInfo(modifyProduct);
                 rCount++;
             }
         }
         EventLogProvider.LogEvent(EventType.INFORMATION, "SKU Update", "UPDATECRN", eventDescription: "Update CRN with SKU");
         lblUpdatedCRN.Text = string.Format("{0} Records moved to CRN", rCount);
     }
     catch (Exception ex)
     {
         EventLogProvider.LogException("ProductsSKUUpdate", "UpdateCRNRecords", ex, CurrentSite.SiteID, ex.Message);
     }
 }
Esempio n. 17
0
    protected void selectProductTypeElem_OnSelectionChanged(object sender, EventArgs e)
    {
        // Show product type specific properties
        switch (SKUInfoProvider.GetSKUProductTypeEnum((string)this.selectProductTypeElem.Value))
        {
        case SKUProductTypeEnum.Product:
            this.typeSpecificOptionsElem.ActiveViewIndex = -1;
            break;

        case SKUProductTypeEnum.Membership:
            this.typeSpecificOptionsElem.SetActiveView(this.membershipViewElem);
            break;

        case SKUProductTypeEnum.EProduct:
            this.typeSpecificOptionsElem.SetActiveView(this.eProductViewElem);
            break;

        case SKUProductTypeEnum.Donation:
            this.typeSpecificOptionsElem.SetActiveView(this.donationViewElem);
            break;

        case SKUProductTypeEnum.Bundle:
            this.typeSpecificOptionsElem.SetActiveView(this.bundleViewElem);
            this.bundleElem.ReloadRequired = true;
            break;
        }

        // If data was not reloaded recently
        if (!ValidationHelper.GetBoolean(this.ViewState["DataReloaded"], false))
        {
            this.LoadDefaults();
        }

        // Clear data reloaded flag
        this.ViewState["DataReloaded"] = false;
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Get product name ane option category ID
        productId = QueryHelper.GetInteger("productId", 0);
        if (productId > 0)
        {
            SKUInfo productInfoObj = SKUInfoProvider.GetSKUInfo(productId);
            if (productInfoObj != null)
            {
                productName      = ResHelper.LocalizeString(productInfoObj.SKUName);
                optionCategoryId = productInfoObj.SKUOptionCategoryID;
                siteId           = productInfoObj.SKUSiteID;

                // Check if edited object belongs to configured site
                CheckEditedObjectSiteID(siteId);
            }
        }

        this.dialogMode = QueryHelper.GetBoolean("dialogmode", false);

        AddMenuButtonSelectScript("Products", "");
    }
        /// <summary>
        /// If COM_SKU is empty or has less than 3 records (SKUs), creates up to 3 sample SKUs.
        /// </summary>
        public ActionResult CreateSampleSKUs()
        {
            var SKUIDs = GetRelevantSKUIDs();

            if (SKUIDs.Count < 3)
            {
                for (int i = 0; i < (3 - SKUIDs.Count); i++)
                {
                    SKUInfoProvider.SetSKUInfo(new SKUInfo()
                    {
                        SKUName             = "SampleProduct No. " + (i + 1),
                        SKUDescription      = "This is a sample product for MVC Learning Kit.",
                        SKUShortDescription = "LearningKit_SampleData",
                        SKUPrice            = 15.99m + new Random().Next(1, 25),
                        SKUSiteID           = SiteContext.CurrentSiteID,
                        SKUEnabled          = true,
                        SKUTrackInventory   = TrackInventoryTypeEnum.ByProduct,
                        SKUAvailableItems   = 100
                    });
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 20
0
    protected void editOptionCategory_OnAfterSave(object sender, EventArgs e)
    {
        if (EditedCategory == null)
        {
            EditedObject = null;
            return;
        }

        // New option category
        if (!Editing)
        {
            // For new TEXT option category create text option
            if (SelectedCategoryType == OptionCategoryTypeEnum.Text)
            {
                CreateTextOption();
            }

            // Assign option category to product
            if (ParentProduct != null)
            {
                SKUOptionCategoryInfo.Provider.Add(EditedCategory.CategoryID, ParentProduct.SKUID);
            }

            // Redirect from new form dialog to option category edit.
            string query = QueryHelper.BuildQuery("saved", "1", "productid", ProductID.ToString(), "siteid", CategorySiteID.ToString());
            if (ParentProduct == null)
            {
                URLHelper.Redirect(UIContextHelper.GetElementUrl(ModuleName.ECOMMERCE, "EditOptionCategory", false, EditedCategory.CategoryID, query));
            }
            else
            {
                URLHelper.Redirect(ApplicationUrlHelper.GetElementDialogUrl(ModuleName.ECOMMERCE, "EditProductOptionCategory", EditedCategory.CategoryID, query));
            }
        }

        if (Editing)
        {
            // Refresh breadcrumbs
            var append = EditedCategory.IsGlobal ? " " + GetString("general.global") : "";
            ScriptHelper.RefreshTabHeader(Page, EditedCategory.CategoryDisplayName + append);

            // Category options
            DataSet options = SKUInfoProvider.GetSKUOptions(EditedCategory.CategoryID, false);

            // Option category type may be changed during editing and additional action is required
            switch (SelectedAdditionalAction)
            {
            case AdditionalActionEnum.DeleteOptionsAndCreateTextOption:
                DestroyOptions(options);
                CreateTextOption();

                break;

            case AdditionalActionEnum.DeleteTextOption:
                DestroyOptions(options);
                CategoryHasOptions = false;

                break;

            case AdditionalActionEnum.ConvertAttributeToProduct:
                ChangeAttributeToProduct(options);

                break;

            case AdditionalActionEnum.ConvertProductToAttribute:
                ChangeProductToAttribute(options);

                break;

            case AdditionalActionEnum.None:

                break;
            }

            editOptionCategory.SubmitButton.OnClientClick = "";
        }
    }
Esempio n. 21
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            currentUser = MembershipContext.AuthenticatedUser;

            if (AuthenticationHelper.IsAuthenticated())
            {
                // Control initialization
                lblTitle.Text    = GetString("Ecommerce.Wishlist.Title");
                btnContinue.Text = GetString("Ecommerce.Wishlist.btnContinue");

                mSKUId      = QueryHelper.GetInteger("productID", 0);
                currentSite = SiteContext.CurrentSite;

                // Set repeater transformation
                repeater.TransformationName = TransformationName;
                repeater.ItemSeparator      = ItemSeparator;

                if ((currentUser != null) && (currentSite != null))
                {
                    if ((!RequestHelper.IsPostBack()) && (mSKUId > 0))
                    {
                        int addSKUId = mSKUId;

                        // Get added SKU info object from database
                        SKUInfo skuObj = SKUInfoProvider.GetSKUInfo(addSKUId);
                        if (skuObj != null)
                        {
                            // Can not add option as a product
                            if (skuObj.SKUOptionCategoryID > 0)
                            {
                                addSKUId = 0;
                            }
                            else if (!skuObj.IsGlobal)
                            {
                                // Site specific product must belong to the current site
                                if (skuObj.SKUSiteID != currentSite.SiteID)
                                {
                                    addSKUId = 0;
                                }
                            }
                            else
                            {
                                // Global products must be allowed when adding global product
                                if (!ECommerceSettings.AllowGlobalProducts(currentSite.SiteName))
                                {
                                    addSKUId = 0;
                                }
                            }
                        }

                        if (addSKUId > 0)
                        {
                            // Add specified product to the user's wishlist
                            WishlistItemInfoProvider.AddSKUToWishlist(currentUser.UserID, addSKUId, currentSite.SiteID);
                            LogProductAddedToWLActivity(addSKUId, ResHelper.LocalizeString(skuObj.SKUName));
                        }
                    }

                    if (mSKUId > 0)
                    {
                        // Remove product parameter from URL to avoid adding it next time
                        string newUrl = URLHelper.RemoveParameterFromUrl(RequestContext.CurrentURL, "productID");
                        URLHelper.Redirect(newUrl);
                    }
                }
            }
            else
            {
                // Hide control if current user is not authenticated
                Visible = false;
            }
        }
    }
    private void grid_OnAction(string actionName, object actionArgument)
    {
        if (string.IsNullOrEmpty(actionName))
        {
            return;
        }

        int skuId = ValidationHelper.GetInteger(actionArgument, 0);

        switch (actionName.ToLowerInvariant())
        {
        case "edit":
            // Show product tabs for type Products, otherwise show only general tab
        {
            var url = UIContextHelper.GetElementUrl(ModuleName.ECOMMERCE, "ProductOptions.Options.General");
            url = URLHelper.AddParameterToUrl(url, "displaytitle", "false");
            url = URLHelper.AddParameterToUrl(url, "productId", skuId.ToString());
            url = URLHelper.AddParameterToUrl(url, "categoryid", categoryId.ToString());
            url = URLHelper.AddParameterToUrl(url, "siteId", categoryObj.CategorySiteID.ToString());
            url = URLHelper.AddParameterToUrl(url, "objectid", skuId.ToString());
            // To be able to hide tax class tab for attribute and text option
            url = URLHelper.AddParameterToUrl(url, "parentobjectid", categoryId.ToString());

            // Add parent product id
            if (parentProductId > 0)
            {
                url += "&parentProductId=" + parentProductId;
            }

            if (QueryHelper.GetBoolean("isindialog", false))
            {
                url = URLHelper.AddParameterToUrl(url, "isindialog", "1");
                url = ApplicationUrlHelper.AppendDialogHash(url);
            }

            URLHelper.Redirect(url);
        }
        break;

        case "delete":
            // Check permissions
            CheckModifyPermission();

            // Check dependencies
            if (SKUInfoProvider.CheckDependencies(skuId))
            {
                // Show error message
                ShowError(EcommerceUIHelper.GetDependencyMessage(SKUInfoProvider.GetSKUInfo(skuId)));

                return;
            }

            // Check if same variant is defined by this option
            DataSet variants = VariantOptionInfoProvider.GetVariantOptions()
                               .TopN(1)
                               .Columns("VariantSKUID")
                               .WhereEquals("OptionSKUID", skuId);

            if (!DataHelper.DataSourceIsEmpty(variants))
            {
                // Option is used in some variant
                ShowError(GetString("com.option.usedinvariant"));

                return;
            }

            SKUInfoProvider.DeleteSKUInfo(skuId);
            ugOptions.ReloadData();

            break;
        }
    }
Esempio n. 23
0
 /// <summary>
 /// Adds item to product type dropdown list.
 /// </summary>
 /// <param name="productTypeName">Product type name resource string</param>
 /// <param name="productType">Product type</param>
 private void AddProductType(string productTypeName, SKUProductTypeEnum productType)
 {
     this.drpProductType.Items.Add(new ListItem(this.GetString(productTypeName), SKUInfoProvider.GetSKUProductTypeString(productType)));
 }
    /// <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>
    /// Handles the OptionCategoryGrid's OnAction event.
    /// </summary>
    /// <param name="actionName">Name of item (button) that throws event</param>
    /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param>
    protected void OptionCategoryGrid_OnAction(string actionName, object actionArgument)
    {
        int categoryId = ValidationHelper.GetInteger(actionArgument, 0);

        switch (actionName.ToLowerCSafe())
        {
        case "edit":
            URLHelper.Redirect(UIContextHelper.GetElementUrl(ModuleName.ECOMMERCE, "EditOptionCategory", false, categoryId));

            break;

        case "delete":

            OptionCategoryInfo categoryObj = OptionCategoryInfoProvider.GetOptionCategoryInfo(categoryId);

            if (categoryObj == null)
            {
                break;
            }

            // Check permissions
            if (!ECommerceContext.IsUserAuthorizedToModifyOptionCategory(categoryObj))
            {
                // Check module permissions
                if (categoryObj.CategoryIsGlobal)
                {
                    RedirectToAccessDenied(ModuleName.ECOMMERCE, EcommercePermissions.ECOMMERCE_MODIFYGLOBAL);
                }
                else
                {
                    RedirectToAccessDenied(ModuleName.ECOMMERCE, "EcommerceModify OR ModifyProducts");
                }
            }

            // Check category dependencies
            if (categoryObj.Generalized.CheckDependencies())
            {
                // Show error message
                ShowError(EcommerceUIHelper.GetDependencyMessage(categoryObj));
                return;
            }

            DataSet options = SKUInfoProvider.GetSKUOptions(categoryId, false);

            // Check option category options dependencies
            if (!DataHelper.DataSourceIsEmpty(options))
            {
                // Check if some attribute option is not used in variant
                if (categoryObj.CategoryType == OptionCategoryTypeEnum.Attribute)
                {
                    var optionIds = DataHelper.GetIntegerValues(options.Tables[0], "SKUID");

                    // Check if some variant is defined by this option
                    DataSet variants = VariantOptionInfoProvider.GetVariantOptions()
                                       .TopN(1)
                                       .Column("VariantSKUID")
                                       .WhereIn("OptionSKUID", optionIds);

                    if (!DataHelper.DataSourceIsEmpty(variants))
                    {
                        // Option is used in some variant
                        ShowError(GetString("com.option.categoryoptiosusedinvariant"));

                        return;
                    }
                }

                // Check other dependencies (shopping cart, order)
                foreach (DataRow option in options.Tables[0].Rows)
                {
                    var skuid = ValidationHelper.GetInteger(option["SKUID"], 0);
                    var sku   = SKUInfoProvider.GetSKUInfo(skuid);

                    if (SKUInfoProvider.CheckDependencies(skuid))
                    {
                        // Show error message
                        ShowError(EcommerceUIHelper.GetDependencyMessage(sku));

                        return;
                    }
                }
            }

            // Delete option category from database
            OptionCategoryInfoProvider.DeleteOptionCategoryInfo(categoryObj);

            break;
        }
    }
    private void gridData_OnAction(string actionName, object actionArgument)
    {
        int argument = ValidationHelper.GetInteger(actionArgument, 0);

        actionName = actionName.ToLowerCSafe();

        switch (actionName)
        {
        case "edit":
            string url = null;

            if (NodeID > 0)
            {
                url = "Product_Edit_Frameset.aspx?sectionId=" + NodeID + "&nodeId=" + argument + "&culture=" + CultureCode;
            }
            else
            {
                url = "Product_Edit_Frameset.aspx?productid=" + argument;
            }

            URLHelper.Redirect(url);

            break;

        case "delete":
            if (NodeID > 0)
            {
                URLHelper.Redirect("Product_Section.aspx?action=delete&nodeId=" + argument);
            }
            else
            {
                SKUInfo skuObj = SKUInfoProvider.GetSKUInfo(argument);

                // Check module permissions
                if (!ECommerceContext.IsUserAuthorizedToModifySKU(skuObj))
                {
                    if (skuObj.IsGlobal)
                    {
                        RedirectToAccessDenied("CMS.Ecommerce", "EcommerceGlobalModify");
                    }
                    else
                    {
                        RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyProducts");
                    }
                }

                // Check dependencies
                if (SKUInfoProvider.CheckDependencies(argument))
                {
                    // Show error message
                    ShowError(GetString("Ecommerce.DeleteDisabled"));

                    return;
                }

                SKUInfoProvider.DeleteSKUInfo(skuObj);
            }

            break;
        }
    }
    private void btnAddProduct_Click(object sender, EventArgs e)
    {
        // Do not add item if order is paid
        if (OrderIsPaid)
        {
            return;
        }

        // Get strings with productIDs and quantities separated by ';'
        string productIDs = ValidationHelper.GetString(hidProductID.Value, "");
        string quantities = ValidationHelper.GetString(hidQuantity.Value, "");
        string options    = ValidationHelper.GetString(hidOptions.Value, "");

        // Add new products to shopping cart
        if ((productIDs != "") && (quantities != ""))
        {
            int[] arrID      = ValidationHelper.GetIntegers(productIDs.TrimEnd(';').Split(';'), 0);
            int[] arrQuant   = ValidationHelper.GetIntegers(quantities.TrimEnd(';').Split(';'), 0);
            int[] intOptions = ValidationHelper.GetIntegers(options.Split(','), 0);

            // Check site binding
            if (!CheckSiteBinding(arrID) || !CheckSiteBinding(intOptions))
            {
                return;
            }

            lblError.Text = "";

            for (int i = 0; i < arrID.Length; i++)
            {
                int skuId = arrID[i];

                SKUInfo skuInfo = SKUInfoProvider.GetSKUInfo(skuId);
                if ((skuInfo != null) && !skuInfo.IsProductOption)
                {
                    int quantity = arrQuant[i];

                    ShoppingCartItemParameters cartItemParams = new ShoppingCartItemParameters(skuId, quantity, intOptions);

                    // Add product to the shopping cart
                    ShoppingCartInfoProvider.SetShoppingCartItem(ShoppingCart, cartItemParams);

                    // Log activity
                    if (!ShoppingCartControl.IsInternalOrder)
                    {
                        ShoppingCartControl.TrackActivityProductAddedToShoppingCart(skuInfo, quantity);
                    }

                    // Show empty button
                    btnEmpty.Visible = true;
                }
            }
        }

        // Invalidate values
        hidProductID.Value = "";
        hidOptions.Value   = "";
        hidQuantity.Value  = "";

        ShoppingCart.Evaluate();

        // Update values in table
        btnUpdate_Click(btnAddProduct, e);

        if (ShoppingCart.ContentTable.Any())
        {
            // Inventory should be checked
            checkInventory = true;
        }
        else
        {
            // Hide cart content when empty
            HideCartContent();
        }
    }
Esempio n. 28
0
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Check module permissions
        bool global = (editedSiteId <= 0);

        if (!ECommerceContext.IsUserAuthorizedToModifyOptionCategory(global))
        {
            // Check module permissions
            if (global)
            {
                RedirectToAccessDenied("CMS.Ecommerce", "EcommerceGlobalModify");
            }
            else
            {
                RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyProducts");
            }
        }

        // Check input value from textboxs
        string errorMessage = new Validator().NotEmpty(txtDisplayName.Text, GetString("general.requiresdisplayname"))
                              .NotEmpty(txtCategoryName.Text, GetString("general.requirescodename"))
                              .IsIdentificator(txtCategoryName.Text, GetString("optioncategory_new.errorNotIdentificator")).Result;

        if (errorMessage == "")
        {
            // Category code name must be unique
            OptionCategoryInfo optionCategoryObj = null;
            string             siteWhere         = (ConfiguredSiteID > 0) ? " AND (CategorySiteID = " + ConfiguredSiteID + " OR CategorySiteID IS NULL)" : "";
            DataSet            ds = OptionCategoryInfoProvider.GetOptionCategories("CategoryName = '" + txtCategoryName.Text.Trim().Replace("'", "''") + "'" + siteWhere, null, 1, null);
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                optionCategoryObj = new OptionCategoryInfo(ds.Tables[0].Rows[0]);
            }

            // If category code name value is unique
            if (optionCategoryObj == null)
            {
                // Create, fill and set OptionCategoryInfo object
                optionCategoryObj = new OptionCategoryInfo();
                optionCategoryObj.CategoryDisplayName    = txtDisplayName.Text.Trim();
                optionCategoryObj.CategoryName           = txtCategoryName.Text.Trim();
                optionCategoryObj.CategorySelectionType  = radSelection.Checked ? OptionCategorySelectionTypeEnum.Dropdownlist : OptionCategorySelectionTypeEnum.TextBox;
                optionCategoryObj.CategoryEnabled        = true;
                optionCategoryObj.CategoryDefaultRecord  = "";
                optionCategoryObj.CategoryDefaultOptions = "";
                optionCategoryObj.CategorySiteID         = ConfiguredSiteID;

                // Create category and option under transaction
                using (CMSTransactionScope tr = new CMSTransactionScope())
                {
                    OptionCategoryInfoProvider.SetOptionCategoryInfo(optionCategoryObj);

                    if (radText.Checked)
                    {
                        // Create text product option
                        SKUInfo option = new SKUInfo()
                        {
                            SKUOptionCategoryID = optionCategoryObj.CategoryID,
                            SKUProductType      = SKUProductTypeEnum.Text,
                            SKUSiteID           = ConfiguredSiteID,
                            SKUName             = optionCategoryObj.CategoryDisplayName,
                            SKUDepartmentID     = 0,
                            SKUPrice            = 0,
                            SKUNeedsShipping    = false,
                            SKUWeight           = 0,
                            SKUEnabled          = true
                        };

                        SKUInfoProvider.SetSKUInfo(option);
                    }

                    // Commit a transaction
                    tr.Commit();
                }

                URLHelper.Redirect("OptionCategory_Edit.aspx?categoryId=" + Convert.ToString(optionCategoryObj.CategoryID) + "&saved=1&siteId=" + SiteID);
            }
            else
            {
                lblError.Visible = true;
                lblError.Text    = GetString("optioncategory_new.errorExistingCodeName");
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text    = errorMessage;
        }
    }
Esempio n. 29
0
    /// <summary>
    /// Deletes variants is asynchronous control.
    /// </summary>
    protected void Delete(object parameters)
    {
        bool variantWasDisabled = false;

        try
        {
            // Use special action contexts to turn off unnecessary actions
            using (ECommerceActionContext eCommerceContext = new ECommerceActionContext())
            {
                eCommerceContext.TouchParent            = false;
                eCommerceContext.SetLowestPriceToParent = false;

                // Delete all variants
                if ((WhatEnum)ValidationHelper.GetInteger(drpWhat.SelectedIndex, -1) == WhatEnum.AllVariants)
                {
                    var variants = VariantHelper.GetVariants(ProductID);

                    foreach (SKUInfo variant in variants)
                    {
                        // Set flag when variant was disabled due to dependencies
                        variantWasDisabled |= !DeleteVariant(variant);
                    }
                }
                // Delete selected variants
                else
                {
                    List <string> variantsToDelete = ugVariants.SelectedItems;

                    foreach (string variantId in variantsToDelete)
                    {
                        var variantInfo = SKUInfoProvider.GetSKUInfo(ValidationHelper.GetInteger(variantId, 0));

                        if ((variantInfo != null) && (variantInfo.SKUParentSKUID == ProductID))
                        {
                            // Set flag when variant was disabled due to dependencies
                            variantWasDisabled |= !DeleteVariant(variantInfo);
                        }
                    }
                }
            }

            // Save variant to update parent SKULastModified a SKUPrice properties
            DataSet productVariants = VariantHelper.GetVariants(ProductID);
            if (!DataHelper.DataSourceIsEmpty(productVariants))
            {
                SKUInfo variantInfo = new SKUInfo(productVariants.Tables[0].Rows[0]);
                variantInfo.Generalized.SetObject();
            }
        }
        catch (Exception ex)
        {
            CurrentError = GetString("com.product.deleteerror");
            EventLogProvider.LogException("Variant listing", "DELETEVARIANT", ex);
        }

        ugVariants.ClearSelectedItems();

        if (variantWasDisabled)
        {
            CurrentWarning = GetString("com.product.edit.disablevariant");
        }
    }
Esempio n. 30
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Set correct culture
        SetLiveCulture();

        // Initialization
        productId   = QueryHelper.GetInteger(PRODUCT_ID, 0);
        skuGuid     = QueryHelper.GetGuid(SKU_GUID, Guid.Empty);
        currentSite = SiteContext.CurrentSite;

        var skuObj = SKUInfoProvider.GetSKUInfo(productId);

        if ((skuObj != null) && skuObj.IsProductVariant)
        {
            // Get parent product of variant
            var parent = skuObj.Parent as SKUInfo;

            if (parent != null)
            {
                productId = parent.SKUID;
                skuGuid   = parent.SKUGUID;
            }
        }

        string where = null;
        if (productId > 0)
        {
            where = "NodeSKUID = " + productId;
        }
        else if (skuGuid != Guid.Empty)
        {
            where = "SKUGUID = '" + skuGuid + "'";
        }

        if ((where != null) && (currentSite != null))
        {
            var node = DocumentHelper.GetDocuments()
                       .Path("/", PathTypeEnum.Section)
                       .Culture(CultureInfo.CurrentCulture.Name)
                       .CombineWithDefaultCulture()
                       .Where(where)
                       .Published()
                       .FirstObject;

            if (node != null)
            {
                // Get specified product url
                url = DocumentURLProvider.GetUrl(node);
            }
        }

        if ((url != string.Empty) && (currentSite != null))
        {
            url = AppendQueryStringParameters(url);
            // Redirect to specified product
            URLHelper.Redirect(UrlResolver.ResolveUrl(url));
        }
        else
        {
            // Display error message
            lblInfo.Visible = true;
            lblInfo.Text    = GetString("GetProduct.NotFound");
        }
    }