Example - Adding an order rule

The example demonstrates how you can add an order rule whose macro condition calls a custom method. Your eligible customers receive a 10% discount on their orders if they add at least two products from the Computers category to their shopping carts.

The example uses the sample E-commerce Site.

Adding a custom class into the system's code

First, you need to add a new class inherited from the MacroMethodContainer class. The class contains a custom method that can be called by discount rules.

  1. Add a new class CustomEcommerceMacroMethods to your App_Code\CMSModules\Ecommerce\ sub-folder.

  2. Add the following code to the class:                      

    The class contains the IsProductInCategoryInShoppingCart custom method that will later be called by the custom order rule.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
     
    using CMS.DocumentEngine;
    using CMS.Ecommerce;
    using CMS.Helpers;
    using CMS.MacroEngine;
    using CMS.SiteProvider;
    using CMS.Taxonomy;
    
    /// <summary>
    /// Summary description for CustomEcommerceMacroMethods
    /// </summary>
    public class CustomEcommerceMacroMethods : MacroMethodContainer
    {
        /// <summary>
        /// Returns true if shopping cart contains at least defined number of products in defined category.
        /// </summary>
        /// <param name="context">Evaluation context with child resolver</param>
        /// <param name="parameters">Method parameters</param>
        [MacroMethod(typeof(bool), "Returns true if shopping cart contains defined number of products in defined category.", 2)]
        [MacroMethodParam(0, "shoppingCart", typeof(ShoppingCartInfo), "Shopping cart")]
        [MacroMethodParam(1, "categoryName", typeof(string), "The name of a page category")]
    	[MacroMethodParam(2, "itemsCount", typeof(int), "Number of items")]
        public static object IsProductInCategoryInShoppingCart(EvaluationContext context, params object[] parameters)
        {
            switch (parameters.Length)
            {
                case 3:
                    return IsProductInCategoryInShoppingCart(parameters);
     
                default:
                    throw new NotSupportedException();
            }
        }
     
     
        private static bool IsProductInCategoryInShoppingCart(object[] parameters)
        {
            ShoppingCartInfo cart = (ShoppingCartInfo)parameters[0];
            string categoryName = ValidationHelper.GetString(parameters[1], String.Empty);
            int minItemsCount = ValidationHelper.GetInteger(parameters[2], 1);
     
            // Get site category info
            CategoryInfo category = CategoryInfoProvider.GetCategoryInfo(categoryName, SiteContext.CurrentSiteName);
            
            // SKU IDs in the shopping cart except product options and variants
            var itemsIds = cart.CartItems
                              .Where(item => !(item.SKU.IsProductOption || item.SKU.IsProductVariant))
                              .Select<ShoppingCartItemInfo, int>(item => item.SKUID)
                              .ToList();
     
            // Get NodeSKUIDs of product pages in the shopping cart in given category
            string wherePages = CategoryInfoProvider.GetCategoryDocumentsWhereCondition(category.CategoryIDPath, false);
    		var pages = DocumentHelper.GetDocuments()
                               .Where(wherePages)
                               .WhereIn("NodeSKUID", itemsIds)
                               .Columns("NodeSKUID").ToList();
     
            // Count the number of product units in given category in the shopping cart
            int count = 0;
            foreach(ShoppingCartItemInfo cartItem in cart.CartItems)
            {
                // If cart item SKUID matches some of product page NodeSKUID in given category
                if (pages.Exists(doc => doc.NodeSKUID == cartItem.SKUID))
                {
                    count += cartItem.CartItemUnits;
                }
            }
            
            return (minItemsCount <= count);
        }
    }

                                     

  3. Register the CustomEcommerceMacroMethods container class by extending the ShoppingCartInfo type. Create a new class in the App_Code folder with the following code:

    using CMS.Base;
    using CMS.Ecommerce;
    
    [MacroMethodLoader]
    public partial class CMSModuleLoader
    {
        /// <summary>
        /// Attribute class ensuring the registration of custom macro methods.
        /// </summary>
        private class MacroMethodLoader : CMSLoaderAttribute
        {
            /// <summary>
            /// Called automatically when the application starts.
            /// </summary>
            public override void Init()
            {
                // Makes the IsProductInCategoryInShoppingCart macro method available for shopping cart objects
                Extend<ShoppingCartInfo>.With<CustomEcommerceMacroMethods>();
            }
        }
    }

    The macro resolver now recognizes the IsProductInCategoryInShoppingCart method for shopping cart objects.

                                 

  4. Save the modified classes. Build your solution if you are using a web application project.

You can now add a new order rule. Because the CustomEcommerceMacroMethods container class is registered, any order discount rule can now call the IsProductInCategoryInShoppingCart custom method for shopping cart objects.

On this page

Adding an order rule

This section demonstrates how you can add an order rule limiting the application of order discounts (free shipping offers). Eligible customers receive a discount on their orders if the orders contain at least N products from a selected product category (if the rule is used in an active order discount).

  1. Open the Store configuration application.
  2. Switch to the Discount rules -> Order rules tab.
  3. Click New order rule.
    • The system opens a new page where you can specify the order rule properties and define the rule's parameters.

      Specifying the rule's properties

    1. Enter the following values for the rule's properties:
      • Display name: Shopping cart contains products in the given category
      • User text: Shopping cart contains at least {number} products in the {category} category
      • Condition: IsProductInCategoryInShoppingCart(ShoppingCart, "{category}", {number})

        Specifying order rule properties
                                             
    2. Click Save.
      • The system saves the order rule, leaving it open for further editing.

        Defining the rule's parameters

    1. Switch to the Parameters tab.
      • You specified two parameters that modify the rule's condition (number, category). That's why the system automatically adds two parameters. You can now adjust the parameters' settings.
                               
    2. Select number from the parameters list and enter (verify) the following values for its properties:
      • Field name: number
      • Data type: Integer number
      • Required: Yes (checked)
      • Display field in the editing form: Yes (checked)
      • Field caption: select number
      • Form control: Text box

        Specifying parameter properties
                                              
    3. Click Save.
    4. Select category from the parameters list and enter (verify) the following values for its properties:
      • Field name: category
      • Data type: Text
      • Size: 2000
      • Required: Yes (checked)
      • Display field in the editing form: Yes (checked)
      • Field caption: select
      • Form control: Category selector
      • Display personal categories: No (unchecked)
      • Display general categories: Yes (checked)

        Specifying parameter properties
                                           
    5. Click Save.

The system adds a new order rule with two parameters. The rule's condition calls the IsProductInCategoryInShoppingCart custom method. You can now use the rule in order discounts.

Available order rules

Adding an order discount

This section demonstrates how you can add an order discount allowing the customers to receive a 10% discount on their orders. The customers receive the discount if their orders contain at least two products from the Computers category.

You can assign products (product pages) to categories while editing the products in the Products application on the Categories tab.

  1. Open the Order discounts application.
  2. Click New order discount.
    • The system opens the New order discount page where you can specify the order discount properties.
                          
  3. Enter the following values for the order discount's general and value properties:
    • Name: Computers category discount
    • Enabled: Yes (checked)
    • Discount: Percentage
    • Amount: 10
                  
      Adding an order discount
                                                 
  4. Specify the discount's condition:

    1. Click Edit to edit the discount's Further conditions property.
      • This opens the Edit macro condition dialog on the Rule designer tab.
                                          
    2. Select the Shopping cart contains products in the given category rule in the right part of the dialog.
    3. Click Add rule () to add the rule to the condition.
    4. Click select number in the left part of the dialog.
      • The system opens the Set parameter value dialog for the number parameter.
                                            
    5. Enter 2.
                        
      Specifying the number of products
                                     
    6. Click OK.
      • The system closes the Set parameter value dialog for the number parameter. The Edit macro condition dialog is open for editing.
                                     
    7. Click select in the left part of the dialog.
      • The system opens the Set parameter value dialog for the category parameter.

        Selecting the product category
                            
      1. Click Select.
        • The system opens the Select category dialog.
                                              
      2. Select the Computers category.
                          
        Specifying the category
                                          
      3. Click Save & Close.
        • The system closes the Select category dialog. The Set parameter value dialog is open for editing.
                                        
      4. Click OK.
        • The system closes the Set parameter value dialog for the category parameter. The Edit macro condition dialog is open for editing.
                                                  
    8. Click Save & Close to save the rule's condition and leave the Edit macro condition dialog.
                                                      
      Specifying the discount condition
                                  
  5. Click Save.

The system saves the order discount. If your customers now add at least two products from the Computers category to their shopping carts, they receive a 10% discount on their orders.

Reviewing the order discount's application

  1. View the live site.
  2. Select Computers -> Laptops in your on-line store main menu.

    • The system displays a list of all laptop computers that you offer in your on-line store.
                       

  3. Click Add to cart in the Sony VAIO Z Series section.

    The product has product options. That's why the system now displays the product's details page.

    Here you can specify the amount of product items.

                                   

  4. Enter 1 for the amount of product items.
  5. Click Add to cart.

    • The system displays the content of your shopping cart. The shopping cart contains only one product assigned to the Computers category. That's why the system doesn't apply the Computers category discount order discount.
                         
      Viewing the shopping cart content
                                                          

  6. Repeat steps 2 through 5 or use the Units field on the Shopping cart page to add another Sony VAIO Z Series laptop to the shopping cart.

    • The system displays the content of your shopping cart with the Computers category discount discount applied on your order.
                                  
      Order discount applied
                        

If you now click Check out, you can continue in the checkout process.