Adding a New Link to a Commerce Pipeline

To add new links to a commerce pipeline you need to override the default definition for the appropriate commerce pipeline.  Commerce pipelines are defined in XML so you use ATG’s XML combining feature to accomplish this.

For example if you want to add a new link to the ProcessOrder chain in the /atg/commerce/commercepipeline.xml you would create the following commercepipeline.xml in your local config.

[xml]<pipelinemanager>
<pipelinechain name="processOrder" xml-combine="append">
<pipelinelink transaction="TX_MANDATORY" name="authorizePayment" xml-combine="replace">
<processor jndi="/atg/commerce/order/processor/AuthorizePayment" />
<transition returnvalue="1" link="updateInventory" />
</pipelinelink>
<pipelinelink name="updateInventory" transaction="TX_MANDATORY">
<processor jndi="/betweengo/commerce/inventory/processor/ProcUpdateInventory" />
<transition returnvalue="1" link="updateGiftRepository" />
</pipelinelink>
</pipelinemanager>[/xml]

In this example we added the new updateInventory link which is inserted between the authorizePayment and updateGiftRepository links.

Specifying the Calculator per Promotion

calculator on Flickr

(Photo: calculator by ansik)

ATG’s documentation, as far as I can tell, does not document how to specify the calculator for a promotion.  Promotion’s have a repository property called pricingCalculatorService.  In the ACC you won’t see it by default but you will see it if you show expert-level information.  Also you can see it configured in the Promotion repository (/atg/commerce/pricing/Promotions).

Having a repository property for each promotion allows you to specify different calculators for different promotions.  But typically you will probably specify the same one for the same class of promotion, e.g. /betweengo/commerce/pricing/calculators/ItemDiscountCalculator.

Load ATG Order

Crystal Ball | FlickrCrystal Ball by David Reece

You can always look up an order in the repository using it’s ID.  But then you want to use the properties of this order object you will always be calling getPropertyValue and casting it to the type you expect.

A better and much simpler way is to look up the order using the OrderManager.  Then you get a strongly typed Order object and don’t have have to deal with the repository.  Life has become a little easier. 🙂

OrderManager orderManager = getOrderManager;
Order order = orderManager.loadOrder(orderId);


Now that you have the order you can also get the profile for that order.

RepositoryItem profile = getProfileTools().getProfileForOrder(order);

Limiting the Quantity Added to a Cart

Speed Limit 14 MPH on Flickr

(Photo: Speed Limit 14 MPH by bredgur)

Sometimes the client will ask that the quantity of items you can add to the cart be limited to some number, say 14 like in the photo above. 🙂

Often people will implement this by putting in checks throughout the JSP.  But this is not the best solution because it is more labor intensive and you may miss something.

Another solution is to deal with the issue in the CartModifierFormHandler by extending the doAddItemsToOrder method.  Simply check the quantity of each AddCommerceItemInfo item and make sure that its quantity plus the quantity of the same item already in the cart does not go over the limit.  If it does modify the quantity in the AddCommerceItemInfo item appropriately.

Here is how I implemented this.

    @Override
    protected void doAddItemsToOrder(DynamoHttpServletRequest pRequest,
            DynamoHttpServletResponse pResponse) throws ServletException,
            IOException {

        // fetch the order
        Order order = getOrder();
        if (order == null) {
            String msg = formatUserMessage(MSG_NO_ORDER_TO_MODIFY, pRequest,
                    pResponse);
            throw new ServletException(msg);
        }

        // iterate through the add commerce item infos, making sure that adding
        // any of them will not result in a quantity greater than LIMIT
        AddCommerceItemInfo[] addCommerceItemInfos = getItems();
        for (int ii = 0; ii < addCommerceItemInfos.length; ii++) {

            // see if there is a commerce item already in the order for the next
            // add commerce item info
            AddCommerceItemInfo addCommerceItemInfo = addCommerceItemInfos[ii];
            String catalogRefId = addCommerceItemInfo.getCatalogRefId();
            CommerceItem commerceItem = findCommerceItemByCatalogRefId(order,
                    catalogRefId);
            if (commerceItem == null) {
                continue;
            }

            // check that the quantity we add won't result in a total quantity
            // greater than LIMIT
            long addQty = addCommerceItemInfo.getQuantity();
            long qty = commerceItem.getQuantity();
            if (qty >= LIMIT) {
                addCommerceItemInfo.setQuantity(0);
            } else if (qty + addQty > LIMIT) {
                long newAddQty = LIMIT - qty;
                addCommerceItemInfo.setQuantity(newAddQty);
            }
        }

        super.doAddItemsToOrder(pRequest, pResponse);
    }

    protected CommerceItem findCommerceItemByCatalogRefId(Order pOrder,
            String pCatalogRefId) {
        for (int ii = 0; ii < numCommerceItems; ii++) {
            CommerceItem commerceItem = (CommerceItem) commerceItems.get(ii);
            String catalogRefId = commerceItem.getCatalogRefId();
            if (catalogRefId.equals(pCatalogRefId))
                return commerceItem;
        }
        return null;
    }

NullPointerException in ATG OrderDiscountCalculator

calculator on Flickr

(Photo: calculator by ansik)

There is a bug in the ATG OrderDiscountCalculator which causes a NullPointerException (NPE) under certain conditions.  Fortunately ATG provides the source for this class (I wish they did for all their classes or at least a larger subset of them) so it was pretty simple to figure out why this was happening.

The OrderDiscountCalculator assumes that the taxableShippingGroupSubtotalInfo local will not be null.  If it is an NPE will result when this local is referenced and the page that called this calculator will crash.

The simple fix is to check if it is null and if it is to continue to the next shipping group.

if (taxableShippingGroupSubtotalInfo == null) {
  continue;
}

At my request ATG Support has filed a problem report, NullPointerException in OrderDiscountCalculator.

Update 12-17-2009: ATG may have fixed this issue for ATG 9.1 p1, NPE in OrderDiscountCalculator w/empty shipping groups in Order.

How to Add Multiple Items to the Shopping Cart in ATG

Red Cart Conga, Baby on Flickr

(Photo: Red Cart Conga, Baby by It’sGreg)

ATG’s CartModifierFormHandler has a handle method for adding multiple items to the shopping cart, handleAddMultipleItemsToOrder.

<dsp:input type="submit" bean="CartModifierFormHandler.addMultipleItemsToOrder" />

What is required is that in the request you set the product ID and SKU ID (catalogRefId) for each product you want to add.

<dsp:input bean="CartModifierFormHandler.productIds" paramvalue="product.id" type="hidden" />
<dsp:input bean="CartModifierFormHandler.catalogRefIds" paramvalue="sku.id" type="hidden" />

Seems pretty-straightforward, right?  Well there are a couple of tricks.

Trick #1: Setting the quantity

Setting the quantity of the amount of each SKU you want added to the cart requiring naming the quantity input using the SKU iD.

<input type="text" name="<dsp:valueof param="sku.id"/>" />

Trick #2: Handling zero quantity inputs

When the handleAddMultipleItemsToOrder tries to add something that has a quantity of zero or less you it will output an error message that the quantity is zero or less.  If you have a input form where the user does not have to add all the items on the page then this will be problematic.

To get around this restriction I overrode the preAddMultipleItemsToOrder method.  My method sets the productIds and catalogRefIds properties to only have items that have a quantity greater than zero.

public void preAddMultipleItemsToOrder(DynamoHttpServletRequest pReq,
    DynamoHttpServletResponse pRes) throws ServletException,
    IOException {

  // get the SKU ID's and product ID's set in the form
  String[] oldCatalogRefIds = getCatalogRefIds();
  String[] oldProductIds = getProductIds();

  // make sure that the SKU ID's and product ID's are valid and of the
  // same length
  if (oldCatalogRefIds == null || oldCatalogRefIds.length == 0)
    return;
  if (oldProductIds == null || oldCatalogRefIds.length != oldProductIds.length) {
    return;
  }

  // initialize list for the SKU ID's and product ID's that we will add to
  // the shopping cart
  List newCatalogRefIdsList = new ArrayList(
      oldCatalogRefIds.length);
  List newProductIdsList = new ArrayList(
      oldCatalogRefIds.length);

  // iterate through original SKU ID's
  for (int ii = 0; ii < oldCatalogRefIds.length; ii++) {

    // get next SKU ID
    String catalogRefId = oldCatalogRefIds[ii];

    // get quantity requested for that SKU ID
    long qty;
    try {
      qty = getQuantity(catalogRefId, pRequest, pResponse);
    } catch (NumberFormatException exc) {
      if (isLoggingDebug())
        logDebug("invalid quantity for catalogRefId=" + catalogRefId, exc);
      qty = 0;
    }

    // if quantity > 0 then save this SKU ID and it's product ID
    if (qty > 0) {
      newCatalogRefIdsList.add(catalogRefId);
      String productId = oldProductIds[ii];
      newProductIdsList.add(productId);
    }
  }

  // set the catalog ID's property to only have the SKU ID's of things
  // that are being ordered
  String[] newCatalogRefIds = new String[newCatalogRefIdsList.size()];
  newCatalogRefIdsList.toArray(newCatalogRefIds);
  if (isLoggingDebug()) {
    logDebug("old catalogRefIds=" + Arrays.toString(oldCatalogRefIds)
        + ", new catalogRefIds="
        + Arrays.toString(newCatalogRefIds));
  }
  setCatalogRefIds(newCatalogRefIds);

  // set the product ID's property to only have the product ID's of things
  // that are being ordered
  String[] newProductIds = new String[newProductIdsList.size()];
  newProductIdsList.toArray(newProductIds);
  if (isLoggingDebug()) {
    logDebug("old productIds=" + Arrays.toString(oldProductIds)
        + ", new productIds="
        + Arrays.toString(newProductIds));
  }
  setProductIds(newProductIds);
}

Update Profile in ATG Commerce

Wolf portrait 3 on Flickr
(Photo: Wolf portrait 3 by Tambako the Jaguar)

ProfileTools provides methods for updating a profile.  In ATG Commerce you can access the ProfileTools via the CommerceProfileTools.

Therefore to update a profile it is as simple as calling the update methods in ProfileTools.

getCommerceProfileTools().updateProperty(propertyName,
                                         property, getProfile());

getCommerceProfileTools().updateProperty(propertyTable, getProfile());

The update methods get the MutableRepositoryItem for the profile, set the property in the MutableRepositoryItem and then update the item in the ProfileRepository.

Pretty simple, eh? 🙂

How to Debug an InvalidVersionException from Updating an ATG Order

I thought I saw a puddy cat.... on Flickr

If you ever update an order outside of a transaction then the next time you update it within a transaction you will get the infamous, dreaded InvalidVersionException.

WARN  atg.commerce.order.ShoppingCartModifier
atg.commerce.order.InvalidVersionException: This order (o3830002) is out of date. Changes have been made to the order and the operation should be resubmitted. Order version 333, Repository item version 334.
   at atg.commerce.order.OrderManager.updateOrder(OrderManager.java:2557)

For example this could happen if you update your order in your JSP page.

<dsp:setvalue bean=”order.foo” value=”bar” />

To fix this problem you must always make sure to update an order within a transaction like this.

Transaction tr = null;
try {
  tr = ensureTransaction();
  synchronized (getOrder()) {
    getOrder().setFoo("bar");
    try {
      getOrderManager().updateOrder(order);
    }
    catch (Exception exc) {
      processException(exc, MSG_ERROR_UPDATE_ORDER, pRequest, pResponse);
    }
  }
}
finally {
  if (tr != null) commitTransaction(tr);
}

In some cases you might find a method is called within a transaction by another method and in other cases it is not.

public boolean handleFoo(DynamoHttpServletRequest req, DynamoHttpServletResponse res) {
  Transaction tr = null;
  try {
    tr = ensureTransaction();
    synchronized (getOrder()) {
      setFoo("bar");
      try {
        getOrderManager().updateOrder(order);
      }
      catch (Exception exc) {
        processException(exc, MSG_ERROR_UPDATE_ORDER, pRequest, pResponse);
      }
    }
    return checkFormRedirect(getSuccessUrl(), getErrorUrl(), req, res);
  }
  finally {
    if (tr != null) commitTransaction(tr);
  }
}

public void setFoo(String foo) {
  getOrder().setFoo(foo);
}

In the above example the handleFoo method properly updates the order within the transaction.  However calling the setFoo method directly will cause a problem since the order is not updated within a transaction.  To fix this you use the same pattern again to ensure the order is updated within a transaction.  It is okay to do this more than once during a request.

To debug this problem you can use Eclipse to make sure that wherever you update an order is always within a transaction. You can use the debugger to find which methods are called and/or you can use the call hierarchy to find out how methods are called.

Another way to help debug this is adding JSP code similar to the one I list below. It outputs the version of the order that the form handler has and the version that is in the repository.  If there is a difference then you know that the action you took before at some point updated the order outside of a transaction.

<dspel:getvalueof bean="ShoppingCartModifier.order.id" var="orderId" />
FORM HANDLER ORDER ID: ${orderId}<br/>
FORM HANDLER ORDER VERSION: <dsp:valueof bean="ShoppingCartModifier.order.version" /><br/>
<dsp:droplet name="/atg/dynamo/droplet/RQLQueryForEach">
  <dsp:param name="queryRQL" value="ID IN { \"${orderId}\" }"/>
  <dsp:param name="repository" value="/atg/commerce/order/OrderRepository"/>
  <dsp:param name="itemDescriptor" value="order"/>
  <dsp:oparam name="output">
    REPOSITORY ORDER VERSION: <dsp:valueof param="element.version"/><br/>
  </dsp:oparam>
</dsp:droplet>

For further reading please see Nabble – ATG Dynamo – Commerce Assist Returns and the Transaction Management section in the ATG Programming Guide.

How to Add Products to Categories using Content Groups

Typically after you create a category in your catalog you then add products to the category.  The simple way to do that in ATG eCommerce is to use the ACC and add products to the child products property of the category.  However there is another way.

In the ATG Commerce Guide to Setting Up a Store documentation you can see in the Viewing the Product Catalog section that a category can have child products but also child product groups.

Product Catalog

Child product groups are actually content groups which are described in the Creating Content Groups chapter of the ATG Personalization Guide for Business Users.

Targeting > Profile and Content Groups window

Though the documentation shows a content group composed of features you can easily create a content group using the ProductCatalog as a content source and product as a content type.

To create a content group follow the steps in the ATG documentation for Creating New Content Groups except use an item from the ProductCatalog when specifying the Content Type.  Then create the targeting rules for this Content Group.  Now you can specify this group in the Child products (group) property of a category.

ATG Product Bundles

what's in my sxsw schwag bag - photo by joey.parsons - Flickr

Out of the box ATG eCommerce does not support product bundles.  It does support SKU bundles, i.e. a product can consist of multiple SKU’s.

To support product bundles is pretty simple to implement.

First you create a new type of product for bundles in /atg/commerce/catalog/productCatalog.xml.

<item-descriptor name="product">
 <table name="dcs_product">
  <property name="type" data-type="enumerated" default="regular">
   <attribute name="useCodeForValue" value="false"/>
   <option value="regular" code="0"/>
   <option value="bundle" code="1" />
 </property>
 </table>


Then you define your bundles product to have the new products property. This property is simply a list of products that the bundle contains, e.g. Costco organic cotton polo shirt and Nike athletic shorts.

<item-descriptor name="bundle" super-type="product" sub-type-value="bundle">
 <table name="betweengo_product_bundle" multi-column-name="seq_num"
  type="multi" id-column-names="product_bundle_id">
  <property name="products" column-name="product_id" data-type="list"
   component-item-type="product" display-name="Products" category="Bundle" />
 </table>
</item-descriptor>

A few years ago I did a more advanced version of this implementation which allowed for different numbers of products in one bundle, e.g. two different kinds of shirts and one pair of pants.  I did this using the concept of product links which is similar to SKU links that ATG supports.

If you are interested in wanting to implement a more advanced version please contact us.