Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 40 ยท Pricing, Promotions, Tax

Building a Promotions Engine

Design an e-commerce promotions engine: percent, fixed, BOGO and free-shipping discounts, coupons, stacking rules, usage limits, proration and audit logs.

Sooner or later someone in marketing says: "Can we do 10% off orders over 300, buy-one-get-one on lamps, and a welcome coupon that works with all of it, except during the flash sale?" A promotions engine is the part of the shop that answers that sentence in code without turning into a pile of if statements.

A good engine is a small, boring machine: conditions decide if a promotion applies, actions compute an amount, priority and stacking rules decide the order and what combines, and every discount is recorded line by line so you can explain it later. This lesson builds one in Python. It works on integer cents, as in Representing Money Correctly, and sits on top of the prices from Pricing Models.

Discount types

Almost every promotion you will meet is one of four kinds:

Type Example Notes
Percent 10% off the cart or a category Needs a rounding rule
Fixed amount 5.00 off Capped so it never makes a total negative
BOGO / quantity deal Buy 1 get 1 free, 3 for the price of 2 Needs a rule for which items are free (usually the cheapest)
Free shipping Free delivery over 200 Touches shipping, not product lines

Price changes such as "set the price to 19.00" or a member price are better modeled as price lists, which are covered in the previous lesson. Promotions subtract from a price that has already been resolved.

Coupons versus automatic promotions

An automatic promotion applies whenever its conditions are true: nobody has to type anything. A coupon (promo code) also requires the customer to supply a code. The engine treats both the same way, with one extra condition: "was this code entered?"

Coupons bring extra concerns:

  • Validation messages. "Code not found", "expired", "minimum not reached" and "already used" are different answers; shoppers deserve the real one.
  • Per-customer limits. One use per account or email, which needs a redemptions table.
  • Global limits. The first 500 redemptions. This is a race condition in disguise, so use an atomic counter, as in Reservations and Overselling.
  • Guessable codes. SAVE10 will be tried by bots. Use long random codes for private offers and rate-limit the entry field.

Conditions and actions

Think of each promotion as a pair: when and what.

  • Conditions (all must be true): minimum subtotal, specific SKUs or categories in the cart, customer group, first order only, date window, channel, number of previous orders.
  • Actions: take X percent off the matching lines, take a fixed amount off, make the cheapest N units free, discount the shipping.

Keep conditions and actions as data (a database row or a small structure), not as one if branch per campaign. New campaigns then become configuration, and the engine stays small and testable.

Stacking, priority and exclusions

When several promotions qualify, you need rules for order and combination. Settle these on paper first:

  1. Priority. Promotions run in a fixed order. Percentage discounts usually run before fixed-amount ones, because 10% of a smaller number is a smaller discount; the order changes the total, so decide it deliberately.
  2. Base for percentages. Does the percent apply to the original price or to the price after earlier discounts? "Sequential" is the common choice (each promotion sees the remaining total).
  3. Stackable flag. Some promotions are exclusive: once applied, nothing else may be.
  4. Exclusions. "Not valid on already-discounted items" or "not on gift cards" is a condition on the lines, not a special case in code.
  5. Best-of rule. Some shops let several competing promotions qualify but apply only the one that saves the customer the most. That needs the engine to compute all candidates first.
flowchart TD
    C["Cart + entered codes"] --> S["Sort promotions by priority"]
    S --> E{"Conditions met?<br/>codes, limits, exclusive"}
    E -->|"no"| L["Log: skipped + reason"]
    E -->|"yes"| A["Compute amount"]
    A --> P["Prorate across matching lines"]
    P --> R["Record discount rows<br/>on each line"]
    R --> N{"Next promotion"}
    L --> N
    N --> S

The engine walks the promotions in priority order and logs both what it applied and what it skipped.

Proration across lines

A cart-level discount must be split across the lines, even though the customer only sees one number. You need line-level amounts for three reasons: tax is calculated per line, a refund of one item must return the right share of the discount, and reports by product need true revenue.

The split must add up exactly. If a 5.00 coupon is split over three lines proportionally and each share is rounded separately, you can end up with 4.99 or 5.01. The fix is the largest remainder method: give each line the rounded-down share, then hand the leftover cents, one at a time, to the lines with the biggest fractional parts. The allocate function below does this.

Usage limits and auditability

Two more requirements turn a demo into a system you can trust:

  • Limits: total redemptions, per-customer redemptions, and per-order maximum discount. Count a redemption only when the order is placed (or paid), not when a cart is merely priced, or abandoned carts will use up your coupons.
  • Audit trail: for every order keep which promotion applied, to which line, for how many cents, and why others were skipped. When a customer or finance asks "where did this 4.30 go?", the answer should be a query, not a guess.

A promotions engine you can run

The engine below sorts promotions by priority, checks codes, limits and exclusivity, computes percent, fixed and BOGO amounts with exact proration, and returns a log. BOGO here frees the cheaper half of the matching units. The percent rounding rounds down, which is the shop-friendly default (the shopper never receives more than the stated percent).

Python A priority-based promotions engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the first scenario carefully. The cart is worth 403.00 (40,300 cents). AUTO10 takes 10% (4,030), LAMP-BOGO makes one of the three lamps free (3,500), the welcome coupon takes 500 spread over the three lines, and the shipping code removes the 9.00 delivery charge. The coupon's 5.00 lands on the lines as 3.42 + 0.91 + 0.67, which adds to exactly 500 cents. The goods total is 322.70. In the second scenario the exclusive FLASH50 runs first by priority, takes half of the cart and blocks every other promotion, each with an explicit log entry. In the third the flash code is used up, so it is skipped with a reason and the automatic promotions price the cart as usual.

Testing the engine

Promotions are a bug magnet because the interactions explode. A few habits keep them sane:

  • Write table-driven tests: a cart, a set of promotions, expected per-line discounts and totals.
  • Test boundaries: exactly at the minimum, one cent below, a coupon larger than the cart, a quantity of zero.
  • Test idempotency: pricing the same cart twice must give the same answer and must not consume a redemption. Only order placement does that.
  • Test that line discounts add up to the order discount, always.

When two promotions seem to conflict, resist adding a special case. Add a general rule (a priority, an exclusive flag or a best-of rule) and a test that documents it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should a cart-level discount be split across the line items?

    Taxes are computed per line, a partial refund must return the right share of the discount, and revenue per product must be accurate.
  2. 2. A 5.00 coupon is split over three lines and each share is rounded separately, giving a total of 4.99. Which technique fixes this?

    Give every line its rounded-down share, then distribute the leftover cents to the lines with the largest fractional remainders so the parts add up exactly.
  3. 3. When should a coupon redemption count against its usage limit?

    Pricing a cart is a read-only calculation that may happen many times. Counting it then would let abandoned carts exhaust a limited coupon.
  4. 4. What does an exclusive (non-stackable) promotion do?

    Exclusivity is a combination rule. After an exclusive promotion applies, the engine skips the others and should log why.
  5. 5. What is the main benefit of logging skipped promotions with a reason?

    Auditability turns "why did I not get my discount?" into a lookup instead of a debugging session.

Summary

  • Most promotions are percent, fixed, BOGO or free-shipping actions with conditions; model them as data.
  • Coupons are automatic promotions plus a code condition, with validation messages, limits and unguessable codes.
  • Decide priority, the base for percentages, exclusive flags and exclusions up front; the order changes the total.
  • Prorate discounts across lines with the largest remainder method so cents never disappear.
  • Count redemptions at order placement, log applied and skipped promotions, and test with tables and boundary cases.

Next: Sales Tax, VAT and GST.