Together with Willem Haring of Sitecore Benelux, I did a talk at SUGCON 2017 in Amsterdam about the new Sitecore Commerce Engine. To demonstrate the flexibility and extensibility of the Sitecore Commerce Engine I demonstrated how you can create a new condition (or qualification) to use in promotions.

The background story for this sample should be quite familiar when you're working in e-commerce: Someone from marketing approaches you with the following question:

"It's summer so we want to create a promotion that kicks in when the outside temperature is above 25 degrees centigrade. Is that possible?"

If this was the old Commerce Server your answer would definitely be "NO". But new Commerce Server is different: in fact, creating a new condition is quite easy to do.

You can find the code on GitHub (https://github.com/commerceengineplugins/conditions)

Creating a new condition

I created a condition that returns true when the current temperature in the city you specify is above the temperature you specify. Otherwise it returns false.

The user of the promotion can specify three parameters:

  • Minimum temperature
    If the current temperature in the city you specify is above this value, the condition returns true.
  • City
    The city you want to retrieve the temperature for.
  • Country
    The country code for the specified city.

The project uses two Commerce Engine concepts: Conditions and Policies.

Where to get weather information?

The sample uses the OpenWeatherMap API which supplies current weather information. They have a free plan which is excellent to use for this sample. You need an API key to use their current weather API. Create a free account and generate an API key.

MinTemperatureCondition

The class MinTemperatureCondition implements three interfaces: ICartsCondition, ICondition and IMappableRuleEntity. Commerce Engine automatically adds the condition to the UI based on these interfaces.

To create a condition you only need to implement ICondition's Evaluate method.

WeatherServiceClientPolicy

You need to supply the engine with the correct API key so the WeatherService class can access the OpenWeatherMap API. Of course, you don't want to hard-code this key.

You can use a policy to configure the API Key for each environment. The WeatherServiceClientPolicy is a simple class derived from Policy. It contains one property ApplicationId that contains the API key you get from OpenWeatherMap.

To configure a Commerce environment, add the following JSON to the environment file:

{
    "$type": "Plugin.Sample.Condition.Policies.WeatherServiceClientPolicy, Plugin.Sample.Condition",
    "ApplicationId": "<your application id>"
}

Adding the plugin to a project

To add the plugin to a Commerce Engine just add a reference to it. It's that simple.