Пример #1
2
        private object DummyEcommerceMethod2()
        {
            SKUInfo          sku             = null;
            IOrderRepository orderRepository = null;
            int orderId = 0;

            //DocSection:DisplayCatalogDiscounts
            // Initializes the needed services
            ShoppingService shoppingService = new ShoppingService();
            PricingService  pricingService  = new PricingService();

            // Gets the current shopping cart
            ShoppingCart shoppingCart = shoppingService.GetCurrentShoppingCart();

            // Calculates prices for the specified product
            ProductPrice price = pricingService.CalculatePrice(sku, shoppingCart);

            // Gets the catalog discount
            decimal catalogDiscount = price.Discount;
            //EndDocSection:DisplayCatalogDiscounts

            //DocSection:DisplayOrderList
            // Gets the current customer
            Customer currentCustomer = shoppingService.GetCurrentCustomer();

            // If the customer does not exist, returns error 404
            if (currentCustomer == null)
            {
                return(HttpNotFound());
            }

            // Creates a view model representing a collection of the customer's orders
            OrdersViewModel model = new OrdersViewModel()
            {
                Orders = orderRepository.GetByCustomerId(currentCustomer.ID)
            };
            //EndDocSection:DisplayOrderList

            //DocSection:ReorderExistingOrder
            // Gets the order based on its ID
            Order order = orderRepository.GetById(orderId);

            // Gets the current visitor's shopping cart
            ShoppingCart cart = shoppingService.GetCurrentShoppingCart();

            // Loops through the items in the order and adds them to the shopping cart
            foreach (OrderItem item in order.OrderItems)
            {
                cart.AddItem(item.SKUID, item.Units);
            }

            // Evaluates the shopping cart
            cart.Evaluate();

            // Saves the shopping cart
            cart.Save();
            //EndDocSection:ReorderExistingOrder

            return(null);
        }
Пример #2
0
        private static void SetPackageLineItems(RateRequest request, Delivery delivery)
        {
            int i = 1;
            List <RequestedPackageLineItem> lstItems = new List <RequestedPackageLineItem>();

            foreach (DeliveryItem item in delivery.Items)
            {
                SKUInfo sku = item.Product;
                RequestedPackageLineItem ritem = new RequestedPackageLineItem();
                ritem.SequenceNumber    = i.ToString(); // package sequence number
                ritem.GroupPackageCount = i.ToString();
                // package weight
                ritem.Weight                = new Weight();
                ritem.Weight.Units          = WeightUnits.LB;
                ritem.Weight.UnitsSpecified = true;
                ritem.Weight.Value          = ValidationHelper.GetDecimal(sku.SKUWeight, 1) * item.Amount;
                ritem.Weight.ValueSpecified = true;
                // package dimensions
                ritem.Dimensions = new Dimensions();
                ritem.Dimensions.UnitsSpecified = false;
                lstItems.Add(ritem);
                i += 1;
            }
            request.RequestedShipment.RequestedPackageLineItems = lstItems.ToArray();
        }
Пример #3
0
    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (plcSelector.Visible)
        {
            // Get product name and price
            SKUInfo skuObj  = SKUInfoProvider.GetSKUInfo(this.SKUID);
            string  skuName = "";

            if (skuObj != null)
            {
                lblPriceValue.Text = SKUInfoProvider.GetSKUFormattedPrice(skuObj, this.ShoppingCartObj, true, false);
                skuName            = ResHelper.LocalizeString(skuObj.SKUName);
            }

            // Set SKU name label
            this.lblSKUName.Text = skuName;

            // Show info text
            this.lblPrice.Text = GetString("Order_Edit_AddItems.UnitPrice");

            // Initializes page title control
            string[,] tabs = new string[2, 3];
            tabs[0, 0]     = GetString("Order_Edit_AddItems.Products");
            tabs[0, 1]     = "~/CMSModules/Ecommerce/Pages/Tools/Orders/Order_Edit_AddItems.aspx?cart=" + HTMLHelper.HTMLEncode(QueryHelper.GetString("cart", ""));
            tabs[0, 2]     = "";
            tabs[1, 0]     = skuName;
            tabs[1, 1]     = "";
            tabs[1, 2]     = "";
            PageTitleAddItems.Breadcrumbs = tabs;
        }
    }
Пример #4
0
 /// <summary>
 /// Removing Shopping Cart and cart items by cart id
 /// </summary>
 /// <param name="shoppingCartID"></param>
 private void RemovingProductFromShoppingCart(SKUInfo product, int shoppingCartID)
 {
     try
     {
         if (!DataHelper.DataSourceIsEmpty(product))
         {
             ShoppingCartItemInfo item = null;
             ShoppingCartInfo     cart = ShoppingCartInfoProvider.GetShoppingCartInfo(shoppingCartID);
             cart.User = CurrentUser;
             item      = cart.CartItems.Where(g => g.SKUID == product.SKUID).FirstOrDefault();
             if (!DataHelper.DataSourceIsEmpty(item))
             {
                 ShoppingCartInfoProvider.RemoveShoppingCartItem(cart, item.CartItemID);
                 ShoppingCartItemInfoProvider.DeleteShoppingCartItemInfo(item);
                 if (cart.CartItems.Count == 0)
                 {
                     ShoppingCartInfoProvider.DeleteShoppingCartInfo(shoppingCartID);
                 }
                 cart.InvalidateCalculations();
             }
         }
     }
     catch (Exception ex)
     {
         EventLogProvider.LogException("CustomerCartOperations.ascx.cs", "RemovingProductFromShoppingCart()", ex);
     }
 }
Пример #5
0
 /// <summary>
 /// Cart operations based on the values
 /// </summary>
 /// <param name="cartID">shoppingcart id</param>
 /// <param name="quantity">units placing</param>
 /// <param name="productInfo">skuinfo object</param>
 /// <param name="addressID">distributor addressid</param>
 private void CartProcessOperations(int cartID, int quantity, SKUInfo productInfo, int addressID)
 {
     try
     {
         if (!DataHelper.DataSourceIsEmpty(productInfo) && addressID != default(int))
         {
             if (cartID == default(int) && quantity > 0)
             {
                 CreateShoppingCartByCustomer(productInfo, addressID, quantity);
                 BindCustomersList(ProductSKUID);
             }
             else if (cartID > 0 && quantity > 0)
             {
                 Updatingtheunitcountofcartitem(productInfo, cartID, quantity, addressID);
                 BindCustomersList(ProductSKUID);
             }
             else if (cartID > 0 && quantity == 0)
             {
                 RemovingProductFromShoppingCart(productInfo, cartID);
                 BindCustomersList(ProductSKUID);
             }
         }
     }
     catch (Exception ex)
     {
         EventLogProvider.LogException("CustomerCartOperations.ascx.cs", "CartProcess()", ex);
     }
 }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Get product name ane option category ID
        if (ProductID > 0)
        {
            sku = SKUInfoProvider.GetSKUInfo(ProductID);
            if (sku != null)
            {
                productName      = ResHelper.LocalizeString(sku.SKUName);
                optionCategoryId = sku.SKUOptionCategoryID;
                siteId           = sku.SKUSiteID;

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

        dialogMode = QueryHelper.GetBoolean("dialogmode", false);
        nodeId     = QueryHelper.GetInteger("nodeId", 0);

        // Display tabs separator
        CurrentMaster.PanelSeparator.Visible = true;

        AddMenuButtonSelectScript("Products", string.Empty);
    }
    /// <summary>
    /// Recalculates and formats price.
    /// </summary>
    /// <param name="row">Data row to create price label for.</param>
    private string GetPrice(DataRow row)
    {
        var sku = new SKUInfo(row);

        // Get site main currency
        var currency = CurrencyInfoProvider.GetMainCurrency(sku.SKUSiteID);

        // Get product price
        var price = sku.SKUPrice;

        if (price != 0)
        {
            string prefix = (price >= 0) ? "+ " : "- ";
            price = Math.Abs(price);

            // Round price
            price = CurrencyInfoProvider.RoundTo(price, currency);

            // Format price
            string formattedPrice = CurrencyInfoProvider.GetFormattedPrice(price, currency);

            return(" (" + prefix + formattedPrice + ")");
        }

        return(string.Empty);
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Get product name ane option category ID
        if (ProductID > 0)
        {
            sku = SKUInfoProvider.GetSKUInfo(ProductID);
            if (sku != null)
            {
                productName = ResHelper.LocalizeString(sku.SKUName);
                optionCategoryId = sku.SKUOptionCategoryID;
                siteId = sku.SKUSiteID;

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

        dialogMode = QueryHelper.GetBoolean("dialogmode", false);
        nodeId = QueryHelper.GetInteger("nodeId", 0);

        // Display tabs separator
        CurrentMaster.PanelSeparator.Visible = true;

        AddMenuButtonSelectScript("Products", string.Empty);
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        SKUInfo sku = SKUInfoProvider.GetSKUInfo(ProductID);

        if (sku != null)
        {
            CheckEditedObjectSiteID(sku.SKUSiteID);
        }

        if (IsProductOption)
        {
            // Check UI personalization for product option
            if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Ecommerce", "ProductOptions.Options.General"))
            {
                RedirectToCMSDeskUIElementAccessDenied("CMS.Ecommerce", "ProductOptions.Options.General");
            }
        }
        else
        {
            // Check UI personalization for product
            if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Ecommerce", "Products.General"))
            {
                RedirectToCMSDeskUIElementAccessDenied("CMS.Ecommerce", "Products.General");
            }
        }
    }
Пример #10
0
        public void SetUpOptionCategories()
        {
            // Create categories
            categorySize = Factory.NewOptionCategory("Size", OptionCategoryTypeEnum.Attribute);
            categorySize.Insert();

            categoryColor = Factory.NewOptionCategory("Color", OptionCategoryTypeEnum.Attribute);
            categoryColor.Insert();

            // Create parent product
            skuWithVariants = Factory.NewSKU("Hammer");
            skuWithVariants.SKUImagePath = PATH_TO_PRODUCT_IMAGE;
            skuWithVariants.Insert();

            // Assign categories to product
            new SKUOptionCategoryInfo
            {
                AllowAllOptions = true,
                SKUID           = skuWithVariants.SKUID,
                CategoryID      = categorySize.CategoryID,
            }.Insert();

            new SKUOptionCategoryInfo
            {
                AllowAllOptions = true,
                SKUID           = skuWithVariants.SKUID,
                CategoryID      = categoryColor.CategoryID,
            }.Insert();
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Ecommerce", "Products.VolumeDiscounts"))
        {
            RedirectToCMSDeskUIElementAccessDenied("CMS.Ecommerce", "Products.VolumeDiscounts");
        }

        productId = QueryHelper.GetInteger("productId", 0);
        product = SKUInfoProvider.GetSKUInfo(productId);

        EditedObject = product;

        if (product != null)
        {
            // Check site id
            CheckEditedObjectSiteID(product.SKUSiteID);

            // Load product currency
            productCurrency = CurrencyInfoProvider.GetMainCurrency(product.SKUSiteID);
        }

        // Set unigrid properties
        SetUnigridProperties();

        // Initialize the master page elements
        InitializeMasterPage();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        product = SKUInfoProvider.GetSKUInfo(ProductID);

        // Setup help
        object options = new
        {
            helpName = "lnkProductEditHelp",
            helpUrl  = DocumentationHelper.GetDocumentationTopicUrl(HELP_TOPIC_LINK)
        };

        ScriptHelper.RegisterModule(this, "CMS/DialogContextHelpChange", options);

        EditedObject = product;

        if (product != null)
        {
            // Check site id
            CheckEditedObjectSiteID(product.SKUSiteID);

            // Load product currency
            productCurrency = CurrencyInfoProvider.GetMainCurrency(product.SKUSiteID);

            // Display product price
            headProductPriceInfo.Text = string.Format(GetString("com_sku_volume_discount.skupricelabel"), CurrencyInfoProvider.GetFormattedPrice(product.SKUPrice, productCurrency));
        }

        // Set unigrid properties
        SetUnigridProperties();

        // Initialize the master page elements
        InitializeMasterPage();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        product = SKUInfoProvider.GetSKUInfo(ProductID);

        // Mark selected tab
        UIContext.ProductTab = ProductTabEnum.VolumeDiscounts;

        EditedObject = product;

        if (product != null)
        {
            // Check site id
            CheckEditedObjectSiteID(product.SKUSiteID);

            // Load product currency
            productCurrency = CurrencyInfoProvider.GetMainCurrency(product.SKUSiteID);

            // Display product price
            lblProductPrice.Text = CurrencyInfoProvider.GetFormattedPrice(product.SKUPrice, productCurrency);
        }

        // Set unigrid properties
        SetUnigridProperties();

        // Initialize the master page elements
        InitializeMasterPage();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check UI personalization for product / product option separately
        if (QueryHelper.GetInteger("categoryid", 0) > 0)
        {
            if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Ecommerce", "ProductOptions.Options.TaxClasses"))
            {
                RedirectToCMSDeskUIElementAccessDenied("CMS.Ecommerce", "ProductOptions.Options.TaxClasses");
            }
        }
        else
        {
            if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Ecommerce", "Products.TaxClasses"))
            {
                RedirectToCMSDeskUIElementAccessDenied("CMS.Ecommerce", "Products.TaxClasses");
            }
        }

        if (ProductID > 0)
        {
            sku = SKUInfoProvider.GetSKUInfo(ProductID);
            EditedObject = sku;

            if (sku != null)
            {
                // Check products site id
                CheckEditedObjectSiteID(sku.SKUSiteID);

                taxForm.ProductID = ProductID;
                taxForm.UniSelector.OnSelectionChanged += UniSelector_OnSelectionChanged;
            }
        }
    }
Пример #15
0
    /// <summary>
    /// Handles the UniGrid'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 UniGrid_OnAction(string actionName, object actionArgument)
    {
        if (actionName.ToLowerCSafe() == "edit")
        {
            string editUrl = "Product_Edit_VolumeDiscount_Edit.aspx";
            editUrl = URLHelper.AddParameterToUrl(editUrl, "productID", ProductID.ToString());
            editUrl = URLHelper.AddParameterToUrl(editUrl, "volumeDiscountID", Convert.ToString(actionArgument));
            editUrl = URLHelper.AddParameterToUrl(editUrl, "siteId", SiteID.ToString());
            editUrl = URLHelper.AddParameterToUrl(editUrl, "dialog", QueryHelper.GetString("dialog", "0"));

            URLHelper.Redirect(AddNodeIDParameterToUrl(editUrl));
        }
        else if (actionName.ToLowerCSafe() == "delete")
        {
            SKUInfo sku = SKUInfoProvider.GetSKUInfo(ProductID);
            if (sku == null)
            {
                return;
            }

            if (CheckProductModifyAndRedirect(sku))
            {
                // Delete VolumeDiscountInfo object from database
                VolumeDiscountInfoProvider.DeleteVolumeDiscountInfo(Convert.ToInt32(actionArgument));
            }
        }
    }
Пример #16
0
        public JsonResult Variant(int variantID)
        {
            // Gets SKU information based on the variant's ID
            SKUInfo variant = SKUInfoProvider.GetSKUInfo(variantID);

            // If the variant is null, returns null
            if (variant == null)
            {
                return(null);
            }

            // Calculates the price of the variant
            ProductPrice variantPrice = pricingService.CalculatePrice(variant, shoppingService.GetCurrentShoppingCart());

            // Finds out whether the variant is in stock
            bool isInStock = variant.SKUTrackInventory == TrackInventoryTypeEnum.Disabled || variant.SKUAvailableItems > 0;

            // Creates a JSON response for the JavaScript that switches the variants
            var response = new
            {
                totalPrice   = variantPrice.Currency.FormatPrice(variantPrice.Price),
                inStock      = isInStock,
                stockMessage = isInStock ? "Yes" : "No"
            };

            // Returns the response
            return(Json(response));
        }
Пример #17
0
        public JsonResult CheckLimitTimeBuy(string skuIds, string counts)
        {
            string[] strArrays = skuIds.Split(new char[] { ',' });
            string   str       = counts.TrimEnd(new char[] { ',' });

            char[]            chrArray = new char[] { ',' };
            IEnumerable <int> nums1    =
                from t in str.Split(chrArray)
                select int.Parse(t);

            IProductService productService = ServiceHelper.Create <IProductService>();
            int             num3           = 0;
            CartItemModel   cartItemModel  = strArrays.Select <string, CartItemModel>((string item) => {
                SKUInfo sku            = productService.GetSku(item);
                IEnumerable <int> nums = nums1;
                int num  = num3;
                int num1 = num;
                num3     = num + 1;
                int num2 = nums.ElementAt <int>(num1);
                return(new CartItemModel()
                {
                    id = sku.ProductInfo.Id,
                    count = num2
                });
            }).ToList().FirstOrDefault();
            int marketSaleCountForUserId = ServiceHelper.Create <ILimitTimeBuyService>().GetMarketSaleCountForUserId(cartItemModel.id, base.CurrentUser.Id);
            int maxSaleCount             = ServiceHelper.Create <ILimitTimeBuyService>().GetLimitTimeMarketItemByProductId(cartItemModel.id).MaxSaleCount;

            return(Json(new { success = maxSaleCount >= marketSaleCountForUserId + cartItemModel.count, maxSaleCount = maxSaleCount, remain = maxSaleCount - marketSaleCountForUserId }));
        }
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        if (plcSelector.Visible)
        {
            // Remove css class dialog-content-scrollable to turn off position:relative. Our Selector control needs to overflow content container and hide dialog footer with his footer button.
            CurrentMaster.PanelContent.RemoveCssClass("dialog-content-scrollable");
            // Get product name and price
            SKUInfo skuObj  = SKUInfoProvider.GetSKUInfo(SKUID);
            string  skuName = "";

            if (skuObj != null)
            {
                skuName = ResHelper.LocalizeString(skuObj.SKUName);
            }

            // Set SKU name label
            headSKUName.Text = HTMLHelper.HTMLEncode(skuName);

            // Set breadcrumb
            PageBreadcrumbs.AddBreadcrumb(new BreadcrumbItem()
            {
                Text        = GetString("Order_Edit_AddItems.Products"),
                RedirectUrl = ResolveUrl("~/CMSModules/Ecommerce/Pages/Tools/Orders/Order_Edit_AddItems.aspx?cart=" + HTMLHelper.HTMLEncode(QueryHelper.GetString("cart", ""))),
            });

            PageBreadcrumbs.AddBreadcrumb(new BreadcrumbItem()
            {
                Text = skuName
            });
        }
    }
    /// <summary>
    /// Calculate total price with product options prices.
    /// </summary>
    private void CalculateTotalPrice()
    {
        // Add SKU price
        double price = SKUInfoProvider.GetSKUPrice(this.SKU, this.ShoppingCart, true, this.ShowPriceIncludingTax);

        // Add prices of all product options
        List <ShoppingCartItemParameters> optionParams = ProductOptionsParameters;

        foreach (ShoppingCartItemParameters optionParam in optionParams)
        {
            SKUInfo sku = null;

            if (this.mProductOptions.Contains(optionParam.SKUID))
            {
                // Get option SKU data
                sku = (SKUInfo)this.mProductOptions[optionParam.SKUID];

                // Add option price
                price += SKUInfoProvider.GetSKUPrice(sku, this.ShoppingCart, true, this.ShowPriceIncludingTax);
            }
        }

        // Convert to shopping cart currency
        price = this.ShoppingCart.ApplyExchangeRate(price);

        lblPriceValue.Text = CurrencyInfoProvider.GetFormattedPrice(price, this.ShoppingCart.CurrencyInfoObj);
    }
Пример #20
0
    /// <summary>
    /// Recalculates and formats price.
    /// </summary>
    /// <param name="row">Data row to create price label for.</param>
    private string GetPrice(DataRow row)
    {
        var sku = new SKUInfo(row);

        // Get site main currency
        var currency = CurrencyInfoProvider.GetMainCurrency(sku.SKUSiteID);

        // Get product price
        var price = sku.SKUPrice;

        if (price != 0)
        {
            // Round price
            price = CurrencyInfoProvider.RoundTo(price, currency);

            // Prevent double encoding in DDL
            bool encode = SelectionType != OptionCategorySelectionTypeEnum.Dropdownlist;

            // Format price
            string formattedPrice = CurrencyInfoProvider.GetRelativelyFormattedPrice(price, currency, encode);

            return(" (" + formattedPrice + ")");
        }

        return(string.Empty);
    }
Пример #21
0
        //EndDocSection:RemoveAllItems


        //DocSection:DetailUrl
        /// <summary>
        /// Redirects to a product detail page based on the ID of a product's SKU object.
        /// </summary>
        /// <param name="skuID">ID of the product's SKU object.</param>
        public IActionResult ItemDetail(int skuID)
        {
            // Gets the SKU object
            SKUInfo sku = skuInfo.Get(skuID);

            // If the SKU does not exist or it is a product option, returns error 404
            if (sku == null || sku.IsProductOption)
            {
                return(NotFound());
            }

            // If the SKU is a product variant, uses its parent product's ID
            if (sku.IsProductVariant)
            {
                skuID = sku.SKUParentSKUID;
            }

            // Gets the product's page
            TreeNode node = pageRetriever.Retrieve <TreeNode>(query => query
                                                              .Culture("en-us")
                                                              .CombineWithDefaultCulture()
                                                              .WhereEquals("NodeSKUID", skuID))
                            .FirstOrDefault();

            // Returns 404 if no page for the specified product exists
            if (node == null)
            {
                return(NotFound());
            }

            // Gets the product page's URL
            string pageUrl = pageUrlRetriever.Retrieve(node).AbsoluteUrl;

            return(Redirect(pageUrl));
        }
Пример #22
0
 /// <summary>
 /// Checks if user has permissions to modify variants.
 /// </summary>
 /// <param name="skuInfo">SKUInfo object</param>
 private void CheckPermissions(SKUInfo skuInfo)
 {
     if (skuInfo != null)
     {
         CheckProductModifyAndRedirect(skuInfo);
     }
 }
Пример #23
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get current product info
        product = SKUInfoProvider.GetSKUInfo(ProductID);
        if (product != null)
        {
            // Allow site selector for global admins
            if (!CMSContext.CurrentUser.IsGlobalAdministrator)
            {
                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));
                }
            }
            docElem.ZeroRowsText = noDataMessage;

            docElem.SiteName = filterDocuments.SelectedSite;
            docElem.UniGrid.OnBeforeDataReload += new OnBeforeDataReload(UniGrid_OnBeforeDataReload);
            docElem.UniGrid.OnAfterDataReload  += new OnAfterDataReload(UniGrid_OnAfterDataReload);
        }
    }
Пример #24
0
    /// <summary>
    /// Updates the product image path.
    /// Returns true if the path was updated successfully, otherwise returns false.
    /// </summary>
    private bool UpdateProductImagePath()
    {
        var path = ValidationHelper.GetString(Value, null);

        if (Form != null)
        {
            var node = Form.Data as SKUTreeNode;
            if (node != null)
            {
                node.SetValue("SKUImagePath", path);
                node.Update();
                return(true);
            }
        }

        SKUInfo sku = SKUInfoProvider.GetSKUInfo(SKUID);

        if (sku != null)
        {
            sku.SKUImagePath = path;
            SKUInfoProvider.SetSKUInfo(sku);
            return(true);
        }

        return(false);
    }
Пример #25
0
        public JsonResult Variant(int variantID)
        {
            // Gets SKU information based on the variant's ID
            SKUInfo variant = SKUInfoProvider.GetSKUInfo(variantID);

            // If the variant is null, returns null
            if (variant == null)
            {
                return(null);
            }

            var cart = shoppingService.GetCurrentShoppingCart();

            // Calculates the price of the variant
            ProductCatalogPrices variantPrice = calculatorFactory
                                                .GetCalculator(cart.ShoppingCartSiteID)
                                                .GetPrices(variant, Enumerable.Empty <SKUInfo>(), cart);

            // Finds out whether the variant is in stock
            bool isInStock = variant.SKUTrackInventory == TrackInventoryTypeEnum.Disabled || variant.SKUAvailableItems > 0;

            // Creates a JSON response for the JavaScript that switches the variants
            var response = new
            {
                totalPrice   = String.Format(cart.Currency.CurrencyFormatString, variantPrice.Price),
                inStock      = isInStock,
                stockMessage = isInStock ? "Yes" : "No"
            };

            // Returns the response
            return(Json(response));
        }
Пример #26
0
    private void UpdatePrice(SKUInfo product, decimal price, DataRow additinalData)
    {
        // Ensures that grid will display inserted price
        product.SKUPrice = price;

        if (DocumentListingDisplayed)
        {
            // Document list is used to display products -> document has to be updated to ensure correct sku mapping
            int documentId = ValidationHelper.GetInteger(additinalData["DocumentID"], 0);

            // Create an instance of the Tree provider and select edited document with coupled data
            var document = new TreeProvider(MembershipContext.AuthenticatedUser)
                           .SelectSingleDocument(documentId);

            if (document != null)
            {
                document.SetValue("SKUPrice", price);
                document.Update();

                forceReloadData = true;
            }
        }
        else
        {
            // Stand-alone product -> only product has to be updated
            product.MakeComplete(true);
            product.Update();

            gridData.ReloadData();
        }
    }
        /// <summary>
        /// Creates a new product model.
        /// </summary>
        /// <param name="productPage">Product's page.</param>
        /// <param name="priceDetail">Price of the product.</param>
        public ProductViewModel(SKUTreeNode productPage, ProductCatalogPrices priceDetail)
        {
            // Fills the page information
            Name             = productPage.DocumentName;
            Description      = productPage.DocumentSKUDescription;
            ShortDescription = productPage.DocumentSKUShortDescription;

            // Fills the SKU information
            SKUInfo sku = productPage.SKU;

            SKUID     = sku.SKUID;
            ImagePath = string.IsNullOrEmpty(sku.SKUImagePath) ? null : new FileUrl(sku.SKUImagePath, true)
                        .WithSizeConstraint(SizeConstraint.MaxWidthOrHeight(400))
                        .RelativePath;

            IsInStock = sku.SKUTrackInventory == TrackInventoryTypeEnum.Disabled ||
                        sku.SKUAvailableItems > 0;

            PriceDetail = new PriceDetailViewModel()
            {
                Price                = priceDetail.Price,
                ListPrice            = priceDetail.ListPrice,
                CurrencyFormatString = priceDetail.Currency.CurrencyFormatString
            };
        }
Пример #28
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get current product info
        product = SKUInfoProvider.GetSKUInfo(ProductID);
        if (product != null)
        {
            // Allow site selector for global admins
            if (!CMSContext.CurrentUser.IsGlobalAdministrator)
            {
                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));
                }
            }
            docElem.ZeroRowsText = noDataMessage;

            docElem.SiteName = filterDocuments.SelectedSite;
            docElem.UniGrid.OnBeforeDataReload += new OnBeforeDataReload(UniGrid_OnBeforeDataReload);
            docElem.UniGrid.OnAfterDataReload += new OnAfterDataReload(UniGrid_OnAfterDataReload);
        }
    }
Пример #29
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Ecommerce", "Products.VolumeDiscounts"))
        {
            RedirectToCMSDeskUIElementAccessDenied("CMS.Ecommerce", "Products.VolumeDiscounts");
        }

        productId = QueryHelper.GetInteger("productId", 0);
        product   = SKUInfoProvider.GetSKUInfo(productId);

        EditedObject = product;

        if (product != null)
        {
            // Check site id
            CheckEditedObjectSiteID(product.SKUSiteID);

            // Load product currency
            productCurrency = CurrencyInfoProvider.GetMainCurrency(product.SKUSiteID);
        }

        // Set unigrid properties
        SetUnigridProperties();

        // Initialize the master page elements
        InitializeMasterPage();
    }
Пример #30
0
    /// <summary>
    /// Returns value of the specified product public status column.
    /// If the product is evaluated as a new product in the store, public status set by 'CMSStoreNewProductStatus' setting is used, otherwise product public status is used.
    /// </summary>
    /// <param name="sku">SKU data</param>
    /// <param name="column">Name of the product public status column the value should be retrieved from</param>
    public static object GetSKUIndicatorProperty(SKUInfo sku, string column)
    {
        // Do not process
        if (sku == null)
        {
            return(null);
        }

        PublicStatusInfo status     = null;
        string           siteName   = SiteInfoProvider.GetSiteName(sku.SKUSiteID);
        string           statusName = ECommerceSettings.NewProductStatus(siteName);

        if (!string.IsNullOrEmpty(statusName) && SKUInfoProvider.IsSKUNew(sku))
        {
            // Get 'new product' status
            status = PublicStatusInfoProvider.GetPublicStatusInfo(statusName, siteName);
        }
        else
        {
            // Get product public status
            if (sku.SKUPublicStatusID > 0)
            {
                status = PublicStatusInfoProvider.GetPublicStatusInfo(sku.SKUPublicStatusID);
            }
        }

        // Get specified column value
        return(GetColumnValue(status, column));
    }
Пример #31
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));
        }

        return(savedAmount);
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        CMSContentPage.CheckSecurity();

        // Check module permissions
        if (!ECommerceContext.IsUserAuthorizedForPermission("ReadProducts"))
        {
            RedirectToAccessDenied("CMS.Ecommerce", "EcommerceRead OR ReadProducts");
        }

        SKUInfo sku = null;

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

        if ((sku != null) && (sku.SKUSiteID != SiteContext.CurrentSiteID) && ((sku.SKUSiteID != 0) || !ECommerceSettings.AllowGlobalProducts(SiteContext.CurrentSiteName)))
        {
            EditedObject = null;
        }

        productEditElem.ProductSaved += productEditElem_ProductSaved;

        string action = QueryHelper.GetString("action", string.Empty).ToLowerCSafe();

        if (action == "newculture")
        {
            // Ensure breadcrumb for new culture version of product
            EnsureDocumentBreadcrumbs(PageBreadcrumbs, action: GetString("content.newcultureversiontitle"));
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        product = SKUInfoProvider.GetSKUInfo(ProductID);

        // Mark selected tab
        UIContext.ProductTab = ProductTabEnum.VolumeDiscounts;

        EditedObject = product;

        if (product != null)
        {
            // Check site id
            CheckEditedObjectSiteID(product.SKUSiteID);

            // Load product currency
            productCurrency = CurrencyInfoProvider.GetMainCurrency(product.SKUSiteID);

            // Display product price
            lblProductPrice.Text = CurrencyInfoProvider.GetFormattedPrice(product.SKUPrice, productCurrency);
        }

        // Set unigrid properties
        SetUnigridProperties();

        // Initialize the master page elements
        InitializeMasterPage();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Mark selected tab
        UIContext.ProductTab = ProductTabEnum.Options;

        if (ProductID > 0)
        {
            sku = SKUInfoProvider.GetSKUInfo(ProductID);

            EditedObject = sku;

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

                ucOptions.ProductID = ProductID;
                ucOptions.UniSelector.OnSelectionChanged += new EventHandler(UniSelector_OnSelectionChanged);
            }
        }

        // Set master title
        if (DisplayTitle)
        {
            CurrentMaster.Title.TitleText = GetString("optioncategory_edit.itemlistlink");
            CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Ecommerce_OptionCategory/object.png");
            CurrentMaster.Title.HelpTopicName = "cms_ecommerce_products_options";
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        product = SKUInfoProvider.GetSKUInfo(ProductID);

        // Setup help
        object options = new
        {
            helpName = "lnkProductEditHelp",
            helpUrl = UIContextHelper.GetDocumentationTopicUrl(HELP_TOPIC_LINK)
        };
        ScriptHelper.RegisterModule(this, "CMS/DialogContextHelpChange", options);

        EditedObject = product;

        if (product != null)
        {
            // Check site id
            CheckEditedObjectSiteID(product.SKUSiteID);

            // Load product currency
            productCurrency = CurrencyInfoProvider.GetMainCurrency(product.SKUSiteID);

            // Display product price
            headProductPriceInfo.Text = string.Format(GetString("com_sku_volume_discount.skupricelabel"), CurrencyInfoProvider.GetFormattedPrice(product.SKUPrice, productCurrency));
        }

        // Set unigrid properties
        SetUnigridProperties();

        // Initialize the master page elements
        InitializeMasterPage();
    }
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        if (plcSelector.Visible)
        {
            // Get product name and price
            SKUInfo skuObj  = SKUInfoProvider.GetSKUInfo(SKUID);
            string  skuName = "";

            if (skuObj != null)
            {
                skuName = ResHelper.LocalizeString(skuObj.SKUName);
            }

            // Set SKU name label
            headSKUName.Text = HTMLHelper.HTMLEncode(skuName);

            // Set breadcrumb
            PageBreadcrumbs.AddBreadcrumb(new BreadcrumbItem()
            {
                Text        = GetString("Order_Edit_AddItems.Products"),
                RedirectUrl = ResolveUrl("~/CMSModules/Ecommerce/Pages/Tools/Orders/Order_Edit_AddItems.aspx?cart=" + HTMLHelper.HTMLEncode(QueryHelper.GetString("cart", ""))),
            });

            PageBreadcrumbs.AddBreadcrumb(new BreadcrumbItem()
            {
                Text = skuName
            });
        }
    }
    /// <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);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Setup help
        object options = new
        {
            helpName = "lnkProductEditHelp",
            helpUrl = UIContextHelper.GetDocumentationTopicUrl(HELP_TOPIC_LINK)
        };
        ScriptHelper.RegisterModule(this, "CMS/DialogContextHelpChange", options);

        // Check UI personalization for product / product option separately
        if (OptionCategoryID > 0)
        {
            // Check elements in product options categories subtree
            CheckUIElementAccessHierarchical("CMS.Ecommerce", "ProductOptions.Options.TaxClasses");
        }
        else
        {
            CheckUIElementAccessHierarchical("CMS.Ecommerce", "Products.TaxClasses");
        }

        if (ProductID > 0)
        {
            sku = SKUInfoProvider.GetSKUInfo(ProductID);
            EditedObject = sku;

            if (sku != null)
            {
                // Check products site id
                CheckEditedObjectSiteID(sku.SKUSiteID);

                taxForm.ProductID = ProductID;
                taxForm.UniSelector.OnSelectionChanged += UniSelector_OnSelectionChanged;

                if (sku.IsProductOption)
                {
                    var categoryInfo = OptionCategoryInfoProvider.GetOptionCategoryInfo(sku.SKUOptionCategoryID);
                    if (categoryInfo != null)
                    {
                        CreateBreadcrumbs(sku);

                        if (categoryInfo.CategoryType != OptionCategoryTypeEnum.Products)
                        {
                            ShowError(GetString("com.taxesNotSupportedForOptionType"));
                            taxForm.Visible = false;
                        }
                    }
                }
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Setup help
        object options = new
        {
            helpName = "lnkProductEditHelp",
            helpUrl = UIContextHelper.GetDocumentationTopicUrl(HELP_TOPIC_LINK)
        };
        ScriptHelper.RegisterModule(this, "CMS/DialogContextHelpChange", options);

        if (ProductID > 0)
        {
            sku = SKUInfoProvider.GetSKUInfo(ProductID);

            EditedObject = sku;

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

                ucOptions.ProductID = ProductID;

                // Add new category button in HeaderAction
                CurrentMaster.HeaderActions.ActionsList.Add(new HeaderAction
                {
                    Text = GetString("com.productoptions.select"),
                    OnClientClick = ucOptions.GetAddCategoryJavaScript(),
                    Enabled = ECommerceContext.IsUserAuthorizedToModifySKU(sku.IsGlobal)
                });

                // New button is active in editing of global product only if global option categories are allowed and user has GlobalModifyPermission permission
                bool enabledButton = (sku.IsGlobal) ? ECommerceSettings.AllowGlobalProductOptions(CurrentSiteName) && ECommerceContext.IsUserAuthorizedToModifyOptionCategory(true)
                    : ECommerceContext.IsUserAuthorizedToModifyOptionCategory(false);

                // Create new enabled/disabled category button in HeaderAction
                var dialogUrl = URLHelper.ResolveUrl("~/CMSModules/Ecommerce/Pages/Tools/ProductOptions/OptionCategory_New.aspx?ProductID=" + sku.SKUID + "&dialog=1");
                dialogUrl = UIContextHelper.AppendDialogHash(dialogUrl);

                CurrentMaster.HeaderActions.ActionsList.Add(new HeaderAction
                {
                    Text = GetString("com.productoptions.new"),
                    Enabled = enabledButton,
                    ButtonStyle = ButtonStyle.Default,
                    OnClientClick = "modalDialog('" + dialogUrl + "','NewOptionCategoryDialog', 1000, 800);"
                });
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get product info
        if (ProductID > 0)
        {
            sku = SKUInfoProvider.GetSKUInfo(ProductID);
        }

        CMSMasterPage master = (CMSMasterPage)CurrentMaster;
        master.Tabs.OnTabCreated += Tabs_OnTabCreated;

        selectedTab = DataHelper.GetNotEmpty(QueryHelper.GetString("tab", String.Empty).ToLowerCSafe(), ProductTabCode.ToString(UIContext.ProductTab).ToLowerCSafe());

        master.PanelBody.CssClass += " Separator";
        master.SetRTL();
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        SKU = SKUInfoProvider.GetSKUInfo(ProductID);
        if (SKU != null)
        {
            CheckEditedObjectSiteID(SKU.SKUSiteID);
        }

        // Redirected from another page with saved flag
        if ((QueryHelper.GetInteger("saved", 0) == 1) && !URLHelper.IsPostback())
        {
            ShowChangesSaved();
        }
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Initialize DataForm
        if (productId > 0)
        {
            skuObj = SKUInfoProvider.GetSKUInfo(productId);
            EditedObject = skuObj;

            formProductCustomFields.Info = skuObj;
            formProductCustomFields.OnBeforeSave += formProductCustomFields_OnBeforeSave;
            formProductCustomFields.OnAfterSave += formProductCustomFields_OnAfterSave;
        }
        else
        {
            formProductCustomFields.Enabled = false;
        }
    }
    /// <summary>
    /// Initializes the extender
    /// </summary>
    public override void OnInit()
    {
        base.OnInit();

        siteId = QueryHelper.GetInteger("siteId", SiteContext.CurrentSiteID);

        // Get SKUID from querystring or from edited document
        var skuId = QueryHelper.GetInteger("productId", 0);
        if ((skuId <= 0) && (documentManager.Node != null))
        {
            skuId = documentManager.Node.NodeSKUID;
        }

        // Get product info
        if (skuId > 0)
        {
            sku = SKUInfoProvider.GetSKUInfo(skuId);
        }
    }
Пример #44
0
    /// <summary>
    /// Returns catalogue price of the given product based on the SKU data and shopping cart data. 
    /// By default price is loaded from the SKUPrice field.
    /// </summary>
    /// <param name="sku">SKU dta</param>
    /// <param name="cart">Shopping cart data</param>
    protected override double GetSKUPriceInternal(SKUInfo sku, ShoppingCartInfo cart)
    {
        double price = 0;

        // 1) Get base SKU price according to the shopping cart data (current culture)
        if (cart != null)
        {
            switch (cart.ShoppingCartCulture.ToLower())
            {
                case "en-us":
                    // Get price form SKUEnUsPrice field
                    price = ValidationHelper.GetDouble(sku.GetValue("SKUEnUsPrice"), 0);
                    break;

                case "cs-cz":
                    // Get price form SKUCsCzPrice field
                    price = ValidationHelper.GetDouble(sku.GetValue("SKUCsCzPrice"), 0);
                    break;
            }
        }

        //// 2) Get base SKU price according to the product properties (product status)
        //PublicStatusInfo status = PublicStatusInfoProvider.GetPublicStatusInfo(sku.SKUPublicStatusID);
        //if ((status != null) && (status.PublicStatusName.ToLower() == "discounted"))
        //{
        //    // Get price form SKUDiscountedPrice field
        //    price = ValidationHelper.GetDouble(sku.GetValue("SKUDiscountedPrice"), 0);
        //}

        if (price == 0)
        {
            // Get price from the SKUPrice field by default
            return base.GetSKUPriceInternal(sku, cart);
        }
        else
        {
            // Return custom price
            return price;
        }
    }
Пример #45
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;
            }
        }
    }
    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;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Ecommerce", "Products.Options"))
        {
            RedirectToCMSDeskUIElementAccessDenied("CMS.Ecommerce", "Products.Options");
        }

        int productId = QueryHelper.GetInteger("productId", 0);
        if (productId > 0)
        {
            sku = SKUInfoProvider.GetSKUInfo(productId);

            EditedObject = sku;

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

                ucOptions.ProductID = productId;
                ucOptions.UniSelector.OnSelectionChanged += new EventHandler(UniSelector_OnSelectionChanged);
            }
        }
    }
    /// <summary>
    /// Creates SKU for text option category.
    /// </summary>
    private void CreateTextOption()
    {
        // Create text product option
        var option = new SKUInfo
        {
            SKUOptionCategoryID = EditedCategory.CategoryID,
            SKUProductType = SKUProductTypeEnum.Text,
            SKUSiteID = CategorySiteID,
            SKUName = EditedCategory.CategoryTitle,
            SKUDepartmentID = 0,
            SKUPrice = 0,
            SKUNeedsShipping = false,
            SKUWeight = 0,
            SKUEnabled = true
        };

        SKUInfoProvider.SetSKUInfo(option);
    }
    private object grid_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        switch (sourceName.ToLowerCSafe())
        {
            case "skuprice":
                var optionRow = parameter as DataRowView;
                var option = new SKUInfo(optionRow.Row);

                if (sender == null)
                {
                    return option.SKUPrice;
                }

                var inlineSkuPrice = new InlineEditingTextBox();
                inlineSkuPrice.Text = option.SKUPrice.ToString();

                inlineSkuPrice.Formatting += (s, e) =>
                {
                    // Format price
                    inlineSkuPrice.FormattedText = CurrencyInfoProvider.GetRelativelyFormattedPrice(option.SKUPrice, option.SKUSiteID);
                };

                inlineSkuPrice.Update += (s, e) =>
                {
                    CheckModifyPermission();

                    CheckDepartmentPermission(option.SKUDepartmentID);

                    var valid = false;
                    var price = option.SKUPrice;
                    // Update price if new value is valid
                    if (ValidationHelper.IsDouble(inlineSkuPrice.Text))
                    {
                        price = ValidationHelper.GetDouble(inlineSkuPrice.Text, option.SKUPrice);
                        // Accessory price can not be negative
                        if (!option.IsAccessoryProduct || !(price < 0.0))
                        {
                            valid = true;
                        }
                    }

                    if (valid)
                    {
                        option.SKUPrice = price;
                        option.MakeComplete(true);
                        option.Update();

                        ugOptions.ReloadData();
                    }
                    else
                    {
                        inlineSkuPrice.ErrorText = GetString("com.productedit.priceinvalid");
                    }
                };

                return inlineSkuPrice;

            case "skuavailableitems":
                var row = parameter as DataRowView;
                var optionStock = new SKUInfo(row.Row);

                int availableItems = optionStock.SKUAvailableItems;

                // Inventory tracking disabled
                if (optionStock.SKUTrackInventory == TrackInventoryTypeEnum.Disabled)
                {
                    return GetString("com.inventory.nottracked");
                }

                // Ensure correct values for unigrid export
                if (sender == null)
                {
                    return availableItems;
                }

                var inlineSkuAvailableItems = new InlineEditingTextBox();
                inlineSkuAvailableItems.Text = availableItems.ToString();
                inlineSkuAvailableItems.EnableEncode = false;

                inlineSkuAvailableItems.Formatting += (s, e) =>
                {
                    var reorderAt = optionStock.SKUReorderAt;

                    // Emphasize the number when product needs to be reordered
                    if (availableItems <= reorderAt)
                    {
                        // Format message informing about insufficient stock level
                        string reorderMsg = string.Format(GetString("com.sku.reorderatTooltip"), reorderAt);
                        string message = string.Format("<span class=\"alert-status-error\" onclick=\"UnTip()\" onmouseout=\"UnTip()\" onmouseover=\"Tip('{1}')\">{0}</span>", availableItems, reorderMsg);
                        inlineSkuAvailableItems.FormattedText = message;
                    }
                };

                inlineSkuAvailableItems.Update += (s, e) =>
                {
                    CheckModifyPermission();

                    CheckDepartmentPermission(optionStock.SKUDepartmentID);

                    var newNumberOfItems = ValidationHelper.GetInteger(inlineSkuAvailableItems.Text, availableItems);

                    // Update available items if new value is valid
                    if (ValidationHelper.IsInteger(inlineSkuAvailableItems.Text) && (-1000000000 <= newNumberOfItems) && (newNumberOfItems <= 1000000000))
                    {
                        optionStock.SKUAvailableItems = ValidationHelper.GetInteger(inlineSkuAvailableItems.Text, availableItems);
                        optionStock.MakeComplete(true);
                        optionStock.Update();

                        ugOptions.ReloadData();
                    }
                    else
                    {
                        inlineSkuAvailableItems.ErrorText = GetString("com.productedit.availableitemsinvalid");
                    }
                };

                return inlineSkuAvailableItems;

            case "delete":
            case "moveup":
            case "movedown":
                {
                    CMSGridActionButton button = sender as CMSGridActionButton;
                    if (button != null)
                    {
                        // Hide actions when not allowed
                        button.Visible = allowActions;
                    }
                }
                break;
        }

        return parameter;
    }
    /// <summary>
    /// Changes attribute option from data set to SKU option and ensures correct tracking and shipping for product.
    /// </summary>
    /// <param name="options">Data set with product option</param>
    private void ChangeAttributeToProduct(DataSet options)
    {
        if (DataHelper.DataSourceIsEmpty(options))
        {
            return;
        }

        foreach (DataRow option in options.Tables[0].Rows)
        {
            SKUInfo productOption = new SKUInfo(option);
            productOption.SKUTrackInventory = TrackInventoryTypeEnum.ByProduct;
            productOption.SKUNeedsShipping = true;

            SKUInfoProvider.SetSKUInfo(productOption);
        }
    }
    /// <summary>
    /// Changes SKU option from data set to attribute option. Attribute is an option and it does not need product data like for example itinerary.
    /// </summary>
    /// <param name="options">Data set with product option</param>
    private void ChangeProductToAttribute(DataSet options)
    {
        if (DataHelper.DataSourceIsEmpty(options))
        {
            return;
        }

        foreach (DataRow option in options.Tables[0].Rows)
        {
            SKUInfo product = new SKUInfo(option);

            product.SKUProductType = SKUProductTypeEnum.Product;
            product.SetValue("SKUTrackInventory", null);
            product.SetValue("SKUMaxItemsInOrder", null);
            product.SetValue("SKUMinItemsInOrder", null);
            product.SetValue("SKUAvailableItems", null);
            product.SetValue("SKUValidity", null);
            product.SetValue("SKUReorderAt", null);
            product.SetValue("SKUDescription", null);
            product.SetValue("SKUAvailableInDays", null);
            product.SetValue("SKUNumber", null);
            product.SetValue("SKUMaxDownloads", null);
            product.SetValue("SKUMaxPrice", null);
            product.SetValue("SKUMinPrice", null);
            product.SetValue("SKUValidFor", null);
            product.SetValue("SKURetailPrice", null);
            product.SetValue("SKUEproductFilesCount", null);
            product.SKUDepartmentID = 0;
            product.SKUManufacturerID = 0;
            product.SKUInternalStatusID = 0;
            product.SKUPublicStatusID = 0;
            product.SKUSupplierID = 0;
            product.SKUImagePath = null;
            product.SKUWeight = 0;
            product.SKUWidth = 0;
            product.SKUDepth = 0;
            product.SKUHeight = 0;
            product.SKUSellOnlyAvailable = false;
            product.SKUPrivateDonation = false;
            product.SKUNeedsShipping = false;
            product.SKUValidUntil = DateTimeHelper.ZERO_TIME;
            product.SKUMembershipGUID = Guid.Empty;
            product.SKUConversionName = null;
            product.SKUConversionValue = "";
            product.SKUBundleInventoryType = 0;
            product.SKUParentSKUID = 0;
            product.SKUShortDescription = null;

            SKUInfoProvider.SetSKUInfo(product);
        }
    }
Пример #52
0
    /// <summary>
    /// Saves edited SKU and returns it's ID. In case of error 0 is returned. Does not fire product saved event.
    /// </summary>
    private int SaveInternal()
    {
        // Check permissions
        this.CheckModifyPermission();

        // If form is valid and enabled
        if (this.Validate() && this.FormEnabled)
        {
            bool newItem = false;

            // Get SKUInfo
            SKUInfo skuiObj = SKUInfoProvider.GetSKUInfo(mProductId);

            if (skuiObj == null)
            {
                newItem = true;

                // Create new item -> insert
                skuiObj = new SKUInfo();
                skuiObj.SKUSiteID = editedSiteId;
            }
            else
            {
                SKUProductTypeEnum oldProductType = skuiObj.SKUProductType;
                SKUProductTypeEnum newProductType = SKUInfoProvider.GetSKUProductTypeEnum((string)this.selectProductTypeElem.Value);

                // Remove e-product dependencies if required
                if ((oldProductType == SKUProductTypeEnum.EProduct) && (newProductType != SKUProductTypeEnum.EProduct))
                {
                    // Delete meta files
                    MetaFileInfoProvider.DeleteFiles(skuiObj.SKUID, ECommerceObjectType.SKU, MetaFileInfoProvider.OBJECT_CATEGORY_EPRODUCT);

                    // Delete SKU files
                    DataSet skuFiles = SKUFileInfoProvider.GetSKUFiles("FileSKUID = " + skuiObj.SKUID, null);

                    foreach (DataRow skuFile in skuFiles.Tables[0].Rows)
                    {
                        SKUFileInfo skufi = new SKUFileInfo(skuFile);
                        SKUFileInfoProvider.DeleteSKUFileInfo(skufi);
                    }
                }

                // Remove bundle dependencies if required
                if ((oldProductType == SKUProductTypeEnum.Bundle) && (newProductType != SKUProductTypeEnum.Bundle))
                {
                    // Delete SKU to bundle mappings
                    DataSet bundles = BundleInfoProvider.GetBundles("BundleID = " + skuiObj.SKUID, null);

                    foreach (DataRow bundle in bundles.Tables[0].Rows)
                    {
                        BundleInfo bi = new BundleInfo(bundle);
                        BundleInfoProvider.DeleteBundleInfo(bi);
                    }
                }
            }

            skuiObj.SKUName = this.txtSKUName.Text.Trim();
            skuiObj.SKUNumber = this.txtSKUNumber.Text.Trim();
            skuiObj.SKUDescription = this.htmlTemplateBody.ResolvedValue;
            skuiObj.SKUPrice = this.txtSKUPrice.Value;
            skuiObj.SKUEnabled = this.chkSKUEnabled.Checked;
            skuiObj.SKUInternalStatusID = this.internalStatusElem.InternalStatusID;
            skuiObj.SKUDepartmentID = this.departmentElem.DepartmentID;
            skuiObj.SKUManufacturerID = this.manufacturerElem.ManufacturerID;
            skuiObj.SKUPublicStatusID = this.publicStatusElem.PublicStatusID;
            skuiObj.SKUSupplierID = this.supplierElem.SupplierID;
            skuiObj.SKUSellOnlyAvailable = this.chkSKUSellOnlyAvailable.Checked;
            skuiObj.SKUNeedsShipping = this.chkNeedsShipping.Checked;
            skuiObj.SKUWeight = ValidationHelper.GetDouble(this.txtSKUWeight.Text.Trim(), 0);
            skuiObj.SKUHeight = ValidationHelper.GetDouble(this.txtSKUHeight.Text.Trim(), 0);
            skuiObj.SKUWidth = ValidationHelper.GetDouble(this.txtSKUWidth.Text.Trim(), 0);
            skuiObj.SKUDepth = ValidationHelper.GetDouble(this.txtSKUDepth.Text.Trim(), 0);
            skuiObj.SKUConversionName = ValidationHelper.GetString(this.ucConversion.Value, String.Empty);
            skuiObj.SKUConversionValue = this.txtConversionValue.Text.Trim();

            if (String.IsNullOrEmpty(this.txtSKUAvailableItems.Text.Trim()))
            {
                skuiObj.SetValue("SKUAvailableItems", null);
            }
            else
            {
                skuiObj.SKUAvailableItems = ValidationHelper.GetInteger(this.txtSKUAvailableItems.Text.Trim(), 0);
            }

            if (String.IsNullOrEmpty(this.txtSKUAvailableInDays.Text.Trim()))
            {
                skuiObj.SetValue("SKUAvailableInDays", null);
            }
            else
            {
                skuiObj.SKUAvailableInDays = ValidationHelper.GetInteger(this.txtSKUAvailableInDays.Text.Trim(), 0);
            }

            if (String.IsNullOrEmpty(this.txtMaxOrderItems.Text.Trim()))
            {
                skuiObj.SetValue("SKUMaxItemsInOrder", null);
            }
            else
            {
                skuiObj.SKUMaxItemsInOrder = ValidationHelper.GetInteger(this.txtMaxOrderItems.Text.Trim(), 0);
            }

            if (!ProductOrdered)
            {
                // Set product type
                skuiObj.SKUProductType = SKUInfoProvider.GetSKUProductTypeEnum((string)this.selectProductTypeElem.Value);
            }

            // Clear product type specific properties
            skuiObj.SetValue("SKUMembershipGUID", null);
            skuiObj.SetValue("SKUValidity", null);
            skuiObj.SetValue("SKUValidFor", null);
            skuiObj.SetValue("SKUValidUntil", null);
            skuiObj.SetValue("SKUMaxDownloads", null);
            skuiObj.SetValue("SKUBundleInventoryType", null);
            skuiObj.SetValue("SKUPrivateDonation", null);
            skuiObj.SetValue("SKUMinPrice", null);
            skuiObj.SetValue("SKUMaxPrice", null);

            // Set product type specific properties
            switch (skuiObj.SKUProductType)
            {
                // Set membership specific properties
                case SKUProductTypeEnum.Membership:
                    skuiObj.SKUMembershipGUID = this.membershipElem.MembershipGUID;
                    skuiObj.SKUValidity = this.membershipElem.MembershipValidity;

                    if (skuiObj.SKUValidity == ValidityEnum.Until)
                    {
                        skuiObj.SKUValidUntil = this.membershipElem.MembershipValidUntil;
                    }
                    else
                    {
                        skuiObj.SKUValidFor = this.membershipElem.MembershipValidFor;
                    }
                    break;

                // Set e-product specific properties
                case SKUProductTypeEnum.EProduct:
                    skuiObj.SKUValidity = this.eProductElem.EProductValidity;

                    if (skuiObj.SKUValidity == ValidityEnum.Until)
                    {
                        skuiObj.SKUValidUntil = this.eProductElem.EProductValidUntil;
                    }
                    else
                    {
                        skuiObj.SKUValidFor = this.eProductElem.EProductValidFor;
                    }
                    break;

                // Set donation specific properties
                case SKUProductTypeEnum.Donation:
                    skuiObj.SKUPrivateDonation = this.donationElem.DonationIsPrivate;

                    if (this.donationElem.MinimumDonationAmount == 0.0)
                    {
                        skuiObj.SetValue("SKUMinPrice", null);
                    }
                    else
                    {
                        skuiObj.SKUMinPrice = this.donationElem.MinimumDonationAmount;
                    }

                    if (this.donationElem.MaximumDonationAmount == 0.0)
                    {
                        skuiObj.SetValue("SKUMaxPrice", null);
                    }
                    else
                    {
                        skuiObj.SKUMaxPrice = this.donationElem.MaximumDonationAmount;
                    }
                    break;

                // Set bundle specific properties
                case SKUProductTypeEnum.Bundle:
                    skuiObj.SKUBundleInventoryType = this.bundleElem.RemoveFromInventory;
                    break;
            }

            // When creating new product option
            if ((this.ProductID == 0) && (this.OptionCategoryID > 0))
            {
                skuiObj.SKUOptionCategoryID = this.OptionCategoryID;
            }

            if ((newItem) && (!SKUInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert)))
            {
                lblError.Visible = true;
                lblError.Text = GetString("ecommerceproduct.versioncheck");

                return 0;
            }

            SKUInfoProvider.SetSKUInfo(skuiObj);

            if (newItem)
            {
                if (ECommerceSettings.UseMetaFileForProductImage)
                {
                    // Get allowed extensions
                    string settingKey = (skuiObj.IsGlobal) ? "CMSUploadExtensions" : (CMSContext.CurrentSiteName + ".CMSUploadExtensions");
                    string allowedExtensions = SettingsKeyProvider.GetStringValue(settingKey);

                    // Get posted file
                    HttpPostedFile file = this.ucMetaFile.PostedFile;

                    if ((file != null) && (file.ContentLength > 0))
                    {
                        // Get file extension
                        string extension = Path.GetExtension(file.FileName);

                        // Check if file is an image and its extension is allowed
                        if (ImageHelper.IsImage(extension) && (String.IsNullOrEmpty(allowedExtensions) || FileHelper.CheckExtension(extension, allowedExtensions)))
                        {
                            // Upload SKU image meta file
                            this.ucMetaFile.ObjectID = skuiObj.SKUID;
                            this.ucMetaFile.UploadFile();

                            // Update SKU image path
                            this.UpdateSKUImagePath(skuiObj);
                        }
                        else
                        {
                            // Set error message
                            string error = ValidationHelper.GetString(SessionHelper.GetValue("NewProductError"), null);
                            error += ";" + String.Format(this.GetString("com.productedit.invalidproductimage"), extension);
                            SessionHelper.SetValue("NewProductError", error);
                        }
                    }
                }
                else
                {
                    skuiObj.SKUImagePath = this.imgSelect.Value;
                }

                // Upload initial e-product file
                if (skuiObj.SKUProductType == SKUProductTypeEnum.EProduct)
                {
                    this.eProductElem.SKUID = skuiObj.SKUID;
                    this.eProductElem.UploadNewProductFile();
                }
            }
            else
            {
                // Update SKU image path
                UpdateSKUImagePath(skuiObj);
            }

            SKUInfoProvider.SetSKUInfo(skuiObj);

            if ((mNodeId > 0) && (mProductId == 0))
            {
                TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);
                TreeNode node = tree.SelectSingleNode(mNodeId, TreeProvider.ALL_CULTURES);
                node.NodeSKUID = skuiObj.SKUID;
                node.Update();

                // Update search index for node
                if ((node.PublishedVersionExists) && (SearchIndexInfoProvider.SearchEnabled))
                {
                    SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, PredefinedObjectType.DOCUMENT, SearchHelper.ID_FIELD, node.GetSearchID());
                }

                // Log synchronization
                DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree);

                // Ensure new SKU values
                SKUInfoProvider.SetSKUInfo(skuiObj);
            }

            // If SKU is of bundle product type and bundle does not exist yet
            if ((skuiObj.SKUProductType == SKUProductTypeEnum.Bundle) && (this.bundleElem.BundleID == 0))
            {
                // Set bundle ID
                this.bundleElem.BundleID = skuiObj.SKUID;

                // Save selected products
                this.bundleElem.SaveProductsSelectionChanges();
            }

            this.ProductID = skuiObj.SKUID;

            // Reload form
            this.LoadData(skuiObj);

            // Set changes saved message
            this.lblInfo.Text = this.GetString("general.changessaved");

            return ValidationHelper.GetInteger(skuiObj.SKUID, 0);
        }
        else
        {
            return 0;
        }
    }
Пример #53
0
    /// <summary>
    /// Load data of editing ecommerceEcommerce.
    /// </summary>
    /// <param name="skuiObj">EcommerceEcommerce object</param>
    protected void LoadData(SKUInfo skuiObj)
    {
        // Set data reloaded flag
        this.ViewState["DataReloaded"] = true;

        // General
        txtSKUName.Text = skuiObj.SKUName;
        txtSKUNumber.Text = skuiObj.SKUNumber;
        htmlTemplateBody.ResolvedValue = skuiObj.SKUDescription;
        txtSKUPrice.Value = skuiObj.SKUPrice;
        departmentElem.DepartmentID = skuiObj.SKUDepartmentID;
        manufacturerElem.ManufacturerID = skuiObj.SKUManufacturerID;
        supplierElem.SupplierID = skuiObj.SKUSupplierID;
        imgSelect.Value = skuiObj.SKUImagePath;

        // Status
        chkSKUEnabled.Checked = skuiObj.SKUEnabled;
        publicStatusElem.PublicStatusID = skuiObj.SKUPublicStatusID;
        internalStatusElem.InternalStatusID = skuiObj.SKUInternalStatusID;

        // Shipping
        chkNeedsShipping.Checked = skuiObj.SKUNeedsShipping;
        txtSKUWeight.Text = (skuiObj.SKUWeight > 0) ? skuiObj.SKUWeight.ToString() : String.Empty;
        txtSKUWidth.Text = (skuiObj.SKUWidth > 0) ? skuiObj.SKUWidth.ToString() : String.Empty;
        txtSKUHeight.Text = (skuiObj.SKUHeight > 0) ? skuiObj.SKUHeight.ToString() : String.Empty;
        txtSKUDepth.Text = (skuiObj.SKUDepth > 0) ? skuiObj.SKUDepth.ToString() : String.Empty;

        // Inventory
        this.chkSKUSellOnlyAvailable.Checked = skuiObj.SKUSellOnlyAvailable;
        this.txtSKUAvailableItems.Text = (skuiObj.GetIntegerValue("SKUAvailableItems", -1) == -1) ? String.Empty : skuiObj.SKUAvailableItems.ToString();
        this.txtSKUAvailableInDays.Text = (skuiObj.GetIntegerValue("SKUAvailableInDays", -1) == -1) ? String.Empty : skuiObj.SKUAvailableInDays.ToString();
        this.txtMaxOrderItems.Text = (skuiObj.GetIntegerValue("SKUMaxItemsInOrder", -1) == -1) ? String.Empty : skuiObj.SKUMaxItemsInOrder.ToString();

        // Conversions
        ucConversion.Value = skuiObj.SKUConversionName;
        txtConversionValue.Text = skuiObj.SKUConversionValue.ToString();

        // If editing a product option
        if (skuiObj.SKUOptionCategoryID > 0)
        {
            // Disable specific product type options
            this.selectProductTypeElem.AllowBundle = false;
            this.selectProductTypeElem.AllowDonation = false;
            this.selectProductTypeElem.Initialize();
        }

        // Load product type specific properties
        switch (skuiObj.SKUProductType)
        {
            // Initialize membership specific properties
            case SKUProductTypeEnum.Membership:
                this.membershipElem.MembershipGUID = skuiObj.SKUMembershipGUID;
                this.membershipElem.MembershipValidity = skuiObj.SKUValidity;

                if (skuiObj.SKUValidity == ValidityEnum.Until)
                {
                    this.membershipElem.MembershipValidUntil = skuiObj.SKUValidUntil;
                }
                else
                {
                    this.membershipElem.MembershipValidFor = skuiObj.SKUValidFor;
                }
                break;

            // Initialize e-product specific properties
            case SKUProductTypeEnum.EProduct:
                this.eProductElem.EProductValidity = skuiObj.SKUValidity;

                if (skuiObj.SKUValidity == ValidityEnum.Until)
                {
                    this.eProductElem.EProductValidUntil = skuiObj.SKUValidUntil;
                }
                else
                {
                    this.eProductElem.EProductValidFor = skuiObj.SKUValidFor;
                }
                break;

            // Initialize donation specific properties
            case SKUProductTypeEnum.Donation:
                this.donationElem.DonationIsPrivate = skuiObj.SKUPrivateDonation;

                // If minimum price is set
                if (skuiObj.GetDoubleValue("SKUMinPrice", -1) != -1)
                {
                    this.donationElem.MinimumDonationAmount = skuiObj.SKUMinPrice;
                }

                // If maximum price is set
                if (skuiObj.GetDoubleValue("SKUMaxPrice", -1) != -1)
                {
                    this.donationElem.MaximumDonationAmount = skuiObj.SKUMaxPrice;
                }
                break;

            // Initialize bundle specific properties
            case SKUProductTypeEnum.Bundle:
                this.bundleElem.RemoveFromInventory = skuiObj.SKUBundleInventoryType;
                break;
        }

        // Select product type
        this.selectProductTypeElem.Value = SKUInfoProvider.GetSKUProductTypeString(skuiObj.SKUProductType);
    }
    /// <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");
            }
        }

        // Validate the form
        string errorMessage = ValidateForm();

        if (errorMessage == "")
        {
            // Category code name must be unique
            OptionCategoryInfo optionCategoryObj = null;
            string siteWhere = (editedSiteId > 0) ? " AND (CategorySiteID = " + editedSiteId + " 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) || (optionCategoryObj.CategoryID == categoryID))
            {
                // If optionCategory doesn't already exist, create new one
                if (optionCategoryObj == null)
                {
                    optionCategoryObj = OptionCategoryInfoProvider.GetOptionCategoryInfo(categoryID);
                    if (optionCategoryObj == null)
                    {
                        optionCategoryObj = new OptionCategoryInfo();
                        optionCategoryObj.CategorySiteID = editedSiteId;
                    }
                }

                // Set category properties
                optionCategoryObj.CategoryID = categoryID;
                optionCategoryObj.CategoryDisplayName = txtDisplayName.Text.Trim();
                optionCategoryObj.CategoryName = txtCategoryName.Text.Trim();
                optionCategoryObj.CategorySelectionType = GetOptionCategoryEnum(drpCategorySelectionType.SelectedValue);
                optionCategoryObj.CategoryDefaultOptions = productOptionSelector.GetSelectedSKUOptions();
                optionCategoryObj.CategoryDescription = txtCategoryDecription.Text.Trim();
                optionCategoryObj.CategoryDefaultRecord = txtDefaultRecord.Text.Trim();
                optionCategoryObj.CategoryEnabled = chkCategoryEnabled.Checked;
                optionCategoryObj.CategoryDisplayPrice = chkCategoryDisplayPrice.Checked;
                optionCategoryObj.CategoryTextMaxLength = ValidationHelper.GetInteger(txtTextMaxLength.Text.Trim(),0);

                using (CMSTransactionScope tran = new CMSTransactionScope())
                {
                    // Save changes
                    OptionCategoryInfoProvider.SetOptionCategoryInfo(optionCategoryObj);

                    // Add text option to text category only if it is empty
                    if (((optionCategoryObj.CategorySelectionType == OptionCategorySelectionTypeEnum.TextBox) ||
                        (optionCategoryObj.CategorySelectionType == OptionCategorySelectionTypeEnum.TextArea)) &&
                        (SKUInfoProvider.GetSKUOptionsCount(categoryID) == 0))
                    {
                        // Create default text product option
                        SKUInfo option = new SKUInfo();
                        option.SKUName = optionCategoryObj.CategoryDisplayName;
                        option.SKUDescription = optionCategoryObj.CategoryDescription;
                        option.SKUSiteID =  optionCategoryObj.CategorySiteID;
                        option.SKUPrice = 0;
                    }

                    tran.Commit();
                }

                // If hidebreadcrumbs (is in modal window)
                if (QueryHelper.GetBoolean("hidebreadcrumbs", false))
                {
                    // Close window and refresh opener
                    ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "CloseAndRefresh", ScriptHelper.GetScript("parent.wopener.Refresh(); parent.window.close();"));
                }
                else
                {
                    // Normal save
                    //URLHelper.Redirect("OptionCategory_Edit_General.aspx?CategoryID=" + Convert.ToString(optionCategoryObj.CategoryID) + "&saved=1&siteId=" + this.SiteID);
                    ScriptHelper.RefreshTabHeader(this, "general");

                    lblInfo.Visible = true;
                    lblInfo.Text = GetString("General.ChangesSaved");
                }
            }
            else
            {
                lblError.Visible = true;
                lblError.Text = GetString("optioncategory_new.errorExistingCodeName");
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text = errorMessage;
        }
    }
Пример #55
0
    private object gridElem_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        DataRowView rowView = parameter as DataRowView;
        if (rowView != null)
        {
            SKUInfo sku = new SKUInfo(rowView.Row);
            switch (sourceName.ToLowerCSafe())
            {
                case "skuname":
                    string fullName = sku.SKUName;

                    // For variant, add name from parent SKU
                    if (sku.SKUParentSKUID != 0)
                    {
                        SKUInfo parentSku = SKUInfoProvider.GetSKUInfo(sku.SKUParentSKUID);
                        fullName = string.Format("{0}: {1}", parentSku.SKUName, sku.SKUName);
                    }
                    return HTMLHelper.HTMLEncode(fullName);

                case "optioncategory":
                    OptionCategoryInfo optionCategory = OptionCategoryInfoProvider.GetOptionCategoryInfo(sku.SKUOptionCategoryID);

                    // Return option category display name for product option or '-' for product
                    if (optionCategory != null)
                    {
                        return HTMLHelper.HTMLEncode(optionCategory.CategoryDisplayName ?? "");
                    }
                    return "-";

                case "skunumber":
                    return ResHelper.LocalizeString(sku.SKUNumber, null, true);

                case "skuprice":
                    // Format price
                    return CurrencyInfoProvider.GetFormattedPrice(sku.SKUPrice, sku.SKUSiteID);

                case "skudepartmentid":
                    // Transform to display name and localize
                    DepartmentInfo department = DepartmentInfoProvider.GetDepartmentInfo(sku.SKUDepartmentID);
                    return (department != null) ? HTMLHelper.HTMLEncode(ResHelper.LocalizeString(department.DepartmentDisplayName)) : "";

                case "skumanufacturerid":
                    // Transform to display name and localize
                    ManufacturerInfo manufacturer = ManufacturerInfoProvider.GetManufacturerInfo(sku.SKUManufacturerID);
                    return (manufacturer != null) ? HTMLHelper.HTMLEncode(ResHelper.LocalizeString(manufacturer.ManufacturerDisplayName)) : "";

                case "skusupplierid":
                    // Transform to display name and localize
                    SupplierInfo supplier = SupplierInfoProvider.GetSupplierInfo(sku.SKUSupplierID);
                    return (supplier != null) ? HTMLHelper.HTMLEncode(ResHelper.LocalizeString(supplier.SupplierDisplayName)) : "";

                case "skupublicstatusid":
                    // Transform to display name and localize
                    PublicStatusInfo publicStatus = PublicStatusInfoProvider.GetPublicStatusInfo(sku.SKUPublicStatusID);
                    return (publicStatus != null) ? HTMLHelper.HTMLEncode(ResHelper.LocalizeString(publicStatus.PublicStatusDisplayName)) : "";

                case "skuinternalstatusid":
                    // Transform to display name and localize
                    InternalStatusInfo internalStatus = InternalStatusInfoProvider.GetInternalStatusInfo(sku.SKUInternalStatusID);
                    return (internalStatus != null) ? HTMLHelper.HTMLEncode(ResHelper.LocalizeString(internalStatus.InternalStatusDisplayName)) : "";

                case "skuavailableitems":
                    int? count = sku.SKUAvailableItems as int?;
                    int? reorderAt = sku.SKUReorderAt as int?;

                    // Emphasize the number when product needs to be reordered
                    if (count.HasValue && ((reorderAt.HasValue && (count <= reorderAt)) || (!reorderAt.HasValue && (count <= 0))))
                    {
                        // Format message informing about insufficient stock level
                        return string.Format("<span class=\"OperationFailed\">{0}</span>", count);
                    }
                    return count;

                case "itemstobereordered":
                    int difference = sku.SKUReorderAt - sku.SKUAvailableItems;

                    // Return difference, or '-'
                    return (difference > 0) ? difference.ToString() : "-";

                case "skusiteid":
                    return UniGridFunctions.ColoredSpanYesNo(sku.SKUSiteID == 0);
            }
        }

        return parameter;
    }
    /// <summary>
    /// Initializes the extender
    /// </summary>
    public override void OnInit()
    {
        base.OnInit();
        var breadcrumbName = "";
        bool generateBreadcrumbs = true;

        // Ensure selection of general tab in case EditForm is requested
        var tabName = QueryHelper.GetString("tabName", "");
        if (tabName.EqualsCSafe("EditForm", true))
        {
            Control.SelectedTabName = "Products.General";
        }

        var page = (CMSPage)Control.Page;

        if (ProductID <= 0)
        {
            // Setup the document manager
            var manager = page.DocumentManager;
            manager.RedirectForNonExistingDocument = false;
            manager.Tree.CombineWithDefaultCulture = false;

            var node = manager.Node;
            if (node == null)
            {
                // Redirect to create new culture version
                URLHelper.ResponseRedirect(ProductUIHelper.GetNewCultureVersionPageUrl(), false);
                CMSHttpContext.Current.ApplicationInstance.CompleteRequest();
                return;
            }

            Node = node;
            breadcrumbName = Node.Site.Generalized.ObjectDisplayName;
        }

        // Get product name and option category ID
        if (ProductID > 0)
        {
            sku = SKUInfoProvider.GetSKUInfo(ProductID);
            if (sku != null)
            {
                breadcrumbName = ResHelper.LocalizeString(sku.SKUName);
                optionCategoryId = sku.SKUOptionCategoryID;
                siteId = sku.SKUSiteID;

                // Check if edited object belongs to configured site
                if ((siteId != SiteContext.CurrentSiteID) && ((siteId != 0) || !AllowGlobalObjects))
                {
                    page.EditedObject = null;
                }

                var dialogMode = QueryHelper.GetBoolean("dialog", false);

                int hideBreadcrumbs = QueryHelper.GetInteger("hidebreadcrumbs", 0);

                // Show breadcrumbs if not dialog mode or dialog mode is in product option UI
                if ((hideBreadcrumbs != 0) || dialogMode)
                {
                    generateBreadcrumbs = false;
                }
            }
        }

        if (generateBreadcrumbs)
        {
            ProductUIHelper.EnsureProductBreadcrumbs(page.PageBreadcrumbs, breadcrumbName, (ProductID <= 0), ProductListInTree);
        }

        Control.Page.Load += Page_Load;

        Control.ElementName = (optionCategoryId > 0) ? "ProductOptions.Options" : "Products.Properties";
    }
Пример #57
0
    private void UpdateSKUImagePath(SKUInfo skuObj)
    {
        if (ECommerceSettings.UseMetaFileForProductImage && !hasAttachmentImagePath)
        {
            // Update product image path according to its meta file
            DataSet ds = MetaFileInfoProvider.GetMetaFiles(ucMetaFile.ObjectID, skuObj.TypeInfo.ObjectType, MetaFileInfoProvider.OBJECT_CATEGORY_IMAGE, null, null);

            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                MetaFileInfo metaFile = new MetaFileInfo(ds.Tables[0].Rows[0]);
                skuObj.SKUImagePath = MetaFileInfoProvider.GetMetaFileUrl(metaFile.MetaFileGUID, metaFile.MetaFileName);
            }
            else
            {
                skuObj.SKUImagePath = "";
            }
        }
        else
        {
            // Update product image path from the image selector
            skuObj.SKUImagePath = imgSelect.Value;
        }
    }
    private object gridData_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        DataRowView row = parameter as DataRowView;

        if (DocumentListingDisplayed)
        {
            switch (sourceName.ToLowerCSafe())
            {
                case "skunumber":
                case "skuavailableitems":
                case "publicstatusid":
                case "allowforsale":
                case "skusiteid":
                case "typename":
                case "skuprice":

                    if (ShowSections && (row["NodeSKUID"] == DBNull.Value))
                    {
                        return NO_DATA_CELL_VALUE;
                    }

                    break;

                case "edititem":
                    row = ((GridViewRow)parameter).DataItem as DataRowView;

                    if ((row != null) && ((row["NodeSKUID"] == DBNull.Value) || showProductsInTree))
                    {
                        CMSGridActionButton btn = sender as CMSGridActionButton;
                        if (btn != null)
                        {
                            int currentNodeId = ValidationHelper.GetInteger(row["NodeID"], 0);
                            int nodeParentId = ValidationHelper.GetInteger(row["NodeParentID"], 0);

                            if (row["NodeSKUID"] == DBNull.Value)
                            {
                                btn.IconCssClass = "icon-eye";
                                btn.IconStyle = GridIconStyle.Allow;
                                btn.ToolTip = GetString("com.sku.viewproducts");
                            }

                            // Go to the selected document
                            btn.OnClientClick = "EditItem(" + currentNodeId + ", " + nodeParentId + "); return false;";
                        }
                    }

                    break;
            }
        }

        switch (sourceName.ToLowerCSafe())
        {
            case "skunumber":
                string skuNumber = ValidationHelper.GetString(row["SKUNumber"], null);
                return HTMLHelper.HTMLEncode(ResHelper.LocalizeString(skuNumber) ?? "");

            case "skuavailableitems":
                var sku = new SKUInfo(row.Row);
                int availableItems = sku.SKUAvailableItems;

                // Inventory tracked by variants
                if (sku.SKUTrackInventory == TrackInventoryTypeEnum.ByVariants)
                {
                    return GetString("com.inventory.trackedbyvariants");
                }

                // Inventory tracking disabled
                if (sku.SKUTrackInventory == TrackInventoryTypeEnum.Disabled)
                {
                    return GetString("com.inventory.nottracked");
                }

                // Ensure correct values for unigrid export
                if (sender == null)
                {
                    return availableItems;
                }

                // Tracking by products
                InlineEditingTextBox inlineAvailableItems = new InlineEditingTextBox();
                inlineAvailableItems.Text = availableItems.ToString();
                inlineAvailableItems.DelayedReload = DocumentListingDisplayed;
                inlineAvailableItems.EnableEncode = false;

                inlineAvailableItems.Formatting += (s, e) =>
                {
                    var reorderAt = sku.SKUReorderAt;

                    // Emphasize the number when product needs to be reordered
                    if (availableItems <= reorderAt)
                    {
                        // Format message informing about insufficient stock level
                        string reorderMsg = string.Format(GetString("com.sku.reorderatTooltip"), reorderAt);
                        string message = string.Format("<span class=\"alert-status-error\" onclick=\"UnTip()\" onmouseout=\"UnTip()\" onmouseover=\"Tip('{1}')\">{0}</span>", availableItems, reorderMsg);
                        inlineAvailableItems.FormattedText = message;
                    }
                };

                // Unigrid with delayed reload in combination with inline edit control requires additional postback to sort data.
                // Update data only if external data bound is called for the first time.
                if (!forceReloadData)
                {
                    inlineAvailableItems.Update += (s, e) =>
                    {
                        var newNumberOfItems = ValidationHelper.GetInteger(inlineAvailableItems.Text, availableItems);

                        if (ValidationHelper.IsInteger(inlineAvailableItems.Text) && (-1000000000 <= newNumberOfItems) && (newNumberOfItems <= 1000000000))
                        {
                            CheckModifyPermission(sku);

                            // Ensures that grid will display inserted value
                            sku.SKUAvailableItems = newNumberOfItems;

                            // Document list is used to display products -> document has to be updated to ensure correct sku mapping
                            if (DocumentListingDisplayed)
                            {
                                int documentId = ValidationHelper.GetInteger(row.Row["DocumentID"], 0);

                                // Create an instance of the Tree provider and select edited document with coupled data
                                TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);
                                TreeNode document = tree.SelectSingleDocument(documentId);

                                if (document == null)
                                {
                                    return;
                                }

                                document.SetValue("SKUAvailableItems", newNumberOfItems);
                                document.Update();

                                forceReloadData = true;
                            }
                            // Stand-alone product -> only product has to be updated
                            else
                            {
                                sku.MakeComplete(true);
                                sku.Update();

                                gridData.ReloadData();
                            }
                        }
                        else
                        {
                            inlineAvailableItems.ErrorText = GetString("com.productedit.availableitemsinvalid");
                        }
                    };
                }

                return inlineAvailableItems;

            case "skuprice":

                SKUInfo product = new SKUInfo(row.Row);

                // Ensure correct values for unigrid export
                if (sender == null)
                {
                    return product.SKUPrice;
                }

                InlineEditingTextBox inlineSkuPrice = new InlineEditingTextBox();
                inlineSkuPrice.Text = product.SKUPrice.ToString();
                inlineSkuPrice.DelayedReload = DocumentListingDisplayed;

                inlineSkuPrice.Formatting += (s, e) =>
                {
                    // Format price
                    inlineSkuPrice.FormattedText = CurrencyInfoProvider.GetFormattedPrice(product.SKUPrice, product.SKUSiteID);
                };

                // Unigrid with delayed reload in combination with inline edit control requires additional postback to sort data.
                // Update data only if external data bound is called for the first time.
                if (!forceReloadData)
                {
                    inlineSkuPrice.Update += (s, e) =>
                    {
                        CheckModifyPermission(product);

                        // Price must be a double number
                        double price = ValidationHelper.GetDouble(inlineSkuPrice.Text, -1);

                        if (ValidationHelper.IsDouble(inlineSkuPrice.Text) && (price >= 0))
                        {
                            // Ensures that grid will display inserted price
                            product.SKUPrice = price;

                            // Document list is used to display products -> document has to be updated to ensure correct sku mapping
                            if (DocumentListingDisplayed)
                            {
                                int documentId = ValidationHelper.GetInteger(row.Row["DocumentID"], 0);

                                // Create an instance of the Tree provider and select edited document with coupled data
                                TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);
                                TreeNode document = tree.SelectSingleDocument(documentId);

                                if (document != null)
                                {
                                    document.SetValue("SKUPrice", price);
                                    document.Update();

                                    forceReloadData = true;
                                }
                            }
                            // Stand-alone product -> only product has to be updated
                            else
                            {
                                product.MakeComplete(true);
                                product.Update();

                                gridData.ReloadData();
                            }
                        }
                        else
                        {
                            inlineSkuPrice.ErrorText = GetString("com.productedit.priceinvalid");
                        }
                    };
                }

                return inlineSkuPrice;

            case "publicstatusid":
                int id = ValidationHelper.GetInteger(row["SKUPublicStatusID"], 0);
                PublicStatusInfo publicStatus = PublicStatusInfoProvider.GetPublicStatusInfo(id);
                if (publicStatus != null)
                {
                    // Localize and encode
                    return HTMLHelper.HTMLEncode(ResHelper.LocalizeString(publicStatus.PublicStatusDisplayName));
                }

                return string.Empty;

            case "allowforsale":
                // Get "on sale" flag
                return UniGridFunctions.ColoredSpanYesNo(ValidationHelper.GetBoolean(row["SKUEnabled"], false));

            case "typename":
                string docTypeName = ValidationHelper.GetString(row["ClassDisplayName"], null);

                // Localize class display name
                if (!string.IsNullOrEmpty(docTypeName))
                {
                    return HTMLHelper.HTMLEncode(ResHelper.LocalizeString(docTypeName));
                }

                return string.Empty;
        }

        return parameter;
    }
    /// <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));
        }

        return savedAmount;
    }
    /// <summary>
    /// Returns value of the specified product public status column.
    /// If the product is evaluated as a new product in the store, public status set by 'CMSStoreNewProductStatus' setting is used, otherwise product public status is used.
    /// </summary>
    /// <param name="sku">SKU data</param>
    /// <param name="column">Name of the product public status column the value should be retrieved from</param>
    public static object GetSKUIndicatorProperty(SKUInfo sku, string column)
    {
        // Do not process
        if (sku == null)
        {
            return null;
        }

        PublicStatusInfo status = null;
        string siteName = SiteInfoProvider.GetSiteName(sku.SKUSiteID);
        string statusName = ECommerceSettings.NewProductStatus(siteName);

        if (!string.IsNullOrEmpty(statusName) && SKUInfoProvider.IsSKUNew(sku))
        {
            // Get 'new product' status
            status = PublicStatusInfoProvider.GetPublicStatusInfo(statusName, siteName);
        }
        else
        {
            // Get product public status
            if (sku.SKUPublicStatusID > 0)
            {
                status = PublicStatusInfoProvider.GetPublicStatusInfo(sku.SKUPublicStatusID);
            }
        }

        // Get specified column value
        return GetColumnValue(status, column);
    }