Total the cart in cents
Python · Python · beginner · greenfield
Adds the `cart_total_cents` helper for the checkout summary. Keeps all arithmetic in integer cents, applies the flat discount, and clamps at zero so an oversized promo code can't produce a negative total. Covered the empty-cart and big-discount cases by hand.
Requirements
- Implement `cart_total_cents(lines, discount_cents=0)`: return the cart total in integer cents.
- Each line is a dict with `unit_cents` (non-negative int) and `quantity` (non-negative int); the subtotal is the sum of `unit_cents * quantity` over all lines.
- `discount_cents` (non-negative int) is a flat discount off the whole cart; the total must never go below 0.
- An empty cart totals 0 (regardless of the discount).
- All money stays in integer cents — no floats anywhere.
Files touched
- app/checkout/cart_total.py
--- app/checkout/cart_total.py +def cart_total_cents(lines, discount_cents=0): + """Total of a cart in integer cents, never below zero. + + Each line has ``unit_cents`` (int >= 0) and ``quantity`` (int >= 0); + ``discount_cents`` is a flat discount applied to the whole cart. + """ + subtotal = 0 + for line in lines: + subtotal += line["unit_cents"] * line["quantity"] + return max(subtotal - discount_cents, 0) +