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.
Add a new class CustomEcommerceMacroMethods to your App_Code\CMSModules\Ecommerce\ sub-folder.
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, "categoryGUID", typeof(Guid), "CategoryGUID")] [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); } }
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.
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.
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).
- Open the Store configuration application.
- Switch to the Discount rules -> Order rules tab.
- 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
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})
Click Save.
The system saves the order rule, leaving it open for further editing.
Defining the rule’s parameters
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.
Select number from the parameters list and enter (verify) the following values for its properties:
Field name: number
Field type: Integer number
Required: Yes (checked)
Display field in the editing form: Yes (checked)
Field caption: select number
Form control: Text box
Click Save.
Select category from the parameters list and enter (verify) the following values for its properties:
Field name: category
Field type: Text
Field 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)
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.
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.
Open the Order discounts application.
ClickNew order discount.
- The system opens the New order discount page where you can specify the order discount properties.
Enter the following values for the order discount’s general and value properties:
Name: Computers category discount
Enabled: Yes (checked)
Discount: Percentage
Amount: 10
Specify the discount’s condition:
Click Edit to edit the discount’s Further conditions property.
- This opens the Edit macro condition dialog on the Rule designer tab.
Select the Shopping cart contains products in the given category rule in the right part of the dialog.
Click Add rule () to add the rule to the condition.
Click select number in the left part of the dialog.
- The system opens the Set parameter value dialog for the number parameter.
Enter 2.
Click OK.
- The system closes the Set parameter value dialog for the number parameter. The Edit macro condition dialog is open for editing.
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
Click Select.
- The system opens the Select category dialog.
Select the Computers category.
Click Save & Close.
- The system closes the Select category dialog. The Set parameter value dialog is open for editing.
Click OK.
- The system closes the Set parameter value dialog for the category parameter. The Edit macro condition dialog is open for editing.
Click Save & Close to save the rule’s condition and leave the Edit macro condition dialog.
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
View the live site.
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.
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.
Enter 1 for the amount of product items.
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.
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.
If you now click Check out, you can continue in the checkout process.