Commerce
Limiting the Quantity Added to a Cart
by Frank Kim on Jan.14, 2010, under Commerce
(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
by Frank Kim on Dec.15, 2009, under Commerce
(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
by Frank Kim on Nov.02, 2009, under Commerce
(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
by Frank Kim on Sep.08, 2009, under Commerce
(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
by Frank Kim on Aug.17, 2009, under Commerce
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
by Frank Kim on Jul.31, 2009, under Commerce, Personalization
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.
Child product groups are actually content groups which are described in the Creating Content Groups chapter of the ATG Personalization Guide for Business Users.
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
by Frank Kim on Jul.29, 2009, under Commerce
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.
ATG Consulting Interview
by Frank Kim on Mar.10, 2008, under Commerce, Form Handlers, Java SE, Nucleus, Repository
Today I had the most detailed but at same time most interesting ATG consulting interview yet. Here are the questions I was asked with answers when appropriate in italics.
- Which versions of ATG have you worked with?
- What parts of ATG’s stack have you worked with?
- How do you compare ATG with Ruby on Rails?
- What is Nucleus?
- What is the ATG Repository?
- When creating form handlers typically what ATG base class do you extend? GenericFormHandler.java
- When creating droplets what ATG base class do you extend? DynamoServlet.java
- What form handlers and methods do you use during checkout? ShoppingCartFormHandler, numerous handlers like handleMoveToConfirm, etc.
- What does a user typically see during checkout? Add to shopping cart, login, billing and shipping address, payment, confirm, confirmation, email confirmation, shipped email.
- How do you compare strings in Java? If String a = “hello” and String b= “hello” what is a == b? True, a and b both reference the same constant string.
In another interview I was asked these questions.
- What is HTTP? How does it work?
- If HTTP is stateless then how does a web application maintain state.
Shop.com Product Display Integration
by Frank Kim on Feb.11, 2008, under Commerce, Commons
Last year for Casual Male I did the Shop.com Product Display Integration (PDI) which allows Casual Male to sell its products on Shop.com.
The integration involved three steps.
- Access all the products organized by category using ATG’s GSA Repository.
- Export the products into an XML file according to the PDI DTD using the XStream library.
- FTP upload to Shop.com’s servers using Apache Commons Net library.
Persisting Orders
by Frank Kim on Dec.10, 2007, under ACC, Commerce
When troubleshooting orders it is really helpful to be able to view the order in the ACC.
By default orders are saved because persistOrders property of the /atg/commerce/ShoppingCart component is set to true. If you don’t see incomplete orders being saved then this means this property is not set to true.
More information on Troubleshooting Order Problems can be found in the ATG Commerce Programming Guide.






