Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 40 ยท Projects

Project: A Complete Order Engine

Build a small but complete order engine in Python: cart, coupon discounts, allocation across lines, tax, totals in integer cents, order creation with snapshots and a state machine.

This project ties the course together. You will write a compact order engine: a program that takes a cart and a coupon, produces correct totals, creates an order that no later price change can alter, and moves that order through a protected set of states. It is small enough to read in one sitting and real enough that each part maps to a lesson you have already seen.

Everything runs live below in Python. There is no database and no web framework, because the interesting logic lives in plain functions that you could move into any platform. We follow the rules from earlier chapters: money is always an integer number of cents (money as integers), discounts are shared across lines without losing a cent (promotions engine), tax is rounded per line (taxes), and an order carries a snapshot of what the customer agreed to (order lifecycle).

The design

The engine has four steps, each a separate function so you can test it on its own.

flowchart LR
  A["Cart<br/>sku to quantity"] --> B["Price lines<br/>from catalog"]
  B --> C["Apply coupon<br/>allocate across lines"]
  C --> D["Shipping<br/>and tax"]
  D --> E["Totals"]
  E --> F["Create order<br/>snapshot + reserve stock"]
  F --> G["State machine<br/>pending, paid, fulfilled..."]

Pricing is a pure calculation; creating an order is the step that records it and changes stock.

Two design choices matter more than the rest:

  1. Pricing is a pure function. It reads the cart, the catalog and the coupon, and returns numbers. It changes nothing. That makes it easy to test and safe to call on every cart change, which is what real shops do.
  2. Order creation copies, it does not reference. The order stores unit prices, names, discounts and tax as they were at that moment. If the catalog changes tomorrow, yesterday's order still shows what was charged.

Step 1: allocation and tax

The trickiest arithmetic is splitting one order-level discount over several lines. If a 10 percent discount is 2.35 and there are three lines, you cannot give each line a rounded third. The largest remainder method gives each line the floor of its fair share, then hands out the leftover cents to the lines with the biggest fractional parts. The parts always add up exactly.

Python Allocating a discount across lines, then taxing each line

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.

Notice the order: discount first, then tax on the discounted amount of each line. That is the common rule for percent and fixed order discounts in tax-exclusive pricing. Rules differ by country and by kind of discount, so treat this as a configurable policy, not a law of nature.

Step 2: the complete engine

Now the whole thing. Read it from top to bottom: data first, then pricing, then orders, then the state machine, then a short script that exercises everything. Run it, then change a quantity or a coupon and watch the totals move.

Python The complete order 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 output against the code. The coupon shares its discount across the three lines; shipping is charged only when the discounted subtotal stays under the free-shipping threshold; and the snapshot holds even after CATALOG changes. The one-line guard in move_to is the whole state machine: the transition table is data, so adding a status means editing a dictionary, not hunting through if chains.

What this engine leaves out

A production system adds real concerns that deserve their own lessons:

  • Concurrency. Two customers can both pass the stock check at the same moment. The fix is an atomic reservation, as in reservations and overselling and the inventory project.
  • Payment. The status changes from pending to paid only because a payment provider said so, via a verified webhook; see webhooks and signatures.
  • Persistence. Orders, lines and history belong in database tables, with the status change and the history row written in one transaction.
  • Stacking and rules. Real promotions have priorities, exclusions and usage limits.
  • Multi-currency and tax services, shipping zones and carriers, partial refunds, and returns.

Extend it

Try these in the editor above; each is a good exercise.

  1. Add a coupon with kind: "shipping" that makes shipping free.
  2. Limit FIVEOFF to one use per customer by passing a used_coupons set into create_order.
  3. Add an inventory shortfall rule: instead of refusing the whole order, report which lines are short.
  4. Write refund(order, amount) that allows partial refunds but never more than the total paid.
  5. Record a timestamp in each history entry (inject the clock as a parameter so output stays deterministic).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is price_cart written as a pure function?

    A pure function reads inputs and returns numbers. It never reserves stock or writes data, so calling it repeatedly is safe.
  2. 2. What does the largest remainder method guarantee?

    Each line receives the floor of its share and the leftover cents go to the lines with the largest remainders, so the sum is exact.
  3. 3. Why does the order store unit prices and tax instead of referencing the catalog?

    An order is a record of an agreement. Snapshotting prices and tax keeps invoices and refunds consistent.
  4. 4. What happens when code tries to move a fulfilled order back to pending?

    The transition table lists the legal next states. Anything else raises an error before the status or history is touched.

Summary

  • Keep pricing a pure function of cart, catalog and coupon; create orders in a separate step.
  • Work in integer cents, allocate order-level discounts with the largest remainder method and round tax per line.
  • Snapshot prices, discounts and tax into the order so history stays true.
  • Model status as a transition table and reject anything not listed.
  • Real systems add atomic stock handling, verified payment events, persistence and richer promotion rules.

Next, build the part this engine cheated on: Project: Inventory Reservation Service.