April 02, 2018
Step by step guide to help avoid duplicate line-items due to misaligned letter casing
Not everyone is aware, but the SerializableCart in Optimizely Commerce is by default case sensitive on SKU. It means that features relying on a free-form approach to add to cart features, like Order Entry, potentially creates duplicate line items, which might skew your cart experience and influence your marketing promotions.
Instead of always validating the entry against your catalogue, to apply the right upper casing, you can rely on these snippets to continuously enforce a similar business rule.
static class OrderGroupExtensions
{
public static void UpdateCasingOnLineItems(this IOrderGroup orderGroup)
{
if (!(orderGroup is ICart))
return;
foreach (IShipment shipment in orderGroup.Forms.SelectMany(form => form.Shipments))
{
//All line items that are not all upper case
foreach (SerializableLineItem lineItem in shipment.LineItems.Where(lineItem => !lineItem.Code.ToUpper().Equals(lineItem.Code, StringComparison.InvariantCulture))
.OfType<SerializableLineItem>()
.ToList())
{
lineItem.Code = lineItem.Code.ToUpper();
}
}
}
public static void MergeDuplicateLineItemsIfAny(this IOrderGroup orderGroup)
{
if (!(orderGroup is ICart))
return;
foreach (IShipment shipment in orderGroup.Forms.SelectMany(form => form.Shipments))
{
foreach (ILineItem lineItem in shipment.LineItems.ToList())
{
if(!shipment.LineItems.Contains(lineItem))
continue;
IEnumerable<ILineItem> duplicates = shipment.LineItems.Where(l => l.LineItemId != lineItem.LineItemId && l.Code.Equals(lineItem.Code, StringComparison.OrdinalIgnoreCase)).ToList();
if (duplicates.Any())
{
lineItem.Quantity += duplicates.Sum(l => l.Quantity);
duplicates.ForEach(l =>
{
shipment.LineItems.Remove(l);
});
}
}
}
}
}
It’s a two-part exercise – first and foremost, we iterate through the entire cart and modify the letter casing across all inconsistent line items. Secondly, potential conflicting SKUs are now merged to a single line item to avoid line duplication.
Similarly to the way you use existing workflows within Optimizely Commerce, you can now execute these processes as part of your cart validation.
cart.UpdateCasingOnLineItems();
cart.MergeDuplicateLineItemsIfAny();
Very simple, yet highly practical.
Original article was posted on Optimizely Fellow Blog: http://fellow.aagaardrasmussen.dk/2018/04/02/avoid-duplicate-line-items-due-to-misaligned-letter-casing/