I was asked to developed a solution to apply easily applying discounts to products in a ecommerce store and I tried to do it in the most generic way.
Let's say we have the following products:
- Product A: $5
- Product B: $20
- Product C: $7.50
And we have the following discounts:
- 2-for-1 for the Product A
- If you buy 3 or more items of the Product B, the price per unit should be 19.00€.
To do so, I modeled a class called Pricing Rule that contains the following data:
- min_items: min number of purchased items necessary to apply the discount.
- discounted_items_rate: percentage of products affected by the discount.
- price_reduction: percentage of price reduction applicable to the items with discount.
Using this class, the 2-for-1 discount would be
- min_items: 2. At least there should be 2 items in the cart.
- discounted_items_rate: 0.5. Half of the items will get a discount
- price_reduction: 1. That means, the price reduction will be 100%.
And in a similar way, the 3 or more items of the product B for $19 would be:
- min_items: 3
- discounted_items_rate: 1 (all of them)
- price_reduction: 0.05 ($19 instead of 20$ is a price reduction of the 5%).
I modeled a formula to determine the total price, the formula would be:
(Forget about the correctness of the code, imagine we iterate correctly over the CART and we select the appropriate PRICING_RULE. Imagine the cart like CART = { productA: 10 items, productB: 6 items, .... })
if (CART.PRODUCT.ITEMS > PRICING_RULE.min_items) [It has a discount]
var items_with_discount = floor(CART.PRODUCT.ITEMS * PRICING_RULE.discounted_items_rate)
var with_discount = items_with_discount * price * (1 -PRICING_RULE.price_reduction)
var without_discount = (CART.PRODUCT.ITEMS - items_with_discount) * price
total += (with_discount + without_discount)
else [It does not have a discount]
total += CART.PRODUCT.ITEMS * price
For example if I buy 5 items of the product A, the total price would be 5 * 5 = $25, but I have a 2-for-1 discount, so the price would be $15.
Following the algorithm:
items_with_discount = floor(5 * 0.5) = floor(2.5) = 2
with_discount = 2 * 5 * (1 - 1) = 0
without_discount = (5 - 2) * 5 = 15
total += 0 + 15 = $15
It works for lots of popular discounts (5-for-3, 3-for-1, 8% discount for all products, 3 or more for X-price, .... any typical discount).
I got the feedback that it seems complex, but I actually find it very simple. What is the best way to model an algorithm to apply discounts in a generic way?