Limit the total amount of discounts applied

Sometimes you’re in need of some business rules when applying promotions. You can do this by overriding the calculation of the discounts, but that could be a lot of work.

For a simple rule, like “the total amount of discounts can’t be more than half of the order total” you could use a different approach.

You can run the promotion engine without actually applying the promotions. This is ‘hidden’ in the promotion engine settings. It will give you all the info as if they were applied.

So in my case the steps were:

  • Run the promotion engine without applying the discounts and only  for fulfilled promotions.
  • Check the amount that is saved, compare it with the total amount in the cart.
  • If less than half, apply the discounts, else don’t. The discounts already applied will stay applied.

public IEnumerable<RewardDescription> ApplyDiscounts(ICart cart)
{
IOrderForm orderForm = cart.GetFirstForm();

if (orderForm == null)
{
return new List<RewardDescription>();
}

decimal total = orderForm.Shipments.Sum(shipment => shipment.LineItems.Sum(item => item.PlacedPrice * item.Quantity));

if (total <= 0)
{
return new List<RewardDescription>();
}

IPromotionEngine promotionEngine = ServiceLocator.Current.GetInstance<IPromotionEngine>();

IEnumerable<RewardDescription> rewards = promotionEngine.Run(
cart,
new PromotionEngineSettings()
{
ApplyReward = false,
RequestedStatuses = RequestFulfillmentStatus.Fulfilled
});

decimal totalDiscount = rewards.Sum(rewardDescription => rewardDescription.SavedAmount);

return totalDiscount <= (total / 2) ? cart.ApplyDiscounts(promotionEngine, new PromotionEngineSettings()) : new List<RewardDescription>();
}

So if you replace your call to cart.ApplyDiscounts with a call to the above method, you have a quick business rule without having to adjust calculators, promotion processors, etc.

 

The code is also available in a Gist

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s