Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 28 ยท Projects

Project: Product Badges and Delivery Estimates

Build product badges and delivery estimates in Salesforce B2C Commerce: custom attributes, model decorators, ISML snippets and the effect on page caching.

Merchants love two small additions to a product tile: a badge ("New", "Bestseller", "Eco") and a delivery estimate ("Arrives Wed 12 โ€“ Fri 14"). They are small to build and surprisingly instructive, because they touch every layer you have learned: custom attributes on the product, a model decorator, an ISML snippet, and, most importantly, the page cache. A delivery date depends on today's date and the time of day, and a tile on a category page may be cached for a day. Get the design wrong and shoppers see promises you cannot keep.

This project builds the feature in four parts: data, decorators, template and caching strategy. You will need Catalog, Products and Price Books, Models, Decorators and Helpers, ISML Templates and Caching and Performance. The real cartridge code is read-only because it needs a B2C Commerce sandbox. The TryIt blocks are stand-ins: the date logic is ordinary JavaScript that you can run and adapt, and the decorators are modeled on plain objects. Each says clearly what it represents.

The design

flowchart LR
    A["Product custom attributes<br/>badge, launchDate, leadTimeDays"] --> B["productTile model<br/>(extended via superModule)"]
    B --> C["badge decorator"]
    B --> D["deliveryEstimate decorator"]
    D --> E["deliveryHelpers<br/>(pure date logic)"]
    C --> F["ISML snippet on the tile"]
    D --> F
    F --> G["Cache decision:<br/>relative text or live include"]

Data lives on the product, rules live in small testable functions, and the cache strategy is a deliberate decision.

Part 1: custom attributes

Three attributes on the Product system object (see Custom Objects and System Object Extensions):

Attribute Type Meaning
badge enum of strings A badge the merchant sets by hand: bestseller, eco or none
launchDate date When the product launched; used to show "New" automatically
leadTimeDays integer Business days of handling before the product ships
XML
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.demandware.com/xml/impex/metadata/2006-10-31">
    <type-extension type-id="Product">
        <custom-attribute-definitions>
            <attribute-definition attribute-id="badge">
                <display-name xml:lang="x-default">Badge</display-name>
                <type>enum-of-string</type>
                <mandatory-flag>false</mandatory-flag>
                <externally-managed-flag>false</externally-managed-flag>
                <select-multiple-flag>false</select-multiple-flag>
                <value-definitions>
                    <value-definition>
                        <display xml:lang="x-default">Bestseller</display>
                        <value>bestseller</value>
                    </value-definition>
                    <value-definition>
                        <display xml:lang="x-default">Eco-friendly</display>
                        <value>eco</value>
                    </value-definition>
                </value-definitions>
            </attribute-definition>
            <attribute-definition attribute-id="launchDate">
                <display-name xml:lang="x-default">Launch date</display-name>
                <type>date</type>
                <mandatory-flag>false</mandatory-flag>
                <externally-managed-flag>false</externally-managed-flag>
            </attribute-definition>
            <attribute-definition attribute-id="leadTimeDays">
                <display-name xml:lang="x-default">Handling time (business days)</display-name>
                <type>int</type>
                <mandatory-flag>false</mandatory-flag>
                <externally-managed-flag>false</externally-managed-flag>
            </attribute-definition>
        </custom-attribute-definitions>
    </type-extension>
</metadata>

Using an enum for the badge keeps the values controlled: the template and the translation keys (badge.bestseller) can rely on a short, known list instead of free text. Remember that variation products can take attributes from the master, so decide where merchants will maintain them.

Part 2: the badge rule

The rule is: a badge set by the merchant wins; otherwise a product launched in the last 30 days is "new"; otherwise there is no badge. Keeping the rule as a plain function with the date passed in makes it easy to test.

JS Stand-in: the badge decorator on plain objects

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The future launch date gives no badge, and a product with no data simply has none: decorators must cope with missing attributes, because most products will not have them.

Part 3: the delivery estimate

An honest estimate has four inputs: the handling time of the product, the cutoff hour for same-day processing, the carrier transit range and the calendar (weekends and holidays are not business days). The algorithm used here:

  1. Handling starts today if it is a business day and the order comes in before the cutoff; otherwise on the next business day.
  2. The ship date is the start plus leadTimeDays business days.
  3. Delivery is a range: ship date plus the minimum and maximum transit business days.

This is a deliberately simple model, good enough for a tile. Real carriers publish more complex rules, and the "right" estimate may come from a service (Service Framework and Third-Party Integrations). Keep the pure date logic separate from the platform so you can test it:

JS Stand-in: delivery estimate with cutoff, weekends and holidays

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read two rows closely. The Monday 16:00 order misses the cutoff, so handling starts Tuesday. The Saturday order starts on Monday. The last row crosses the holiday: two business days of handling from Monday skip Wednesday 19th.

In the cartridge, the real helper is the same logic in ES5-style code (var, function expressions; keep the syntax conservative, see The Script API and Common Classes). The platform side supplies "now" and the settings:

JavaScript
'use strict';

var Site = require('dw/system/Site');
var Calendar = require('dw/util/Calendar');

/**
 * @returns {{ iso: string, hour: number }} the current date and hour in the site's time zone
 */
function siteNow() {
    var cal = Site.getCalendar();
    var month = cal.get(Calendar.MONTH) + 1;
    var day = cal.get(Calendar.DAY_OF_MONTH);
    return {
        iso: cal.get(Calendar.YEAR) + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day,
        hour: cal.get(Calendar.HOUR_OF_DAY)
    };
}

function getConfig() {
    var site = Site.getCurrent();
    return {
        cutoffHour: site.getCustomPreferenceValue('deliveryCutoffHour') || 14,
        transitMin: site.getCustomPreferenceValue('deliveryTransitMin') || 2,
        transitMax: site.getCustomPreferenceValue('deliveryTransitMax') || 4
    };
}

module.exports = { siteNow: siteNow, getConfig: getConfig };

Cutoff and transit times are site preferences, so merchants and operations can change them without a deployment. Check the details of the Calendar class on your platform release before relying on the sketch above.

Part 4: extending the tile model

The tile model is extended with module.superModule, so the base cartridge stays untouched (SFRA Architecture and Request Flow). The function signature of the base model differs between SFRA versions, so mirror what your version exports:

JavaScript
'use strict';

var base = module.superModule;
var badgeDecorator = require('*/cartridge/models/product/decorators/badge');
var deliveryDecorator = require('*/cartridge/models/product/decorators/deliveryEstimate');

module.exports = function productTile(product, apiProduct, productType) {
    base.call(this, product, apiProduct, productType);
    badgeDecorator(product, apiProduct);
    deliveryDecorator(product, apiProduct);
    return product;
};

Place this at cartridge/models/product/productTile.js in a cartridge that sits before the base on the path. If another cartridge already overrides the tile model, extend that one instead; the chain only works if each layer calls its superModule.

Part 5: the ISML snippet

The template prints only what the model provides, with output encoding:

HTML
<isif condition="${product.badge}">
    <span class="product-badge product-badge--${product.badge.id}">
        <isprint value="${Resource.msg('badge.' + product.badge.id, 'product', null)}" encoding="htmlcontent"/>
    </span>
</isif>
<isif condition="${product.delivery}">
    <p class="delivery-note"><isprint value="${product.delivery.text}" encoding="htmlcontent"/></p>
</isif>

The class suffix comes from the enum value, a controlled list, which is another reason to use an enum rather than free text.

Part 6: what caching does to your estimate

Now the important design question. A category page with 24 tiles is cached for hours (see Caching and Performance). If each tile prints "Arrives Wed 12 โ€“ Fri 14", the text is frozen at the moment the page was cached. Tomorrow it is wrong. If the cutoff passes at 14:00, it is wrong at 14:01. And a page cached for everyone cannot depend on the shopper's address anyway.

Your options, from simplest to most precise:

  1. Relative text on tiles: "Ships in 1 to 2 business days". It only depends on the product's leadTimeDays, so it stays true for as long as the cache lives. This is the best choice for lists.
  2. Date text on the product page with a short cache: use a shorter cache lifetime or a daily expiry for the include that prints the date, so the text never lives longer than the information it contains.
  3. Client-side date: the cached HTML contains data-lead-time and the cutoff, and a small script computes the date in the browser. The page stays fully cacheable, at the price of a script (and the browser's clock).
  4. A separate remote include for the estimate, with its own cache time, as described in the caching lesson.

The final stand-in compares the strategies after the cache has been alive for a day:

JS Stand-in: what a cached tile says a day later

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The absolute text is one day stale on Tuesday, which is exactly the bug that appears in production when the date is rendered into a long-lived cached fragment. Relative text and client-side computation both stay correct.

Testing and rollout

  • Unit test badgeFor and estimateDelivery with the cases above, including a holiday, a weekend, a missing attribute and a date just before and after the cutoff (Testing, Debugging and Logging).
  • Import the metadata and a few sample products first, then check a category page and the product page with the Storefront Toolkit's cache information.
  • Document who maintains badge, launchDate and leadTimeDays, and what happens when they are empty.
  • Make sure checkout does not promise more than the tile: if the estimate is only indicative, say so in the copy.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the badge attribute modeled as an enum of strings rather than free text?

    A controlled list avoids typos and lets the template use the value as a CSS suffix and translation key. Merchants pick from a menu instead of typing.
  2. 2. A shopper orders on Monday at 16:00, the cutoff is 14:00 and the lead time is 1 business day. When does handling start?

    The order misses the cutoff, so the first handling day is the next business day. The ship date is then one business day after that.
  3. 3. Why is an exact date risky on a tile that is cached for 24 hours?

    A cached fragment is served unchanged to everyone until it expires. Anything that depends on the current date or time has to be relative, short-lived or computed on the client.
  4. 4. What is the benefit of putting the cutoff hour and transit days in site preferences?

    Preferences are configuration, not code. Changing a carrier cutoff should not require a release.

Summary

  • Store merchant-controlled data as custom attributes (an enum for badges, a date for launch, an integer for lead time) and keep rules in small pure functions.
  • Extend the tile model through module.superModule, and add one decorator per concern.
  • A delivery estimate needs handling time, a cutoff, a transit range and a business calendar; keep settings in site preferences.
  • Dates computed at render time go stale inside cached HTML: prefer relative text on lists, short-lived includes for exact dates, or client-side computation.
  • Encode every printed value and use enums for CSS suffixes.
  • The TryIt blocks are stand-ins: the date logic is real JavaScript you can reuse, the platform objects are modeled with plain data.

Next: Project: Order Export Job and Integration