Case study: Shopping cart and checkout
What you will learn on this page
Section titled “What you will learn on this page”- Why money is a count of whole cents, and why a shop needs exactly one place where an amount is rounded.
- Why a cart holds products and quantities but no prices, and how a quote, made fresh each time, carries the prices instead.
- When promotions earn a small interface (a Strategy), and when a plain function would do.
- How to reserve stock all or nothing, and move it to sold or back to available with the payment’s answer.
- How one key per press of the button, and the order id as the payment key, keep a second press or a lost answer from charging twice.
- How a change (coupons, with stacking rules) lands in the pricing code, and how a coupon’s single use moves like stock does.
This page follows the order in How to approach a case study. It assumes Strong types and API contracts, API contracts and validation placement, and Idempotency, retries, and duplicate handling. Those pages build each idea on its own; here they meet in one program where a customer, a catalog, a stock room, and a payment provider can each change their mind at a different moment.
The request
Section titled “The request”“Our checkout is a mess. Last month a price change charged people more than the page showed them. Customers who double-click ‘Place order’ sometimes get two orders and two charges. When the card provider times out, we don’t know whether to try again. And marketing wants a ‘3 for 2’ on tea and ‘10% off over 50’. Can you design the cart and checkout?”
Four complaints, and each one is about time. The price changed between the page and the charge. The button was pressed twice. The provider’s answer never came. A promotion depends on what else is in the cart at the moment it is priced. The design must say, for each fact, when it is read and who keeps it.
Clarifying questions
Section titled “Clarifying questions”Each question is here because its answer changes the design.
| Question | Answer (from the team) | What it changes |
|---|---|---|
| Which currency, and how exact? | One currency, to the cent. Totals must match the receipt to the cent. | Money as a whole number of cents. No floating point anywhere. |
| When prices change, which price does a cart pay? | The price at checkout. But never more than the customer was shown. | The cart keeps no prices. Checkout prices again and refuses a total the customer did not see. |
| How do promotions combine? | In a fixed order that marketing sets. “10% off over 50” counts after the “3 for 2”. | Promotions apply in a list order, each on what is left. |
| Can a promotion make an order free? | Rarely, but yes. Never below zero. | The pricer cuts each discount to what is left. A zero total is paid without a charge. |
| When do we take stock? | When the order is placed, so two people cannot buy the last kettle. Not when it goes in the cart. | Reserve at checkout; sell on payment; release on a decline. |
| What does the card provider give us? | A charge with an idempotency key. The same key again returns the first answer and does not charge. | A PaymentGateway interface whose contract says so, and a fake that keeps it. |
| Does the provider always answer? | No. Timeouts happen, and sometimes the card was charged and the answer lost. | “No answer” is an ordinary reply. The order waits, and a retry under the same key settles it. |
| What does the checkout page send? | The cart’s owner, the total it showed, and a key it makes once per showing of the button. | A SubmitRequest with a RequestKey. A second press sends the same key. |
| What if the stock or a product disappears before checkout? | Tell the customer which products, and change nothing. | Every refusal is a value, and comes before anything is recorded. |
| How many in one cart? | Up to 20 of one product, up to 30 different products. | Two limits, kept by the Cart itself. |
| One server? | One process for now. Requests arrive one at a time. | Step 1 is single-threaded and says so. |
Three answers decide the shape. “Never more than the customer was shown” means checkout must price the cart again and compare. “A second press sends the same key” makes the key the thing that decides whether a request is new. “The card was charged and the answer lost” means the shop must be able to ask again without charging again, which only the provider’s own idempotency can promise.
Confirmed:
- A cart of products and quantities, with limits.
- A catalog with today’s prices, which can change and can drop a product.
- Promotions: “buy so many, pay for fewer” on one product, and “a percentage off above a spend”, applied in a set order.
- Stock that is reserved when an order is placed, sold when it is paid, and freed when the card is declined.
- A payment provider behind an interface, which may decline, may not answer, or may lose its answer after charging.
- Idempotent submission: one order per key, one charge per order.
Assumed (to confirm with the team; see Assumptions):
- The checkout page makes a fresh key each time it shows the button, and sends the same key on a repeat.
- An order whose payment has no answer can wait, with its stock reserved, until a retry gets one. (A real shop would also give up after a while; see Production limitations.)
Out of scope: taxes, shipping, currencies, refunds, accounts and sign-in, storage (everything is in memory), and the provider’s own side (the example has a fake). Coupons arrive as a change, below.
Requirements
Section titled “Requirements”Functional requirements.
- FR-1 Cart. A customer can add a product, change its quantity, or remove it. Each product appears once, with a quantity from 1 to 20, and a cart has at most 30 lines. A change that breaks a rule is refused and changes nothing.
- FR-2 Prices. A cart is priced from today’s catalog. A line whose product is no longer sold is listed as unavailable, not priced.
- FR-3 Promotions. The shop’s promotions apply in a set order, each on the total left by the ones before. A discount never takes the total below zero.
- FR-4 Checkout checks. Placing an order is refused for an empty cart, a product no longer sold, a total that is not the one the customer was shown, or short stock (naming every short product).
- FR-5 Stock. A placed order reserves its stock, all or nothing. Payment sells it; a decline frees it.
- FR-6 Payment. A placed order is charged its total. A total of zero is paid without a charge.
- FR-7 One order per press. A request sent again under the same key returns the first order, and charges nothing more. The same key for another request is refused.
- FR-8 Lost answers. An order whose charge got no answer waits, with its stock reserved, and a retry settles it without charging twice.
Non-functional requirements.
- NFR-1 Exact money. Amounts are integer cents. One function rounds, to the nearest cent, a half cent up.
- NFR-2 Testable without a provider. The provider is an interface, and every reply it can give can be produced on demand by a fake.
- NFR-3 Refusals are values. A customer typing 0, or a total that changed, is not an exception. Exceptions mean a bug.
- NFR-4 Not thread-safe, on purpose. One request at a time, and the documentation says so.
- NFR-5 Ids that cannot be mixed up. A product’s SKU, a customer, an order, and a request key are four different types.
FR-4 and FR-7 are the team’s first two complaints, and FR-8 is the
third. Most of this design is about the order in which submit does
things, so that each refusal leaves nothing behind and each repeat
finds what the first attempt left.
Use cases and acceptance criteria
Section titled “Use cases and acceptance criteria”The tests are named after these criteria. See Use cases, user stories, and acceptance criteria.
UC-1 Manage the cart.
- AC-1.1 Adding a product again adds to its line.
- AC-1.2 A quantity out of range is refused and changes nothing.
- AC-1.3 A full cart refuses a new line, but not more of a line it has.
- AC-1.4 Setting a quantity changes the line; 0 removes it.
- AC-1.5 The cart keeps no prices.
UC-2 Price the cart.
- AC-2.1 The demo cart is priced line by line, then promotion by promotion.
- AC-2.2 A multi-buy counts only full groups.
- AC-2.3 “Spend and save” measures the total after earlier promotions.
- AC-2.4 A percentage rounds to the nearest cent, a half cent up.
- AC-2.5 A discount never takes the total below zero.
- AC-2.6 A product no longer sold is listed, not priced.
- AC-2.7 A promotion that makes no sense is refused when built.
UC-3 Place an order.
- AC-3.1 A placed order is charged once and its stock sold.
- AC-3.2 A changed total is refused and does not use up the key.
- AC-3.3 Short stock reserves nothing and names every short SKU.
- AC-3.4 An empty cart, or a product no longer sold, is refused.
- AC-3.5 A declined card fails the order and frees its stock.
- AC-3.6 An order with nothing to pay is paid without a charge.
- AC-3.7 An order keeps the price it was placed at.
UC-4 Repeats and lost answers.
- AC-4.1 The same key twice is one order and one charge.
- AC-4.2 The same key for another request is refused.
- AC-4.3 A lost answer, whether or not the card was charged, leaves the order waiting, and a retry charges once.
- AC-4.4 A retry that gets no answer again keeps waiting.
- AC-4.5 The fake gateway keeps the contract.
- AC-4.6 A conflict from the gateway is a bug and throws.
UC-5 Order and stock moves.
- AC-5.1 An order moves once: from awaiting payment to paid or to payment failed.
- AC-5.2 Stock is reserved once per order and settled once.
- AC-5.3 Reserve adds up a SKU named twice before it checks.
Invariants
Section titled “Invariants”Each invariant names the code that keeps it. See Invariants.
- INV-1 The cart is always valid. One line per SKU, each quantity
from 1 to 20, at most 30 lines. Kept by
Cart, whose only changes areaddandset_quantity, which check first. - INV-2 Stock is never made or lost. For each SKU, available plus
reserved plus sold is what was received. Kept by
Inventory, which only moves units between its piles. - INV-3 Stock matches the orders. Reserved stock is exactly the
lines of orders awaiting payment, and sold stock the lines of paid
orders. Kept by
Checkout::charge, which moves the order and its stock together, on every answer. - INV-4 One order per key, one charge per order. Kept by
attempts_inCheckout, and by charging under the order id, which the provider treats as its idempotency key. - INV-5 Discounts are positive and the total is never below zero.
Kept by
Pricer::quote, not by each promotion. - INV-6 An order’s status moves once. Kept by
Order, whosemark_paidandmark_failedthrow unless it awaits payment. - INV-7 A refusal leaves nothing behind. Kept by the order of steps
in
Checkout::submit: every refusal comes before anything is recorded.
The random test makes 3,000 random steps and checks INV-2 and INV-3 after every one, and at the end that each customer was charged exactly the totals of their paid orders.
Entities and relationships
Section titled “Entities and relationships”The nouns from the answers: customer, cart, line, product, SKU, price, catalog, promotion, discount, total, stock, order, payment, provider, key, button. Filtered:
- Customer is a
CustomerId. Accounts are out of scope. - Cart and line become
CartandCartLine: a SKU and a quantity. - Product, SKU, price, and catalog become
Product,Sku,Money, andCatalog. - Promotion and discount become the
Promotioninterface and theDiscountlines of a quote. - Total is the last field of a
Quote: the cart priced now, a value made fresh each time. - Stock is
Inventory, with three piles per SKU. - Order is an
Order, which keeps the quote it was placed at, and anOrderStatus. - Payment and provider become the
PaymentGatewayinterface, itsChargeReply, and aFakeGateway. - Key and button become a
RequestKeyin aSubmitRequest.
Text description of the diagram
A customer fills a cart, which holds only lines of SKU and quantity. The cart is priced against the catalog, which maps each SKU to a product and its price, and that makes a quote: priced lines, discounts, and a total. The quote is copied into an order, which also has an id, a customer, and a status. The order reserves stock in the inventory, which keeps available, reserved, and sold counts, and then sells it or frees it. The order has one charge at the provider, keyed by the order id.
Diagram source (Mermaid)
flowchart LR
Customer["Customer (id)"]
Cart["Cart: lines of SKU and quantity"]
Catalog["Catalog: SKU to product and price"]
Quote["Quote: priced lines, discounts, total"]
Order["Order: id, customer, quote, status"]
Stock["Inventory: available, reserved, sold"]
Charge["Charge at the provider, keyed by order id"]
Customer -->|fills| Cart
Cart -->|priced against| Catalog
Catalog -->|makes| Quote
Quote -->|copied into| Order
Order -->|reserves, then sells or frees| Stock
Order -->|one charge| ChargeThe arrow that matters is the one that is not there: the cart does not point at prices. A price lives in the catalog until checkout copies it into a quote, and the order keeps that copy. That is how the team’s first complaint is answered: a price change after the customer saw the total changes the new quote, the totals differ, and the order is refused instead of charged.
Text description of the diagram
Cart holds a vector of CartLine and offers add, set_quantity, and lines. Catalog holds a map from SKU to Product and offers add, set_price, remove, and find. Promotion is an interface with label and discount; MultiBuy and SpendAndSave implement it. Pricer reads a Catalog it does not own and owns its promotions through unique_ptr; it offers quote. Inventory holds three maps from SKU to count, available, reserved, and sold, and offers reserve, commit, and release. PaymentGateway is an interface with charge; FakeGateway implements it. Order holds its id, its quote, and its status, and offers mark_paid and mark_failed. Checkout owns its orders and a map of request keys to attempts, uses the Pricer, the Inventory, and the PaymentGateway without owning them, and offers submit and retry_payments.
Diagram source (Mermaid)
classDiagram
class Cart {
-vector~CartLine~ lines_
+add(Sku, int) CartChange
+set_quantity(Sku, int) CartChange
+lines() vector~CartLine~
}
class Catalog {
-map~Sku, Product~ products_
+add(Product)
+set_price(Sku, Money)
+remove(Sku)
+find(Sku) Product*
}
class Promotion {
<<interface>>
+label() string*
+discount(lines, Money so_far) Money*
}
class Pricer {
-const Catalog* catalog_
-vector~unique_ptr~Promotion~~ promotions_
+quote(Cart) Quote
}
class Inventory {
-map~Sku, int~ available_
-map~Sku, int~ reserved_
-map~Sku, int~ sold_
+reserve(OrderId, lines) ReserveResult
+commit(OrderId)
+release(OrderId)
}
class PaymentGateway {
<<interface>>
+charge(key, CustomerId, Money) ChargeReply*
}
class Order {
-OrderId id_
-Quote quote_
-OrderStatus status_
+mark_paid()
+mark_failed(reason)
}
class Checkout {
-map~RequestKey, Attempt~ attempts_
-map~OrderId, Order~ orders_
+submit(SubmitRequest, Cart&) SubmitResult
+retry_payments() size_t
}
Promotion <|.. MultiBuy
Promotion <|.. SpendAndSave
PaymentGateway <|.. FakeGateway
Pricer --> Catalog : reads
Pricer *-- Promotion : owns
Checkout --> Pricer : uses
Checkout --> Inventory : uses
Checkout --> PaymentGateway : uses
Checkout *-- Order : ownsOwnership in one sentence each. The Pricer owns its promotions and
borrows the catalog. The Checkout owns its orders and borrows the
pricer, the inventory, and the gateway. Whoever builds the shop, the
composition root,
owns everything else, and builds it in the order that each piece needs
the one before.
Class design
Section titled “Class design”The design below is step 1 of the example, the complete answer to FR-1 … FR-8. Coupons are added in When the requirements change.
Money and ids
Section titled “Money and ids”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// An amount in cents. Never a double: a shop adds up prices exactly, and// 0.10 + 0.20 is not 0.30 in binary floating point. A 64-bit whole number// of cents holds any amount a shop will meet, and every sum is exact.// It is a plain value: copy it, compare it, add it; nothing to clean up.struct Money { std::int64_t cents = 0; // so `Money{}` is zero, and `Money{450}` is 4.50
// `= default` asks the compiler to write <, <=, ==, and the rest by // comparing the members, here just cents. friend constexpr auto operator<=>(const Money&, const Money&) = default; // friend: written inside the struct, called as `a + b`. Each one makes // a new Money and changes neither argument. friend constexpr Money operator+(Money a, Money b) { return {a.cents + b.cents}; } friend constexpr Money operator-(Money a, Money b) { return {a.cents - b.cents}; } // A unit price times a quantity. The int is widened to 64 bits first. friend constexpr Money operator*(Money a, int times) { return {a.cents * times}; }};
// dollars(12) is 12.00, that is Money{1200}.[[nodiscard]] constexpr Money dollars(std::int64_t whole) { return {whole * 100}; }
// percent of amount, rounded to the nearest cent, a half cent up. The// one place in the shop where money is rounded. Throws// std::invalid_argument for a negative amount or a percent outside 0..100.// How: amount * percent is the answer in hundredths of a cent; adding 50// before the whole-number division by 100 rounds it instead of cutting it// off. 10% of 50.45 is 5045 * 10 = 50450, + 50 = 50500, / 100 = 505: 5.05.[[nodiscard]] constexpr Money percent_of(Money amount, int percent) { if (amount.cents < 0 || percent < 0 || percent > 100) throw std::invalid_argument("percent_of: out of range"); return {(amount.cents * percent + 50) / 100};}
// "50.40", or "-4.50". Works on the size of the amount and puts the sign// in front, because % and / of a negative number give negative parts.[[nodiscard]] inline std::string to_string(Money money) { const std::int64_t magnitude = money.cents < 0 ? -money.cents : money.cents; std::string cents = std::to_string(magnitude % 100); // the last two digits if (cents.size() < 2) cents.insert(0, "0"); // 5 cents is ".05", not ".5" return (money.cents < 0 ? "-" : "") + std::to_string(magnitude / 100) + "." + cents;}Money is a value object:
whole cents in a 64-bit integer, with only the operations a shop needs.
Sums are exact, so a receipt adds up to the cent. The one operation
that cannot be exact, a percentage, is percent_of, and it is the
only place in the program that rounds. When the rule is “to the
nearest cent, a half cent up”, there must be one function that says so,
or two parts of the shop will one day round the same amount two ways.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One type per kind of id, so that an order id cannot be passed where a// product's SKU is expected. Each is a non-empty string; Tag only makes// the types different.// How: Id<SkuTag> and Id<OrderTag> are two separate classes made from one// template, so mixing them up is a compile error. The tags are never// defined or used for anything else; `struct SkuTag` inside the angle// brackets below just names a new, empty type.template <typename Tag>class Id {public: // explicit: a plain string does not turn into an id by accident; write // Sku("tea-500g"). Throws std::invalid_argument for an empty string. explicit Id(std::string value) : value_(std::move(value)) { if (value_.empty()) throw std::invalid_argument("an id cannot be empty"); }
[[nodiscard]] const std::string& str() const noexcept { return value_; }
// Compares the strings. This also gives ==, and the < that lets an id // be the key of a std::map. friend auto operator<=>(const Id&, const Id&) = default;
private: std::string value_;};
using Sku = Id<struct SkuTag>; // a product, such as "tea-500g"using CustomerId = Id<struct CustomerTag>; // a signed-in customerusing OrderId = Id<struct OrderTag>; // made by Checkout: "order-1001"using RequestKey = Id<struct RequestKeyTag>; // made by the checkout page, once per attempt to orderFour kinds of id, one template, as in
Strong types. submit takes a RequestKey
and charges under an OrderId, and the compiler will not let the two
be swapped.
The catalog and the cart
Section titled “The catalog and the cart”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One thing the shop sells. A plain value: the catalog keeps a copy.struct Product { Sku sku; std::string name; Money price; // the price now; a cart does not keep a copy};
// What the shop sells, at today's prices. Prices change while carts wait,// which is why a cart holds SKUs and quantities, not prices.// It owns its products, in a std::map keyed by SKU, so that a lookup is// quick and each SKU appears once.class Catalog {public: // Throws std::invalid_argument for a SKU already added, an empty name, // or a price that is not positive. void add(Product product) { if (product.name.empty() || product.price <= Money{}) { throw std::invalid_argument("a product needs a name and a positive price"); } const Sku sku = product.sku; // a copy: product is moved from on the next line // emplace returns a pair; .second is false when the SKU was already // a key, and then the map is unchanged. if (!products_.emplace(sku, std::move(product)).second) { throw std::invalid_argument("already in the catalog: " + sku.str()); } } // Throws std::invalid_argument for an unknown SKU or a price that is // not positive. void set_price(const Sku& sku, Money price) { if (price <= Money{}) throw std::invalid_argument("a price must be positive"); at(sku).price = price; } // The product is no longer sold. Carts that hold it keep their line. // An unknown SKU is not an error: erase then removes nothing. void remove(const Sku& sku) { products_.erase(sku); }
// The product, or nullptr if the shop does not sell it (any more). The // pointer is to the catalog's own copy, which the map owns: read it // now and do not keep it, because a later remove destroys that product. [[nodiscard]] const Product* find(const Sku& sku) const { const auto found = products_.find(sku); // A map's find returns end() when the key is missing; found->second // is the Product stored under the key. return found == products_.end() ? nullptr : &found->second; }
private: // Like find, but for changing a product, and an unknown SKU throws. Product& at(const Sku& sku) { const auto found = products_.find(sku); if (found == products_.end()) throw std::invalid_argument("not in the catalog: " + sku.str()); return found->second; }
std::map<Sku, Product> products_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One line of a cart: which product, and how many.struct CartLine { Sku sku; int quantity = 0;
// Two lines are equal when both members are; the tests compare carts. friend bool operator==(const CartLine&, const CartLine&) = default;};
// The answer to a change to the cart. A refusal is a normal answer, not an// exception: a customer typing 0 or 99 is not a bug.enum class CartChange { ok, bad_quantity, // below one, or above the most for one line too_many_lines, // a new line in a full cart not_in_cart, // set_quantity for a SKU with no line};
// What a customer means to buy: SKUs and quantities, nothing else. Always// valid: one line per SKU, each quantity from 1 to max_quantity, at most// max_lines lines. A change that would break a rule is refused and// changes nothing. The cart does not look at the catalog or the stock:// both can change before checkout, which checks them again.class Cart {public: static constexpr int max_quantity = 20; // per line static constexpr std::size_t max_lines = 30; // per cart
// Adds quantity to the SKU's line, or adds a line. [[nodiscard]] CartChange add(const Sku& sku, int quantity); // Sets the quantity of the SKU's line; 0 removes the line. [[nodiscard]] CartChange set_quantity(const Sku& sku, int quantity); void clear() noexcept { lines_.clear(); }
[[nodiscard]] const std::vector<CartLine>& lines() const noexcept { return lines_; } [[nodiscard]] bool empty() const noexcept { return lines_.empty(); }
private: std::vector<CartLine> lines_; // in the order the customer added them};The cart knows nothing but SKUs and quantities, and keeps its own rules (INV-1). It does not check the catalog or the stock, because both can change between “add to cart” and “place order”, and checkout must check them again anyway. A check made twice, once early and once for real, is a check whose first answer someone will one day trust.
A refusal is a CartChange, not an exception: a customer who types 0
has not found a bug. That is the line drawn in
API contracts and validation placement:
input from outside is answered with a value; a broken promise between
parts of our own code throws.
Pricing
Section titled “Pricing”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One cart line at today's price: the name and unit price are copied// from the catalog when the quote is made, so the quote stays as it was// if the catalog changes later.struct PricedLine { Sku sku; std::string name; Money unit; int quantity = 0;
[[nodiscard]] Money total() const { return unit * quantity; }};
// One line of the "you save" list on a quote.struct Discount { std::string label; // "3 for 2 on tea" Money amount; // positive: what comes off};
// What the cart costs now. A quote is a value: made fresh from the cart,// the catalog, and the promotions each time, and never stored in the cart.struct Quote { std::vector<PricedLine> lines; // lines whose product is still sold std::vector<Sku> unavailable; // lines whose product is not Money subtotal; // the sum of lines std::vector<Discount> discounts; Money total; // subtotal less every discount; never below zero};A Quote is a value made from the cart, the catalog, and the
promotions, and never stored in the cart. Each PricedLine copies the
name and unit price, so a quote, and the order that keeps it, stay as
they were when the catalog changes (AC-3.7).
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A pricing rule the shop runs for everyone: a Strategy. Each one looks at// the priced lines and the total so far (after earlier promotions) and// says how much comes off. It does not change anything.// Why an interface: the shop adds kinds of promotion over time, and the// Pricer should not change when it does. A new kind is a new class.class Promotion {public: // virtual: the Pricer deletes promotions through a Promotion pointer, // and this makes the derived class's destructor run too. virtual ~Promotion() = default;
[[nodiscard]] virtual std::string label() const = 0; // What comes off: zero if the promotion does not apply. Never // negative. [[nodiscard]] virtual Money discount(const std::vector<PricedLine>& lines, Money so_far) const = 0;
protected: // Protected: only a derived class can build or copy the base part, so // no one copies a Promotion and loses the derived part ("slicing"). Promotion() = default; Promotion(const Promotion&) = default; Promotion& operator=(const Promotion&) = default;};
// "Buy 3, pay for 2" on one SKU: every full group of buy pays for pay.// final: no class may derive from it.class MultiBuy final : public Promotion {public: // Throws std::invalid_argument unless 1 <= pay < buy. MultiBuy(std::string label, Sku sku, int buy, int pay);
[[nodiscard]] std::string label() const override { return label_; } [[nodiscard]] Money discount(const std::vector<PricedLine>& lines, Money so_far) const override;
private: std::string label_; Sku sku_; int buy_; int pay_;};
// "10% off orders of 50.00 or more", measured after earlier promotions.class SpendAndSave final : public Promotion {public: // Throws std::invalid_argument for a threshold below zero or a // percent outside 1..100. SpendAndSave(std::string label, Money threshold, int percent);
[[nodiscard]] std::string label() const override { return label_; } [[nodiscard]] Money discount(const std::vector<PricedLine>& lines, Money so_far) const override;
private: std::string label_; Money threshold_; int percent_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Prices a cart. It reads the catalog it was given (which must outlive// it) and owns its promotions, which apply in the order given.// Ownership in the types: a pointer to the catalog (borrowed, never// deleted here) and a vector of unique_ptr (owned: the promotions die with// the Pricer). A Pricer can be moved but not copied, because unique_ptr// cannot be copied.class Pricer {public: // Throws std::invalid_argument for a null promotion. Pricer(const Catalog& catalog, std::vector<std::unique_ptr<Promotion>> promotions);
// The cart at today's prices, less every promotion that applies. // Throws std::logic_error if a promotion returns a negative discount. [[nodiscard]] Quote quote(const Cart& cart) const;
private: const Catalog* catalog_; // a pointer, not a reference, so that a Pricer can be assigned std::vector<std::unique_ptr<Promotion>> promotions_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
Pricer::Pricer(const Catalog& catalog, std::vector<std::unique_ptr<Promotion>> promotions) : catalog_(&catalog), promotions_(std::move(promotions)) { for (const auto& promotion : promotions_) { if (!promotion) throw std::invalid_argument("a promotion cannot be null"); }}
// Two passes. First, each cart line is priced from the catalog, or listed// as unavailable. Then each promotion, in order, takes its discount off// what is left so far. The Pricer, not each promotion, enforces the two// rules every promotion must keep: never negative, never below zero.Quote Pricer::quote(const Cart& cart) const { Quote quote; for (const CartLine& line : cart.lines()) { // An if with a declaration: product lives only in this if and its // else, and the branch runs when it is not nullptr. if (const Product* product = catalog_->find(line.sku)) { quote.lines.push_back({line.sku, product->name, product->price, line.quantity}); quote.subtotal = quote.subtotal + quote.lines.back().total(); } else { quote.unavailable.push_back(line.sku); } } Money so_far = quote.subtotal; for (const auto& promotion : promotions_) { // A virtual call: it runs the rule of the promotion's own class. Money amount = promotion->discount(quote.lines, so_far); if (amount < Money{}) throw std::logic_error("a promotion returned a negative discount: " + promotion->label()); if (amount > so_far) amount = so_far; // a total never goes below zero if (amount == Money{}) continue; // a promotion that did not apply is not listed quote.discounts.push_back({promotion->label(), amount}); so_far = so_far - amount; } quote.total = so_far; return quote;}How this code works: Pricer::quote on the demo cart
Alice’s cart is 3 teas at 4.50, one mug at 12.00, and one kettle at 35.00. The promotions are “3 for 2 on tea”, then “10% off orders of 50.00 or more”.
| Step | What the code does | Value | so_far after |
|---|---|---|---|
| tea line | find gives the product; 4.50 × 3 |
13.50 | |
| mug line | 12.00 × 1 | 12.00 | |
| kettle line | 35.00 × 1 | 35.00 | |
| subtotal | the sum of the lines | 60.50 | 60.50 |
MultiBuy::discount |
3 / 3 = 1 full group, × (3 − 2) free, × 4.50 | 4.50 off | 56.00 |
SpendAndSave::discount |
56.00 ≥ 50.00, so percent_of(5600, 10): (56000 + 50) / 100 = 560 |
5.60 off | 50.40 |
| total | what is left | 50.40 |
Three things to notice:
- The order of the list is a business rule. “10% off” measures 56.00, not 60.50, because it comes second. Swapped, it would take 6.05 and the total would be 49.95. AC-2.3 tests a cart that is 50.50 before the tea and 46.00 after: no 10%.
- The Pricer keeps the rules every promotion must keep. A
discount above
so_faris cut toso_far, and a negative one throwsstd::logic_error. A new kind of promotion cannot break INV-5, because the check is not in it. - A promotion that takes nothing is not listed. The receipt shows only what applied.
Does Strategy earn its place here?
Section titled “Does Strategy earn its place here?”Honestly, only just. With two promotions that never change, a plain function would do, and be easier to read:
IllustrativeA fragment for explanation; not compiled on its own.
// Illustrative: the same two promotions, hard-wired in one function.// Fine while marketing has exactly these two, in this order.Money promotions_off(const std::vector<PricedLine>& lines, Money subtotal, const Sku& tea) { Money off; // starts at zero for (const PricedLine& line : lines) { // 3 for 2: one tea free for every full group of three. if (line.sku == tea) off = off + line.unit * (line.quantity / 3); } const Money after = subtotal - off; // 10% off 50.00 or more, measured after the tea. if (after >= dollars(50)) off = off + percent_of(after, 10); return off;}The interface pays for itself here for three reasons that come from
the answers, not from the pattern: marketing adds kinds of promotion
over time (so the Pricer should not change when they do; see
the open-closed principle), each one needs its own
settings checked when it is built (AC-2.7), and each needs a label on
the receipt. A test also slips in a promotion of its own (Fixed, in
the tests) to check the Pricer’s rules alone. If none of that were
true, the function above would be the better design. See
Strategy for the general trade-off.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The answer to reserve. Short stock is a normal answer, not an// exception: two customers can want the last kettle.struct ReserveResult { bool ok = false; std::vector<Sku> short_skus; // the SKUs without enough stock, if not ok};
// Stock per SKU, in three piles: available to sell, reserved for an order// that waits for payment, and sold. Units move between the piles and are// never made or lost: available + reserved + sold is what was received.// A concrete class, not an interface: it runs in our process, and a test// uses the real one.class Inventory {public: // Throws std::invalid_argument for a quantity below one. void receive(const Sku& sku, int quantity);
// All or nothing: reserves every line for the order, or nothing and // says which SKUs are short. Throws std::logic_error for an order that // already has a reservation, and std::invalid_argument for a quantity // below one. If it throws, nothing moved. [[nodiscard]] ReserveResult reserve(const OrderId& order, const std::vector<CartLine>& lines); // The order is paid: its reserved units are sold. void commit(const OrderId& order); // The order will not be paid: its reserved units are available again. void release(const OrderId& order); // commit and release throw std::logic_error for an order with no // reservation: a second commit or release is a bug in the caller.
[[nodiscard]] int available(const Sku& sku) const { return count(available_, sku); } [[nodiscard]] int reserved(const Sku& sku) const { return count(reserved_, sku); } [[nodiscard]] int sold(const Sku& sku) const { return count(sold_, sku); }
private: // How many of the SKU are in the pile: 0 for a SKU it has never held. static int count(const std::map<Sku, int>& pile, const Sku& sku); // Moves the order's reserved units to another pile, and forgets the // reservation. Strong guarantee: if it throws, nothing moved. void move_reserved(const OrderId& order, std::map<Sku, int>& to);
std::map<Sku, int> available_; std::map<Sku, int> reserved_; std::map<Sku, int> sold_; // What each order holds, so that commit and release know what to move. std::map<OrderId, std::map<Sku, int>> reservations_; // per order, per SKU};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Three stages: add up what is wanted, check all of it, then move it. The// check comes before any move, so that a short SKU leaves every pile as it// was: all or nothing.ReserveResult Inventory::reserve(const OrderId& order, const std::vector<CartLine>& lines) { if (reservations_.count(order) != 0) throw std::logic_error("already reserved for " + order.str()); std::map<Sku, int> wanted; // per SKU, in case the lines name one twice for (const CartLine& line : lines) { if (line.quantity < 1) throw std::invalid_argument("reserve at least one unit of " + line.sku.str()); wanted[line.sku] += line.quantity; } ReserveResult result; // A structured binding: each map entry is a (key, value) pair, named // sku and quantity here. for (const auto& [sku, quantity] : wanted) { // check every SKU before moving any if (available(sku) < quantity) result.short_skus.push_back(sku); } if (!result.short_skus.empty()) return result; // Everything that can throw happens before a unit moves: an exception // leaves at most a few zero counts behind. // try_emplace adds a 0 count only for a SKU not there yet. for (const auto& [sku, quantity] : wanted) reserved_.try_emplace(sku, 0); // wanted is moved from here on: the loop below reads it through the map. reservations_.emplace(order, std::move(wanted)); for (const auto& [sku, quantity] : reservations_.at(order)) { available_[sku] -= quantity; // entries that exist: no allocation reserved_[sku] += quantity; } result.ok = true; return result;}How this code works: Inventory::reserve, all or nothing
reserve works in three stages, and the order is the point.
- Add up. The lines are summed per SKU into
wanted. A cart has one line per SKU, butreservedoes not trust its caller to have used aCart. AC-5.3 passes two lines of 2 teas with 3 in stock:wantedis 4 teas. - Check everything. Each SKU in
wantedis compared withavailable. Every short SKU is listed, not only the first, so that the customer is told everything at once. In AC-5.3, 3 is less than 4, so tea is short, andreservereturns with nothing moved. - Move. Only when nothing is short: first the steps that can
throw (a new zero count in
reserved_, and recording the reservation), then the moves themselves, which only change counts that exist and so cannot throw.
That last split is what makes “all or nothing” hold even for an
exception: if memory runs out, it runs out before any unit has moved.
commit and release share move_reserved, which is built the same
way, and both forget the reservation, so a second one throws (AC-5.2).
Why reserve at checkout, not when a line goes in the cart? Because the team said so, and for a reason: a cart is often abandoned, and stock held by forgotten carts is stock no one can buy. The price is that a cart can hold a kettle that is gone by checkout. The demo’s third customer meets exactly that.
Payment
Section titled “Payment”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Every answer the provider can give to a charge.enum class ChargeStatus { approved, declined, // the card issuer said no: final for this key unavailable, // no answer: the charge may or may not have happened conflict, // this key was used before for another customer or amount};
// The whole answer. The default, unavailable, is the safe guess when// nothing came back.struct ChargeReply { ChargeStatus status = ChargeStatus::unavailable; std::string reason; // for declined: what to tell the customer};
// The payment provider, seen from the shop. An interface because it is// another company's service across a network: a test needs a fake, and// production needs an adapter for the provider's SDK.//// Contract: charge is idempotent per key. A second charge with the same// key, customer, and amount does not charge again; it returns the answer// to the first. The same key with another customer or amount is a// conflict. A failure the provider can report is a reply, not an// exception; unavailable covers a timeout.class PaymentGateway {public: virtual ~PaymentGateway() = default;
// = 0: pure virtual, so each implementation must write it. key is the // idempotency key; the shop passes the order id. [[nodiscard]] virtual ChargeReply charge(const std::string& key, const CustomerId& customer, Money amount) = 0;
protected: // Protected, as for Promotion: no one copies a bare PaymentGateway. PaymentGateway() = default; PaymentGateway(const PaymentGateway&) = default; PaymentGateway& operator=(const PaymentGateway&) = default;};The contract is the provider’s half of
idempotency: the same key, the
same customer, and the same amount get the first answer back and
nothing is charged again. “No answer” is a ChargeStatus, because a
timeout is an ordinary event that every caller must handle.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A payment provider in memory that keeps the PaymentGateway contract,// and can be told to decline a customer or to fail the next call.class FakeGateway final : public PaymentGateway {public: // Throws std::invalid_argument for an amount that is not positive: the // shop never charges zero, so that would be a bug in the caller. [[nodiscard]] ChargeReply charge(const std::string& key, const CustomerId& customer, Money amount) override;
// Every charge for this customer is declined from now on. void decline(const CustomerId& customer) { declined_.insert(customer); } // The next charge answers unavailable. applied: the provider charged // the card first, and the answer was lost on the way back. Not // applied: the request never arrived. void fail_next(bool applied = false) { failure_ = applied; }
// What the customer's card has been charged, in all. [[nodiscard]] Money charged(const CustomerId& customer) const; // How many charges were approved: one per key, however often it was sent. [[nodiscard]] std::size_t approved() const noexcept { return approved_; } // How many times charge was called. [[nodiscard]] std::size_t calls() const noexcept { return calls_; }
private: // The first charge under a key, kept so that a repeat gets the same // answer. struct Record { CustomerId customer; Money amount; ChargeReply reply; };
std::map<std::string, Record> by_key_; std::set<CustomerId> declined_; // The failure planned for the next call: empty for none, else the // applied flag that fail_next was given. std::optional<bool> failure_; std::size_t approved_ = 0; std::size_t calls_ = 0;};The fake is a test double that keeps the contract (AC-4.5 checks it) and can fail its next call in the two ways that matter: the request never arrived, or the card was charged and the answer was lost. The shop cannot tell them apart, and the design must be right for both.
The order
Section titled “The order”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Where an order is in its life. The only moves are from// awaiting_payment to one of the other two.enum class OrderStatus { awaiting_payment, // stock reserved; the charge has no answer yet paid, // charged; the stock is sold payment_failed, // declined; the stock is available again};
// A name for printing. The switch has no default, so that the compiler// warns if a new status is added and not named here; the return after it// is never reached for a valid status.[[nodiscard]] constexpr std::string_view to_string(OrderStatus status) { switch (status) { case OrderStatus::awaiting_payment: return "awaiting payment"; case OrderStatus::paid: return "paid"; case OrderStatus::payment_failed: return "payment failed"; } return "?";}
// An order keeps the quote it was placed at: what the customer agreed to// pay, even if a price changes a minute later. Its status moves once,// from awaiting_payment to paid or to payment_failed.class Order {public: // Takes each part by value and moves it in: the caller copies or moves // once, and the order owns its own copy of the quote. Order(OrderId id, CustomerId customer, Quote quote) : id_(std::move(id)), customer_(std::move(customer)), quote_(std::move(quote)) {}
[[nodiscard]] const OrderId& id() const noexcept { return id_; } [[nodiscard]] const CustomerId& customer() const noexcept { return customer_; } [[nodiscard]] const Quote& quote() const noexcept { return quote_; } [[nodiscard]] Money total() const noexcept { return quote_.total; } [[nodiscard]] OrderStatus status() const noexcept { return status_; } // Why the payment failed; empty unless it did. [[nodiscard]] const std::string& failure() const noexcept { return failure_; }
// Both throw std::logic_error unless the order awaits payment. void mark_paid() { expect_awaiting(); status_ = OrderStatus::paid; } void mark_failed(std::string reason) { expect_awaiting(); failure_ = std::move(reason); status_ = OrderStatus::payment_failed; }
private: // The guard both moves share: a second move is a bug in the caller. void expect_awaiting() const { if (status_ != OrderStatus::awaiting_payment) { throw std::logic_error(id_.str() + " is already " + std::string(to_string(status_))); } }
OrderId id_; CustomerId customer_; Quote quote_; OrderStatus status_ = OrderStatus::awaiting_payment; std::string failure_;};Text description of the diagram
An order starts awaiting payment when submit records it, with its stock reserved. If the provider gives no answer, it stays awaiting payment, and a retry charges it again. An approved charge, or a total of zero, makes it paid, and its stock is sold. A decline makes it payment failed, and its stock is available again. Paid and payment failed are final.
Diagram source (Mermaid)
stateDiagram-v2
[*] --> awaiting_payment : submit records the order, stock reserved
awaiting_payment --> awaiting_payment : no answer from the provider
awaiting_payment --> paid : approved, or a total of zero
awaiting_payment --> payment_failed : declined
paid --> [*]
payment_failed --> [*]Three states and one move, kept by expect_awaiting (INV-6). An enum
is enough here: unlike the ATM’s states in
the ATM study, these states carry no data of their
own beyond a failure reason, and the order is the same object in all
three.
Checkout
Section titled “Checkout”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What the checkout page sends when the customer presses "Place order".// The page makes a new key each time it shows the button; a second press,// or the browser sending the request again, carries the same key.struct SubmitRequest { RequestKey key; CustomerId customer; Money expected_total; // the total the customer was shown};
enum class SubmitStatus { placed, // a new order: read its status for the payment duplicate, // this key placed an order already: here it is key_reused, // this key was used for another request empty_cart, // nothing to order unavailable_product, // a line's product is no longer sold price_changed, // the total is not the one the customer saw out_of_stock, // see short_skus};
// The whole answer to submit. Only some members mean something for each// status, as the comments say.struct SubmitResult { SubmitStatus status = SubmitStatus::empty_cart; // std::optional: either holds an Order or holds nothing. A copy, so // that it stays valid whatever happens to the checkout later. std::optional<Order> order; // a copy, for placed and duplicate Quote quote; // the cart priced now, for the refusals std::vector<Sku> short_skus; // for out_of_stock};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Turns a cart into an order: prices it, checks it against what the// customer saw, reserves the stock, records the order, then charges.// Holds references to the pricer, the inventory, and the gateway, which// must outlive it, and owns the orders. Not thread-safe: one request at a// time.class Checkout {public: // Keeps the addresses of its three collaborators; owns none of them. Checkout(const Pricer& pricer, Inventory& inventory, PaymentGateway& gateway) : pricer_(&pricer), inventory_(&inventory), gateway_(&gateway) {}
// Places an order for the cart, and empties the cart once the order // exists. A refusal changes nothing and does not use up the key. // Throws std::logic_error if the gateway reports a conflict (a bug; the // order then exists and waits), and lets std::bad_alloc through. [[nodiscard]] SubmitResult submit(const SubmitRequest& request, Cart& cart); // Charges again every order whose payment had no answer. Returns how // many still have none. std::size_t retry_payments();
// The order, or nullptr for an unknown id. It points at the checkout's // own order, so a later retry_payments can change what it shows. [[nodiscard]] const Order* find(const OrderId& id) const; // The ids of the orders whose payment has no answer yet, in id order. [[nodiscard]] std::vector<OrderId> awaiting_payment() const;
private: // What a key was first used for, so that a repeat can be told apart // from a different request under the same key. struct Attempt { CustomerId customer; Money expected_total; OrderId order; };
// Asks the gateway for the order's total and moves the order and its // stock to match the answer. Safe to call again for an order that waits. void charge(Order& order);
const Pricer* pricer_; Inventory* inventory_; PaymentGateway* gateway_; std::map<RequestKey, Attempt> attempts_; std::map<OrderId, Order> orders_; int next_number_ = 1001; // the number in the next order id: "order-1001"};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Five steps, each of which may end the call early with a refusal. Every// refusal comes before anything is recorded, so it changes nothing and// the same key can be sent again once the customer has fixed the problem.SubmitResult Checkout::submit(const SubmitRequest& request, Cart& cart) { // 1. A key seen before: a repeat of that request, or a mistake. Compare // the request, not the cart: the first submission emptied it. if (const auto found = attempts_.find(request.key); found != attempts_.end()) { const Attempt& first = found->second; if (first.customer != request.customer || first.expected_total != request.expected_total) { return {SubmitStatus::key_reused, std::nullopt, {}, {}}; } // The four values fill the SubmitResult members in order; {} leaves // one empty. orders_.at copies the order into the result. return {SubmitStatus::duplicate, orders_.at(first.order), {}, {}}; }
// 2. Check the cart against today's catalog and what the customer saw. if (cart.empty()) return {SubmitStatus::empty_cart, std::nullopt, {}, {}}; Quote quote = pricer_->quote(cart); // The refusals hand back the quote (moved, not copied), so that the page // can show the customer what changed. if (!quote.unavailable.empty()) return {SubmitStatus::unavailable_product, std::nullopt, std::move(quote), {}}; if (quote.total != request.expected_total) { return {SubmitStatus::price_changed, std::nullopt, std::move(quote), {}}; }
// 3. Reserve the stock, all or nothing. // The number is used up only once the order is recorded (below), so a // refusal here lets the next order take the same id. OrderId id("order-" + std::to_string(next_number_)); ReserveResult reserved = inventory_->reserve(id, cart.lines()); if (!reserved.ok) return {SubmitStatus::out_of_stock, std::nullopt, std::move(quote), std::move(reserved.short_skus)};
// 4. Record the order and the key. If that throws, give the stock back, // so that a refusal of any kind leaves nothing behind. // Two nested try blocks undo in reverse order: if the key cannot be // recorded, the order is erased; if either fails, the stock goes // back. `throw;` passes the same exception on to the caller. Order* order = nullptr; // points into orders_; a std::map never moves its entries try { // emplace returns a pair (iterator, inserted); .first->second is the new Order. order = &orders_.emplace(id, Order(id, request.customer, quote)).first->second; try { attempts_.emplace(request.key, Attempt{request.customer, request.expected_total, id}); } catch (...) { orders_.erase(id); throw; } } catch (...) { inventory_->release(id); throw; } ++next_number_; cart.clear(); // the cart is now the order
// 5. Charge. Whatever the answer, the order exists and the key is used. charge(*order); return {SubmitStatus::placed, *order, std::move(quote), {}};}The order of the five steps is the design:
- The key first. A key seen before is a repeat, and the answer is
the first order, whatever the cart says now (the first submission
emptied it). The request, not the cart, is compared: same customer
and same total, or
key_reused. - Then the checks that change nothing. Empty cart, a product gone, a total that is not the one shown. Each returns the fresh quote so the page can show what changed.
- Then the stock, all or nothing.
- Then record the order and the key, undoing the reservation if recording throws.
- Then charge. From here on, whatever the provider says, the order exists and the key is used.
Everything that can be refused comes before anything is recorded (INV-7). So a refused request has not used up its key (AC-3.2): bob fixes his total and sends the same key again.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each answer moves the stock and the order together: approved sells the// stock and marks the order paid; declined frees the stock and fails it;// unavailable changes nothing, so the order can be charged again.void Checkout::charge(Order& order) { if (order.total() == Money{}) { // promotions took it all: nothing to charge inventory_->commit(order.id()); order.mark_paid(); return; } // The order id is the payment key: a retry of the same order cannot // charge twice, even if an earlier attempt was applied and its answer lost. const ChargeReply reply = gateway_->charge(order.id().str(), order.customer(), order.total()); switch (reply.status) { case ChargeStatus::approved: inventory_->commit(order.id()); order.mark_paid(); return; case ChargeStatus::declined: inventory_->release(order.id()); order.mark_failed(reply.reason); return; case ChargeStatus::unavailable: return; // no answer: the order waits, and its stock stays reserved case ChargeStatus::conflict: // Each order has its own id and a total that never changes, so // this is a bug, not something the customer did. throw std::logic_error("the payment key " + order.id().str() + " was used for another charge"); }}
// Visits every order and charges only those still waiting. Each charge// uses the order id as its key, so a charge that was applied before, with// its answer lost, is answered again rather than taken twice.std::size_t Checkout::retry_payments() { std::size_t waiting = 0; for (auto& [id, order] : orders_) { // auto&: change the stored orders, not copies if (order.status() != OrderStatus::awaiting_payment) continue; charge(order); if (order.status() == OrderStatus::awaiting_payment) ++waiting; } return waiting;}charge moves the order and its stock together on every answer, which
is what keeps INV-3. The payment key is the order id, not the
request key. A request key says “this press of the button”; an order
id says “this order”. retry_payments has no request in hand, only
orders, and it must charge each one under the same key it used the
first time.
Where each rule lives
Section titled “Where each rule lives”| Rule | Where it lives |
|---|---|
| One line per SKU, quantity and line limits | Cart::add, Cart::set_quantity |
| Today’s price, and products no longer sold | Catalog, read by Pricer::quote |
| What each promotion takes off | each Promotion class |
| The order of promotions | the order of the list given to Pricer |
| Never negative, never below zero | Pricer::quote |
| Rounding | percent_of, and nowhere else |
| Stock is never made or lost; all or nothing | Inventory |
| The total is the one the customer saw | Checkout::submit, step 2 |
| One order per key | Checkout::submit, step 1, and attempts_ |
| One charge per order | the gateway contract, keyed by order id |
| Stock follows the payment | Checkout::charge |
| An order’s status moves once | Order::expect_awaiting |
Verification trace
Section titled “Verification trace”Take alice’s order in the step 1 demo: the card is charged, the answer is lost, alice presses the button again, and then the shop retries.
Text description of the diagram
The page submits key k-1 for alice with the total 50.40. Checkout prices the cart, finds 50.40 as shown, reserves the stock for order-1001, and records the order and the key. It charges order-1001 50.40; the provider charges the card but the answer is lost, so checkout sees unavailable, and the page is told the order is placed and awaiting payment. The page sends key k-1 again; checkout finds the key and answers duplicate, order-1001, awaiting payment, without reserving or charging. Later, retry_payments charges order-1001 again under the same key; the provider returns its first answer, approved, without a new charge. Checkout commits the stock and marks the order paid.
Diagram source (Mermaid)
sequenceDiagram
participant P as checkout page
participant C as Checkout
participant I as Inventory
participant G as gateway
P->>C: submit(k-1, alice, 50.40)
C->>C: quote: 50.40, as shown
C->>I: reserve(order-1001, lines)
I-->>C: ok
C->>C: record order-1001 and key k-1
C->>G: charge(order-1001, alice, 50.40)
Note over G: charges, then the answer is lost
G-->>C: unavailable
C-->>P: placed order-1001, awaiting payment
P->>C: submit(k-1, alice, 50.40) again
C-->>P: duplicate: order-1001, awaiting payment
Note over C: later, retry_payments
C->>G: charge(order-1001, alice, 50.40)
G-->>C: approved (the first answer, no new charge)
C->>I: commit(order-1001)
C->>C: mark order-1001 paidStep by step, in the code:
submitdoes not findk-1inattempts_. The cart is not empty, the quote is 50.40, equal toexpected_total, and the id isorder-1001(next_number_starts at 1001).reservemoves 3 teas, 1 mug, and 1 kettle from available to reserved. The order and the attempt are recorded,next_number_becomes 1002, and the cart is cleared.chargecalls the fake, which records an approved charge for keyorder-1001, then returnsunavailable. Theswitchreturns at once: stock reserved, order waiting. The gateway has made 1 call.- The second press finds
k-1, with the same customer and total, and returns a copy oforder-1001. Nothing is reserved or charged. retry_paymentsfindsorder-1001waiting and callscharge. The fake finds the key, the same customer and amount, and returns the first reply,approved. Stock is sold, the order is paid, and the loop counts 0 still waiting.- The demo prints “alice was charged 50.40 in 2 calls”: two calls, one charge.
Put the lost answer anywhere else and the story holds. If the request never arrived, the retry is the first charge. If the retry gets no answer either, the order keeps waiting (AC-4.4). At no point does a second charge go out under a new key.
Architecture and patterns
Section titled “Architecture and patterns”Money as a number of cents
Section titled “Money as a number of cents”Where the price lives
Section titled “Where the price lives”Which key, and when
Section titled “Which key, and when”Reserving stock
Section titled “Reserving stock”What is not here, and why
Section titled “What is not here, and why”- No inventory interface.
Inventoryruns in our process and a test uses the real one. An interface is for a boundary, such as the payment provider. - No State pattern for the order. Three statuses and one move; an enum and a guard say it all.
- No retry loop in
submit. A customer waiting on a page is the wrong place to retry. The order waits, andretry_paymentsis called by whatever schedules background work. - No exceptions for refusals. Every refusal is a
SubmitStatusor aCartChange. The exceptions are for bugs: a conflict from the provider, a second commit of a reservation, an order moved twice. - No threads. One request at a time (NFR-4).
Building it step by step
Section titled “Building it step by step”The example has two steps, each a complete program with its own tests:
- Step 1 is the design above: cart, catalog, pricing with promotions, stock, payment, and idempotent checkout.
- Step 2 is the change: coupons with stacking rules. See When the requirements change.
The order inside step 1 is worth copying. Money and the ids first,
with the rounding test. Then the cart and the pricer, which need no
stock and no payment. Then the fake gateway and the tests of its own
contract (AC-4.5), because every later test trusts it. Then submit
with nothing failing, then each refusal, then each failure of the
provider, one test at a time.
Scenarios
Section titled “Scenarios”The step 1 demo
Section titled “The step 1 demo”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
const Sku tea("tea-500g");const Sku mug("mug-blue");const Sku kettle("kettle-1l");Catalog catalog;catalog.add({tea, "Tea, 500 g", Money{450}});catalog.add({mug, "Blue mug", dollars(12)});catalog.add({kettle, "Kettle, 1 l", dollars(35)});
Inventory inventory;inventory.receive(tea, 10);inventory.receive(mug, 5);inventory.receive(kettle, 2);
// The pricer will own the promotions: make each one, then move the// whole vector into it. They apply in this order.std::vector<std::unique_ptr<Promotion>> promotions;promotions.push_back(std::make_unique<MultiBuy>("3 for 2 on tea", tea, 3, 2));promotions.push_back(std::make_unique<SpendAndSave>("10% off orders of 50.00 or more", dollars(50), 10));const Pricer pricer(catalog, std::move(promotions));
FakeGateway gateway;Checkout checkout(pricer, inventory, gateway);
const CustomerId alice("alice");Cart cart;add(cart, tea, 3);add(cart, mug, 1);add(cart, kettle, 1);std::cout << "alice's cart:\n";show(pricer.quote(cart));
gateway.fail_next(true); // the card is charged; the answer is lost// The page showed 50.40 and made the key k-1 for this button.const SubmitRequest place{RequestKey("k-1"), alice, Money{5040}};std::cout << "place order: " << describe(checkout.submit(place, cart)) << "\n";std::cout << "the button again: " << describe(checkout.submit(place, cart)) << "\n";// Charges order-1001 again under the same key: the provider answers// with the first charge, and does not charge twice.std::cout << "retry payments: " << checkout.retry_payments() << " still waiting\n";std::cout << " " << checkout.find(OrderId("order-1001"))->id().str() << " is " << to_string(checkout.find(OrderId("order-1001"))->status()) << "; alice was charged " << to_string(gateway.charged(alice)) << " in " << gateway.calls() << " calls\n";
const CustomerId bob("bob");Cart bobs;add(bobs, kettle, 1); // shown at 35.00catalog.set_price(kettle, dollars(38));// The first press is refused, so the key k-2 is not used up and the// page can send it again with the new total.std::cout << "bob, shown 35.00: " << describe(checkout.submit({RequestKey("k-2"), bob, dollars(35)}, bobs)) << "\n";std::cout << "bob, shown 38.00: " << describe(checkout.submit({RequestKey("k-2"), bob, dollars(38)}, bobs)) << "\n";
const CustomerId carol("carol");Cart carols;add(carols, kettle, 1); // the cart accepts it: stock is checked only at checkoutstd::cout << "carol: " << describe(checkout.submit({RequestKey("k-3"), carol, dollars(38)}, carols)) << "\n";
const CustomerId dave("dave");gateway.decline(dave);Cart daves;add(daves, mug, 2);std::cout << "dave: " << describe(checkout.submit({RequestKey("k-4"), dave, dollars(24)}, daves)) << "\n";
std::cout << "stock (available / reserved / sold):\n";for (const Sku& sku : {tea, mug, kettle}) { std::cout << " " << sku.str() << " " << inventory.available(sku) << " / " << inventory.reserved(sku) << " / " << inventory.sold(sku) << "\n";}alice's cart: 3 x Tea, 500 g @ 4.50 = 13.50 1 x Blue mug @ 12.00 = 12.00 1 x Kettle, 1 l @ 35.00 = 35.00 subtotal 60.50 3 for 2 on tea: -4.50 10% off orders of 50.00 or more: -5.60 total 50.40place order: placed order-1001, awaiting paymentthe button again: duplicate: order-1001, awaiting paymentretry payments: 0 still waiting order-1001 is paid; alice was charged 50.40 in 2 callsbob, shown 35.00: refused: the total is now 38.00bob, shown 38.00: placed order-1002, paidcarol: refused: not enough stock of kettle-1ldave: placed order-1003, payment failed (Your card was declined.)stock (available / reserved / sold): tea-500g 7 / 0 / 3 mug-blue 4 / 0 / 1 kettle-1l 0 / 0 / 2How this code works: The step 1 demo, call by call
| Call | What submit finds |
Answer | Stock afterwards |
|---|---|---|---|
alice, k-1, shown 50.40 |
new key; quote 50.40; reserve ok; charge lost | placed order-1001, awaiting payment | 5 units reserved |
alice, k-1 again |
key seen, same customer and total | duplicate: order-1001 | unchanged |
retry_payments |
order-1001 waits; the provider repeats “approved” | 0 still waiting; paid | alice’s 5 units sold |
bob, k-2, shown 35.00 |
the kettle is 38.00 now | refused: the total is now 38.00 | unchanged; k-2 not used |
bob, k-2, shown 38.00 |
k-2 not found (the refusal recorded nothing) |
placed order-1002, paid | second kettle sold |
carol, k-3, shown 38.00 |
no kettle available | refused: not enough stock | unchanged; id 1003 not used |
dave, k-4, shown 24.00 |
2 mugs, 24.00, under 50.00: no promotion; declined | placed order-1003, payment failed | dave’s 2 mugs back to available |
Read the last lines of the output against INV-2: tea 7 + 0 + 3 = 10
received, mugs 4 + 0 + 1 = 5, kettles 0 + 0 + 2 = 2. Dave’s order is
order-1003, not 1004, because carol’s refusal came before the order
was recorded, so it did not use up the number.
The tests are named after the acceptance criteria and run against the
real classes, with the fake gateway. A World builds the shop in the
order it needs.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A shop with four products, stock, the two promotions, and a fake// payment provider. Members are declared in the order they are needed:// the pricer reads the catalog, and the checkout uses all of them.struct World { Catalog catalog; Inventory inventory; FakeGateway gateway; Pricer pricer; Checkout checkout;
explicit World(std::vector<std::unique_ptr<Promotion>> promotions = shop_promotions()) : pricer(stocked(catalog, inventory), std::move(promotions)), checkout(pricer, inventory, gateway) {}
// Fills the catalog and the stock, then hands the catalog to the pricer. // Called in the initializer list, so the shop is stocked before the // pricer and the checkout are built. static const Catalog& stocked(Catalog& catalog, Inventory& inventory) { catalog.add({tea, "Tea", Money{450}}); catalog.add({mug, "Mug", dollars(12)}); catalog.add({kettle, "Kettle", dollars(35)}); catalog.add({spoon, "Spoon", dollars(2)}); inventory.receive(tea, 10); inventory.receive(mug, 5); inventory.receive(kettle, 2); inventory.receive(spoon, 20); return catalog; }
// Prices the cart, and places it at the total a customer would be shown. SubmitResult place(const std::string& key, const CustomerId& customer, Cart& cart) { return checkout.submit({RequestKey(key), customer, pricer.quote(cart).total}, cart); }};
// A cart with these lines. Throws if the cart refuses one, so that a test// with a mistake in its setup fails loudly instead of testing the wrong cart.Cart cart_of(std::vector<CartLine> lines) { Cart cart; for (const CartLine& line : lines) { if (cart.add(line.sku, line.quantity) != CartChange::ok) throw std::logic_error("bad test cart"); } return cart;}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The demo's cart: 60.50, less 4.50 for the tea, less 10% of what is// left (56.00), is 50.40.LLD_TEST(ac_2_1_the_demo_cart_prices_line_by_line_then_promotion_by_promotion) { World w; const Quote quote = w.pricer.quote(cart_of({{tea, 3}, {mug, 1}, {kettle, 1}})); LLD_CHECK_EQ(quote.subtotal, Money{6050}); LLD_CHECK_EQ(quote.discounts.size(), std::size_t{2}); LLD_CHECK_EQ(quote.discounts[0].amount, Money{450}); LLD_CHECK_EQ(quote.discounts[1].amount, Money{560}); // 10% of 56.00, after the tea LLD_CHECK_EQ(quote.total, Money{5040});}
// Two teas are not a group of three, so nothing is free; seven teas are// two groups, so two are free.LLD_TEST(ac_2_2_a_multi_buy_counts_only_full_groups) { World w; LLD_CHECK_EQ(w.pricer.quote(cart_of({{tea, 2}})).total, Money{900}); LLD_CHECK_EQ(w.pricer.quote(cart_of({{tea, 7}})).total, Money{2250}); // two free of seven}
LLD_TEST(ac_2_3_spend_and_save_measures_after_earlier_promotions) { World w; // 13.50 + 35.00 + 2.00 = 50.50, but 46.00 after the tea: no 10%. const Quote quote = w.pricer.quote(cart_of({{tea, 3}, {kettle, 1}, {spoon, 1}})); LLD_CHECK_EQ(quote.subtotal, Money{5050}); LLD_CHECK_EQ(quote.discounts.size(), std::size_t{1}); LLD_CHECK_EQ(quote.total, Money{4600});}
// percent_of at the half-cent edges, and its refusals.LLD_TEST(ac_2_4_a_percentage_rounds_to_the_nearest_cent_half_up) { LLD_CHECK_EQ(percent_of(Money{5045}, 10), Money{505}); // 5.045 LLD_CHECK_EQ(percent_of(Money{5044}, 10), Money{504}); LLD_CHECK_EQ(percent_of(Money{5}, 10), Money{1}); // half a cent LLD_CHECK_EQ(percent_of(Money{4}, 10), Money{0}); LLD_CHECK_THROWS(static_cast<void>(percent_of(Money{-1}, 10)), std::invalid_argument); LLD_CHECK_THROWS(static_cast<void>(percent_of(Money{1}, 101)), std::invalid_argument);}
// A promotion worth more than the cart is cut to the cart's value, and a// promotion that returns a negative amount is caught as a bug.LLD_TEST(ac_2_5_a_discount_never_takes_the_total_below_zero) { World w(just(dollars(100))); const Quote quote = w.pricer.quote(cart_of({{mug, 1}})); LLD_CHECK_EQ(quote.discounts[0].amount, dollars(12)); LLD_CHECK_EQ(quote.total, Money{}); World broken(just(Money{-1})); LLD_CHECK_THROWS(static_cast<void>(broken.pricer.quote(cart_of({{mug, 1}}))), std::logic_error);}
// A removed product is listed as unavailable, and the rest is priced.LLD_TEST(ac_2_6_a_product_no_longer_sold_is_listed_not_priced) { World w; w.catalog.remove(kettle); const Quote quote = w.pricer.quote(cart_of({{mug, 1}, {kettle, 1}})); LLD_CHECK(quote.unavailable == std::vector<Sku>{kettle}); LLD_CHECK_EQ(quote.lines.size(), std::size_t{1}); LLD_CHECK_EQ(quote.total, dollars(12));}
// Promotions with impossible settings, and a null promotion, throw when// they are made, not later when a cart is priced.LLD_TEST(ac_2_7_a_promotion_that_makes_no_sense_is_refused_when_built) { LLD_CHECK_THROWS(MultiBuy("x", tea, 3, 3), std::invalid_argument); LLD_CHECK_THROWS(MultiBuy("x", tea, 3, 0), std::invalid_argument); LLD_CHECK_THROWS(SpendAndSave("x", dollars(50), 0), std::invalid_argument); LLD_CHECK_THROWS(SpendAndSave("x", Money{-1}, 10), std::invalid_argument); Catalog catalog; std::vector<std::unique_ptr<Promotion>> with_null; with_null.push_back(nullptr); LLD_CHECK_THROWS(Pricer(catalog, std::move(with_null)), std::invalid_argument);}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The happy path: one charge for the quoted total, the stock sold, and the// cart emptied.LLD_TEST(ac_3_1_a_placed_order_is_charged_once_and_its_stock_sold) { World w; Cart cart = cart_of({{tea, 3}, {mug, 1}, {kettle, 1}}); const SubmitResult result = w.place("k-1", alice, cart); LLD_CHECK_EQ(result.status, SubmitStatus::placed); LLD_CHECK_EQ(result.order->status(), OrderStatus::paid); LLD_CHECK_EQ(result.order->total(), Money{5040}); LLD_CHECK_EQ(w.gateway.charged(alice), Money{5040}); LLD_CHECK_EQ(w.gateway.calls(), std::size_t{1}); LLD_CHECK_EQ(w.inventory.sold(tea), 3); LLD_CHECK_EQ(w.inventory.available(kettle), 1); LLD_CHECK(cart.empty());}
// The price rises after the customer saw it: the order is refused with// the new total, nothing is reserved or charged, and the same key then// works with the new total.LLD_TEST(ac_3_2_a_changed_total_is_refused_and_does_not_use_up_the_key) { World w; Cart cart = cart_of({{kettle, 1}}); w.catalog.set_price(kettle, dollars(38)); const SubmitResult refused = w.checkout.submit({RequestKey("k-1"), alice, dollars(35)}, cart); LLD_CHECK_EQ(refused.status, SubmitStatus::price_changed); LLD_CHECK_EQ(refused.quote.total, dollars(38)); LLD_CHECK_EQ(w.inventory.reserved(kettle), 0); LLD_CHECK_EQ(w.gateway.calls(), std::size_t{0}); LLD_CHECK_EQ(cart.lines().size(), std::size_t{1}); const SubmitResult placed = w.checkout.submit({RequestKey("k-1"), alice, dollars(38)}, cart); LLD_CHECK_EQ(placed.status, SubmitStatus::placed);}
// Two of three lines are short: every short SKU is named, the one with// enough stock is not reserved either, and no order exists.LLD_TEST(ac_3_3_short_stock_reserves_nothing_and_names_every_short_sku) { World w; Cart cart = cart_of({{tea, 2}, {mug, 6}, {kettle, 3}}); const SubmitResult result = w.place("k-1", alice, cart); LLD_CHECK_EQ(result.status, SubmitStatus::out_of_stock); LLD_CHECK(result.short_skus == (std::vector<Sku>{kettle, mug})); // in SKU order LLD_CHECK_EQ(w.inventory.available(tea), 10); LLD_CHECK_EQ(w.inventory.reserved(tea), 0); LLD_CHECK(w.checkout.find(OrderId("order-1001")) == nullptr);}
// An empty cart, then a cart whose product was removed after the customer// saw the total: both are refused before any charge.LLD_TEST(ac_3_4_an_empty_cart_or_a_product_no_longer_sold_is_refused) { World w; Cart empty; LLD_CHECK_EQ(w.checkout.submit({RequestKey("k-1"), alice, Money{}}, empty).status, SubmitStatus::empty_cart); Cart cart = cart_of({{mug, 1}, {kettle, 1}}); const Money shown = w.pricer.quote(cart).total; w.catalog.remove(kettle); const SubmitResult result = w.checkout.submit({RequestKey("k-1"), alice, shown}, cart); LLD_CHECK_EQ(result.status, SubmitStatus::unavailable_product); LLD_CHECK(result.quote.unavailable == std::vector<Sku>{kettle}); LLD_CHECK_EQ(w.gateway.calls(), std::size_t{0});}
// A declined card: the order exists but failed, with the reason, and its// stock is available again.LLD_TEST(ac_3_5_a_declined_card_fails_the_order_and_frees_its_stock) { World w; w.gateway.decline(alice); Cart cart = cart_of({{mug, 2}}); const SubmitResult result = w.place("k-1", alice, cart); LLD_CHECK_EQ(result.status, SubmitStatus::placed); LLD_CHECK_EQ(result.order->status(), OrderStatus::payment_failed); LLD_CHECK_EQ(result.order->failure(), std::string("Your card was declined.")); LLD_CHECK_EQ(w.inventory.available(mug), 5); LLD_CHECK_EQ(w.inventory.reserved(mug), 0); LLD_CHECK_EQ(w.gateway.charged(alice), Money{});}
// A promotion takes the whole total: the order is paid and its stock sold// without calling the gateway, which refuses a charge of zero.LLD_TEST(ac_3_6_an_order_with_nothing_to_pay_is_paid_without_a_charge) { World w(just(dollars(1000))); Cart cart = cart_of({{mug, 1}}); const SubmitResult result = w.place("k-1", alice, cart); LLD_CHECK_EQ(result.order->status(), OrderStatus::paid); LLD_CHECK_EQ(w.gateway.calls(), std::size_t{0}); LLD_CHECK_EQ(w.inventory.sold(mug), 1);}
// A price change after the order is placed does not change the order.LLD_TEST(ac_3_7_an_order_keeps_the_price_it_was_placed_at) { World w; Cart cart = cart_of({{kettle, 1}}); static_cast<void>(w.place("k-1", alice, cart)); w.catalog.set_price(kettle, dollars(99)); const Order* order = w.checkout.find(OrderId("order-1001")); LLD_CHECK_EQ(order->total(), dollars(35)); LLD_CHECK_EQ(order->quote().lines[0].unit, dollars(35));}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same request twice (a double click): the second returns the first// order, and the card is charged once.LLD_TEST(ac_4_1_the_same_key_twice_is_one_order_and_one_charge) { World w; Cart cart = cart_of({{mug, 1}}); const SubmitRequest request{RequestKey("k-1"), alice, dollars(12)}; LLD_CHECK_EQ(w.checkout.submit(request, cart).status, SubmitStatus::placed); const SubmitResult again = w.checkout.submit(request, cart); // the cart is empty now LLD_CHECK_EQ(again.status, SubmitStatus::duplicate); LLD_CHECK_EQ(again.order->id().str(), std::string("order-1001")); LLD_CHECK_EQ(w.gateway.calls(), std::size_t{1}); LLD_CHECK_EQ(w.inventory.sold(mug), 1);}
// The same key with another total or another customer is refused, and// does nothing to the other cart.LLD_TEST(ac_4_2_the_same_key_for_another_request_is_refused) { World w; Cart cart = cart_of({{mug, 1}}); static_cast<void>(w.checkout.submit({RequestKey("k-1"), alice, dollars(12)}, cart)); Cart other = cart_of({{kettle, 1}}); LLD_CHECK_EQ(w.checkout.submit({RequestKey("k-1"), alice, dollars(35)}, other).status, SubmitStatus::key_reused); LLD_CHECK_EQ(w.checkout.submit({RequestKey("k-1"), bob, dollars(12)}, other).status, SubmitStatus::key_reused); LLD_CHECK_EQ(w.inventory.reserved(kettle), 0); LLD_CHECK_EQ(other.lines().size(), std::size_t{1}); LLD_CHECK_EQ(w.gateway.calls(), std::size_t{1});}
LLD_TEST(ac_4_3_a_lost_answer_leaves_the_order_waiting_and_a_retry_charges_once) { // applied: the card was charged and the answer lost. Not applied: the // request never arrived. The shop cannot tell the two apart. for (const bool applied : {false, true}) { World w; Cart cart = cart_of({{kettle, 1}}); w.gateway.fail_next(applied); const SubmitResult result = w.place("k-1", alice, cart); LLD_CHECK_EQ(result.order->status(), OrderStatus::awaiting_payment); LLD_CHECK_EQ(w.inventory.reserved(kettle), 1); LLD_CHECK_EQ(w.gateway.charged(alice), applied ? dollars(35) : Money{}); LLD_CHECK(w.checkout.awaiting_payment() == std::vector<OrderId>{OrderId("order-1001")}); LLD_CHECK_EQ(w.checkout.retry_payments(), std::size_t{0}); LLD_CHECK_EQ(w.checkout.find(OrderId("order-1001"))->status(), OrderStatus::paid); LLD_CHECK_EQ(w.gateway.charged(alice), dollars(35)); LLD_CHECK_EQ(w.gateway.approved(), std::size_t{1}); LLD_CHECK_EQ(w.inventory.sold(kettle), 1); }}
// A retry that also gets no answer leaves the order waiting; the next one// pays it; after that, a retry has nothing to do and calls no one.LLD_TEST(ac_4_4_a_retry_with_no_answer_again_keeps_waiting) { World w; Cart cart = cart_of({{kettle, 1}}); w.gateway.fail_next(); static_cast<void>(w.place("k-1", alice, cart)); w.gateway.fail_next(); LLD_CHECK_EQ(w.checkout.retry_payments(), std::size_t{1}); LLD_CHECK_EQ(w.checkout.retry_payments(), std::size_t{0}); const std::size_t calls = w.gateway.calls(); LLD_CHECK_EQ(w.checkout.retry_payments(), std::size_t{0}); // nothing waits: no call LLD_CHECK_EQ(w.gateway.calls(), calls);}
// The fake itself: a repeat gets the first answer, a different customer// or amount under a key is a conflict, and a decline is repeated too.LLD_TEST(ac_4_5_the_fake_gateway_keeps_the_contract) { FakeGateway gateway; LLD_CHECK(gateway.charge("order-1", alice, dollars(5)).status == ChargeStatus::approved); LLD_CHECK(gateway.charge("order-1", alice, dollars(5)).status == ChargeStatus::approved); LLD_CHECK(gateway.charge("order-1", alice, dollars(6)).status == ChargeStatus::conflict); LLD_CHECK(gateway.charge("order-1", bob, dollars(5)).status == ChargeStatus::conflict); LLD_CHECK_EQ(gateway.charged(alice), dollars(5)); gateway.decline(bob); LLD_CHECK(gateway.charge("order-2", bob, dollars(5)).status == ChargeStatus::declined); LLD_CHECK(gateway.charge("order-2", bob, dollars(5)).status == ChargeStatus::declined); LLD_CHECK_EQ(gateway.approved(), std::size_t{1});}
LLD_TEST(ac_4_6_a_conflict_from_the_gateway_is_a_bug_and_throws) { // The order id is the payment key. If something else charged under it, // the shop has a bug: a conflict is not an answer to show a customer. World w; static_cast<void>(w.gateway.charge("order-1001", bob, dollars(1))); Cart cart = cart_of({{mug, 1}}); LLD_CHECK_THROWS(static_cast<void>(w.place("k-1", alice, cart)), std::logic_error); LLD_CHECK_EQ(w.checkout.find(OrderId("order-1001"))->status(), OrderStatus::awaiting_payment);}ac_4_3 runs twice, once for a request that never arrived and once
for a charge whose answer was lost. Both end the same way: one approved
charge, the order paid, the kettle sold. That is the test of “the shop
cannot tell them apart, and does not need to”.
A random run. The last test makes 3,000 random steps.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Random carts, customers, price changes, repeated presses, lost answers// of both kinds, declines, and retries. After every step, no unit of// stock is made or lost, and reserved and sold stock match the orders.// At the end, once every answer arrives, each customer was charged// exactly the totals of their paid orders.LLD_TEST(inv_stock_and_money_add_up) { std::mt19937 random(2026); // pick(n) is a random number from 0 to n - 1. A fixed seed makes each // run the same, so a failure can be repeated. auto pick = [&](int n) { return static_cast<int>(random() % static_cast<unsigned>(n)); }; World w; const std::vector<Sku> skus{tea, mug, kettle, spoon}; std::map<Sku, int> received{{tea, 10}, {mug, 5}, {kettle, 2}, {spoon, 20}}; for (const Sku& sku : skus) { w.inventory.receive(sku, 200); received[sku] += 200; } const std::vector<CustomerId> customers{alice, bob, CustomerId("carol"), CustomerId("dave")}; w.gateway.decline(customers[3]); std::vector<OrderId> placed; std::vector<SubmitRequest> sent;
for (int step = 0; step < 3000; ++step) { switch (pick(6)) { case 0: case 1: { Cart cart; for (int i = 0; i < 1 + pick(3); ++i) static_cast<void>(cart.add(skus[static_cast<std::size_t>(pick(4))], 1 + pick(4))); const SubmitRequest request{RequestKey("k-" + std::to_string(step)), customers[static_cast<std::size_t>(pick(4))], pick(8) == 0 ? Money{1} : w.pricer.quote(cart).total}; if (pick(4) == 0) w.gateway.fail_next(pick(2) == 1); const SubmitResult result = w.checkout.submit(request, cart); if (result.status == SubmitStatus::placed) placed.push_back(result.order->id()); sent.push_back(request); break; } case 2: if (!sent.empty()) { // a repeat of an earlier press Cart empty; const SubmitResult result = w.checkout.submit(sent[static_cast<std::size_t>(pick(static_cast<int>(sent.size())))], empty); LLD_CHECK(result.status != SubmitStatus::placed); } break; case 3: w.catalog.set_price(skus[static_cast<std::size_t>(pick(4))], Money{100 * (1 + pick(40))}); break; case 4: if (pick(3) == 0) w.gateway.fail_next(pick(2) == 1); static_cast<void>(w.checkout.retry_payments()); break; case 5: w.gateway.fail_next(pick(2) == 1); break; } // Work out from the orders alone what should be reserved and sold, // and compare with the inventory's own piles. std::map<Sku, int> reserved; std::map<Sku, int> sold; for (const OrderId& id : placed) { const Order* order = w.checkout.find(id); for (const PricedLine& line : order->quote().lines) { if (order->status() == OrderStatus::awaiting_payment) reserved[line.sku] += line.quantity; if (order->status() == OrderStatus::paid) sold[line.sku] += line.quantity; } } for (const Sku& sku : skus) { LLD_CHECK_EQ(w.inventory.available(sku) + w.inventory.reserved(sku) + w.inventory.sold(sku), received[sku]); LLD_CHECK_EQ(w.inventory.reserved(sku), reserved[sku]); LLD_CHECK_EQ(w.inventory.sold(sku), sold[sku]); } }
w.gateway.fail_next(true); w.gateway.fail_next(false); // a failure set and not used is replaced, not queued // Retry until nothing waits: the planned failure is used by the first // charge, so this ends. while (w.checkout.retry_payments() != 0) { } std::map<CustomerId, Money> paid; for (const OrderId& id : placed) { const Order* order = w.checkout.find(id); if (order->status() == OrderStatus::paid) paid[order->customer()] = paid[order->customer()] + order->total(); } for (const CustomerId& customer : customers) LLD_CHECK_EQ(w.gateway.charged(customer), paid[customer]); LLD_CHECK(placed.size() > 100);}How this code works: The step 1 random run
- A repeatable dice.
std::mt19937 random(2026)has a fixed seed, so every run makes the same steps and a failure can be replayed.pick(n)gives a whole number from 0 ton - 1. - Six kinds of step. Two of the six place a random cart (one time in eight with a wrong total, one time in four with a lost answer of either kind); one repeats an earlier request on an empty cart, which must never place a new order; one changes a price; one retries payments; one plans a failure.
- The check after every step works out, from the orders alone, what should be reserved (waiting orders) and sold (paid orders), and compares it with the inventory’s piles, along with INV-2.
- The end. Retry until nothing waits, then check that each customer was charged exactly the sum of their paid orders. A double charge or a lost charge anywhere in the run breaks that line.
Checking the tests. The tests were checked by hand-written mutations of the code, applied one at a time by a script to a scratch copy (the script is not part of the example). All 18 mutants, across the two steps, made at least one test fail.
When the requirements change
Section titled “When the requirements change”“Marketing wants coupons. A customer types a code at checkout: ‘SAVE10’ is 10% off, ‘TAKE5’ is 5.00 off orders over 30.00. They want people to combine some of them, but not go wild. And each customer gets each coupon once.”
The team’s answers to the questions that follow:
| Question | Answer |
|---|---|
| Can coupons be combined? | Amount coupons, yes. Only one percentage coupon per order. At most two in all. |
| In what order do they apply? | Promotions first, then the percentage coupon, then amount coupons. |
| Can a coupon be refused when a promotion applies? | Some say “not with promotions”. Only promotions that actually took something count. |
| Is “orders over 30.00” before or after promotions? | After promotions, before coupons. Exactly 30.00 is enough. |
| What if a coupon is worth more than what is left? | It takes what is left. Never below zero. |
| “Once per customer”: when is it used? | When the order is paid. A declined order gives it back. |
| Does the case matter, or stray spaces? | No. “ save10 “ is SAVE10. |
| How is 15% of 16.50 rounded? | As every percentage: to the nearest cent, a half cent up. 2.48. |
| What does the customer see for a coupon that is refused? | A reason, for every code they typed. |
One new requirement:
- FR-9 Coupons. At checkout a customer may enter codes. Each one is applied, or refused with a reason, by the stacking rules above. A coupon is held by an order that waits for payment, used by a paid order, and freed by a declined one, and each customer uses each coupon at most once.
Use cases for the change
Section titled “Use cases for the change”UC-6 Use coupons.
- AC-6.1 Codes are normalised (trimmed, upper-cased) before lookup.
- AC-6.2 Amount coupons stack, but only one percentage coupon applies.
- AC-6.3 At most two coupons apply; a refused coupon does not take a place.
- AC-6.4 Promotions, then the percentage coupon, then amount coupons, whatever order the codes were typed in.
- AC-6.5 A “not with promotions” coupon is refused if any promotion applied.
- AC-6.6 A minimum spend is checked against the total after promotions.
- AC-6.7 A percentage coupon rounds to the nearest cent, a half cent up.
- AC-6.8 Coupons never take the total below zero.
- AC-6.9 Every refused coupon is reported with a reason.
- AC-6.10 A coupon is used once per customer, when the order is paid.
- AC-6.11 A declined payment releases the coupon.
- AC-6.12 A lost answer holds the coupon, and a retry uses it once.
- AC-6.13 The same key with other coupons is refused.
- AC-6.14 A coupon taken meanwhile changes the total and refuses the order.
- AC-6.15 A coupon that makes no sense is refused when added.
- AC-6.16 The coupon book holds all or nothing, and settles once.
One more invariant:
- INV-8 A coupon’s use matches the orders. For each customer and
coupon, at most one waiting order holds it, or one paid order used
it, never both. Kept by
CouponBook, moved byCheckout::chargetogether with the stock.
What moved
Section titled “What moved”| File | Change |
|---|---|
coupon.hpp |
new: Coupon, PercentOff, AmountOff, CouponRefusal, AppliedCoupon, RejectedCoupon, normalise_code |
coupon_book.* |
new: the coupons, and who has used which; reserve, commit, release |
pricing.* |
Quote gains after_promotions, coupons, and rejected; Pricer gains the book and apply_coupons |
checkout.* |
the request carries the codes; submit holds the coupons with the stock; charge settles both |
| tests | the 29 step 1 tests are kept, with a World that also has a coupon book; 16 coupon tests are added; the random test also checks coupons |
The cart, the catalog, the stock, the order, and the payment did not change. The promotions did not change either: coupons are not a new kind of promotion, because they differ in the two ways that matter. A promotion applies to everyone; a coupon only when typed. A promotion can be used any number of times; a coupon once per customer, which needs a record that lasts beyond one quote.
The coupon
Section titled “The coupon”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// New in step 2. A coupon is a code a customer types in. Unlike a// promotion, which the shop runs for everyone, a coupon applies only when// entered, and each customer may use each coupon once.
// "10% off": a percentage of what is left after the promotions, rounded// to the nearest cent, a half cent up (percent_of in money.hpp).struct PercentOff { int percent = 0; // 1 to 100};
// "5.00 off": a fixed amount, but never more than what is left.struct AmountOff { Money amount; // positive};
// What the coupon takes off. A std::variant holds exactly one of the// types listed, so a coupon is always one kind, never both or neither, and// each kind carries only the field it needs.using CouponValue = std::variant<PercentOff, AmountOff>;
// One coupon, as the shop defines it. A plain value: the CouponBook keeps// the copy that counts.struct Coupon { std::string code; // stored normalised: "SAVE10" CouponValue value; Money minimum_spend; // compared with the total after promotions; zero for none bool not_with_promotions = false; // refused if any promotion applied};
// Why a coupon the customer entered was not applied. Every refusal is// reported, never dropped in silence, so that the page can say why.enum class CouponRefusal { unknown_code, // no coupon has this code entered_twice, // the same code is already in this request already_used, // this customer used it on a paid order held_by_another_order, // this customer's order that waits for payment holds it not_with_promotions, // this coupon is refused when a promotion applied minimum_spend_not_met, // the total after promotions is below its minimum one_percentage_only, // a percentage coupon is already applied too_many_coupons, // two coupons are already applied nothing_to_take_off, // it would take off 0.00};
// A short name for each refusal, for logs and tests. The text the// customer sees is in RejectedCoupon, and can say more.[[nodiscard]] constexpr std::string_view to_string(CouponRefusal refusal) { switch (refusal) { case CouponRefusal::unknown_code: return "unknown code"; case CouponRefusal::entered_twice: return "entered twice"; case CouponRefusal::already_used: return "already used"; case CouponRefusal::held_by_another_order: return "held by another order"; case CouponRefusal::not_with_promotions: return "not with promotions"; case CouponRefusal::minimum_spend_not_met: return "minimum spend not met"; case CouponRefusal::one_percentage_only: return "one percentage only"; case CouponRefusal::too_many_coupons: return "too many coupons"; case CouponRefusal::nothing_to_take_off: return "nothing to take off"; } return "?"; // not reached for a valid value; see to_string(OrderStatus)}
// A coupon that was applied, and what it took off.struct AppliedCoupon { std::string code; // normalised Money amount; // positive};
// A coupon that was not applied: the code as the customer typed it, the// reason as a value a program can test, and a sentence for the customer.struct RejectedCoupon { std::string entered; CouponRefusal reason = CouponRefusal::unknown_code; std::string text;};
// The form a code is stored and looked up in: spaces, tabs, and line// breaks trimmed from both ends, and letters upper-cased, so that// " save10 " finds SAVE10. Spaces inside the code are kept.// std::isspace and std::toupper need an unsigned char: a plain char can be// negative, and passing a negative value (other than EOF) is undefined.[[nodiscard]] inline std::string normalise_code(std::string_view entered) { std::size_t first = 0; std::size_t last = entered.size(); // one past the last character kept while (first < last && std::isspace(static_cast<unsigned char>(entered[first])) != 0) ++first; while (last > first && std::isspace(static_cast<unsigned char>(entered[last - 1])) != 0) --last; std::string code(entered.substr(first, last - first)); for (char& c : code) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c))); return code;}A coupon’s value is a std::variant of PercentOff and AmountOff.
A coupon is always exactly one kind, and each kind has only the field
it needs. The refusal is a CouponRefusal, a value a program can test,
plus a sentence for the customer; the code as typed is kept, so the
page can point at the right box.
The stacking rules
Section titled “The stacking rules”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One cart line at today's price: the name and unit price are copied// from the catalog when the quote is made, so the quote stays as it was// if the catalog changes later.struct PricedLine { Sku sku; std::string name; Money unit; int quantity = 0;
[[nodiscard]] Money total() const { return unit * quantity; }};
// One line of the "you save" list on a quote.struct Discount { std::string label; // "3 for 2 on tea" Money amount; // positive: what comes off};
// What the cart costs now. A quote is a value: made fresh from the cart,// the catalog, the promotions, and the coupons entered each time, and// never stored in the cart. Step 2 adds the three coupon members.struct Quote { std::vector<PricedLine> lines; // lines whose product is still sold std::vector<Sku> unavailable; // lines whose product is not Money subtotal; // the sum of lines std::vector<Discount> discounts; // the promotions that applied, in order Money after_promotions; // subtotal less promotions: what minimum spends check std::vector<AppliedCoupon> coupons; // in the order applied: the percentage one first std::vector<RejectedCoupon> rejected; // every coupon entered and not applied, with why Money total; // after_promotions less every coupon; never below zero};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The coupon rules, in two passes over the codes entered.// Pass 1, in the order entered, decides which coupons are accepted. Each// code is checked against the rules for one coupon (known, not entered// twice, free for this customer, not refused with promotions, minimum// spend met), then against the stacking rules (one percentage coupon at// most, max_coupons in all). The first coupons to pass are kept; a later// one that would break a stacking rule is refused, even if it is worth// more (choosing the best set for the customer is a different rule).// Pass 2 applies the accepted coupons in the fixed order: the percentage// coupon first, then the amount coupons in the order entered, each on what// is left. A coupon that would take off nothing is refused there, so that// it is not used up for nothing; its place is not given to a coupon that// pass 1 refused. So quote.rejected lists the pass 1 refusals in the order// entered, then any pass 2 refusals.void Pricer::apply_coupons(Quote& quote, const CustomerId& customer, const std::vector<std::string>& codes) const { const bool any_promotion = !quote.discounts.empty(); // A coupon accepted in pass 1, and the code as typed, for a refusal in // pass 2. The pointer is to the book's coupon, which outlives this call. struct Accepted { std::string entered; const Coupon* coupon = nullptr; }; std::optional<Accepted> percentage; // the one percentage coupon accepted, if any std::vector<Accepted> amounts; // the amount coupons accepted, in the order entered std::set<std::string> seen; // normalised codes already in this request
// A lambda that records a refusal; [&] lets it add to quote.rejected. auto refuse = [&](const std::string& entered, CouponRefusal reason, std::string text) { quote.rejected.push_back({entered, reason, std::move(text)}); };
// ---- pass 1: accept or refuse each code ---- for (const std::string& entered : codes) { const std::string code = normalise_code(entered); const Coupon* coupon = coupons_->find(code); if (coupon == nullptr) { refuse(entered, CouponRefusal::unknown_code, "There is no coupon " + code + "."); continue; // continue: on to the next code; this one is done } // insert returns a pair; .second is false when the code was there already. if (!seen.insert(code).second) { refuse(entered, CouponRefusal::entered_twice, code + " is already entered."); continue; } const CouponUse use = coupons_->use(code, customer); if (use == CouponUse::used) { refuse(entered, CouponRefusal::already_used, "You have already used " + code + "."); continue; } if (use == CouponUse::held) { refuse(entered, CouponRefusal::held_by_another_order, code + " is held by your order that is waiting for payment."); continue; } if (coupon->not_with_promotions && any_promotion) { refuse(entered, CouponRefusal::not_with_promotions, code + " cannot be used with a promotion."); continue; } if (quote.after_promotions < coupon->minimum_spend) { // exactly the minimum is enough refuse(entered, CouponRefusal::minimum_spend_not_met, code + " needs a spend of " + to_string(coupon->minimum_spend) + " after promotions; this order is " + to_string(quote.after_promotions) + "."); continue; } const bool is_percentage = std::holds_alternative<PercentOff>(coupon->value); if (is_percentage && percentage.has_value()) { refuse(entered, CouponRefusal::one_percentage_only, "Only one percentage coupon can be used per order."); continue; } // The count of coupons accepted so far: 1 if there is a percentage // coupon (the ?: gives 1 or 0), plus the amount coupons. const std::size_t accepted = (percentage.has_value() ? 1U : 0U) + amounts.size(); if (accepted == max_coupons) { refuse(entered, CouponRefusal::too_many_coupons, "At most " + std::to_string(max_coupons) + " coupons can be used per order."); continue; } if (is_percentage) { percentage = Accepted{entered, coupon}; } else { amounts.push_back({entered, coupon}); } }
// ---- pass 2: apply them, the percentage coupon first ---- Money so_far = quote.after_promotions; auto take = [&](const Accepted& accepted, Money amount) { const std::string& code = accepted.coupon->code; if (amount == Money{}) { refuse(accepted.entered, CouponRefusal::nothing_to_take_off, code + " would take nothing off this order."); return; // leaves the lambda only, not apply_coupons } quote.coupons.push_back({code, amount}); so_far = so_far - amount; }; if (percentage.has_value()) { // percent_of rounds to the nearest cent, a half cent up. At most // 100 percent, so it never takes more than so_far. std::get is safe: // pass 1 put only a PercentOff coupon here. take(*percentage, percent_of(so_far, std::get<PercentOff>(percentage->coupon->value).percent)); } for (const Accepted& accepted : amounts) { // std::min cuts the amount to what is left: the total never goes // below zero, and a 5.00 coupon on 3.00 takes 3.00. take(accepted, std::min(std::get<AmountOff>(accepted.coupon->value).amount, so_far)); } quote.total = so_far;}The rules live in Pricer::apply_coupons, because they are pricing
rules: which coupons stack, in what order, and what each takes off. The
CouponBook only knows what exists and who used what. Each rule, where
it is, and why:
| Rule | Where in the code | Why |
|---|---|---|
| Codes are normalised | normalise_code, called by find, use, reserve, and pass 1 |
“ save10 “ and “SAVE10” are one coupon; trimming and case are the commonest typing slips |
| Unknown or entered twice | pass 1, find and the seen set |
the same coupon twice would be a second use; seen holds normalised codes, so “take3” and “ TAKE3 “ clash |
| Once per customer | pass 1, use(code, customer): used or held is refused |
a paid order used it; a waiting order holds it, and may yet be paid |
| Not with promotions | pass 1, any_promotion, which is !quote.discounts.empty() |
a promotion that took nothing is not listed, so it does not count (AC-6.5) |
| Minimum spend after promotions | pass 1, quote.after_promotions < minimum_spend |
the spend the customer really makes; < so that exactly the minimum is enough |
| One percentage coupon | pass 1, is_percentage && percentage.has_value() |
two percentages compound and are hard to explain; the first one typed is kept |
| At most two in all | pass 1, accepted == max_coupons, counting accepted coupons only |
a refused coupon (say, an unknown code) does not take a place (AC-6.3) |
| Promotions, percentage, then amounts | quote(cart, customer, codes) prices first; pass 2 takes percentage before amounts |
once the coupons are accepted, the order they were typed in does not change the total (AC-6.4) |
| Rounding | pass 2, percent_of(so_far, percent) |
the one rounding rule of the shop: to the nearest cent, a half cent up |
| Never below zero | pass 2, std::min(amount, so_far); a percentage is at most 100 |
a 10.00 coupon on 4.50 takes 4.50 |
| Nothing to take off | pass 2, take, when the amount is zero |
a coupon that saves nothing should not be used up |
| Every refusal reported | refuse, called on every path that does not accept or apply |
a code typed and silently dropped looks like a bug to the customer |
Note what pass 1 does not do: it does not choose the best set of coupons for the customer. The first coupons to pass are kept, and a later one that would break a stacking rule is refused even if it is worth more. “Give the customer the best combination” is a different rule, with a search over the combinations, and the team did not ask for it.
How this code works: apply_coupons on alice's four codes
Alice’s cart is the demo cart, 50.40 after both promotions. She types
" save10 ", "welcome15", "take5", "Take3".
Pass 1, in the order typed:
| Typed | Normalised | Check that decides | Result |
|---|---|---|---|
" save10 " |
SAVE10 |
every check passes; it is a percentage | accepted as percentage |
"welcome15" |
WELCOME15 |
not with promotions, and two promotions applied | refused: not with promotions |
"take5" |
TAKE5 |
50.40 is at least the 30.00 minimum; 1 accepted so far | accepted into amounts |
"Take3" |
TAKE3 |
2 accepted so far, which is max_coupons |
refused: too many coupons |
Pass 2, in the fixed order:
| Coupon | Amount worked out | so_far after |
|---|---|---|
| (start) | after_promotions |
50.40 |
SAVE10 |
percent_of(5040, 10): (50400 + 50) / 100 = 504, so 5.04 |
45.36 |
TAKE5 |
std::min(5.00, 45.36) = 5.00 |
40.36 |
The total is 40.36, and rejected lists "welcome15" then "Take3",
each with the text the demo prints. Had she typed TAKE5 before SAVE10,
the result would be the same: pass 2 does not follow the typed order.
How this code works: A coupon that takes nothing keeps its place
A coupon accepted in pass 1 can still take nothing in pass 2, when
almost nothing is left. Then take refuses it as nothing_to_take_off,
so it is not held and not used up. But its place among the two is
not given to a coupon that pass 1 refused. Two cases, worked out by
running the step 2 code (they are not in the test suite):
| Cart | Codes typed | Pass 1 | Pass 2 | Total |
|---|---|---|---|---|
| one kettle, 35.00 | ALL100, TAKE3, TAKE1 |
ALL100 and TAKE3 accepted; TAKE1 too many | ALL100 takes 35.00; TAKE3 takes nothing, refused | 0.00 |
| a 0.04 item | SAVE10, TAKE3, TAKE1 |
SAVE10 and TAKE3 accepted; TAKE1 too many | 10% of 0.04 rounds to 0.00, refused; TAKE3 takes 0.04 | 0.00 |
In both, TAKE1 stays “too many coupons”, and in both it would have
taken nothing anyway, because a coupon takes nothing only when (almost)
nothing is left. That is why the simpler rule costs the customer
little. Freeing the place would mean going back to pass 1 after pass 2,
and the reason given for TAKE1 would then depend on amounts worked out
later, which is harder to explain on the page and harder to test. The
choice is written in the comment above apply_coupons, so that a
reader does not take it for an accident.
Who has used which coupon
Section titled “Who has used which coupon”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Where one customer's use of one coupon stands.enum class CouponUse { unused, held, // an order that waits for payment holds it used, // a paid order used it: never again for this customer};
// New in step 2. The coupons the shop offers, and who has used which.// The use of a coupon moves like stock does: reserve holds it for an// order, then commit marks it used when the order is paid, or release// frees it when the payment fails. A concrete class, as Inventory is: it// runs in our process, and a test uses the real one.// Every function that takes a code normalises it first, so " save10 "// and "SAVE10" are the same coupon.class CouponBook {public: // Stores the coupon under its normalised code. Throws // std::invalid_argument for a code that is empty once normalised, a // code already added, a percent outside 1..100, an amount that is not // positive, or a minimum spend below zero. void add(Coupon coupon);
// The coupon, or nullptr for an unknown code. Points at the book's own // copy, which lives as long as the book: there is no way to remove one. [[nodiscard]] const Coupon* find(std::string_view code) const; // Where this customer's use of the coupon stands: unused if it was // never held, or its hold was released, or the code is unknown. [[nodiscard]] CouponUse use(std::string_view code, const CustomerId& customer) const;
// Holds every one of the codes for the order, all or nothing. An order // with no coupons still gets an (empty) hold, so that commit and // release can be called for every order. Throws std::logic_error for an // order that already has a hold, or a code that is unknown or not // unused for this customer: the Pricer has refused those already, so // either is a bug in the caller. If it throws, nothing changed. void reserve(const OrderId& order, const CustomerId& customer, const std::vector<std::string>& codes); // The order is paid: each code it holds is used. void commit(const OrderId& order); // The order will not be paid: each code it holds is unused again. void release(const OrderId& order); // commit and release throw std::logic_error for an order with no hold: // a second commit or release is a bug in the caller.
private: // One customer's use of one coupon is keyed by both: the normalised // code and the customer. using UseKey = std::pair<std::string, CustomerId>;
std::map<std::string, Coupon> coupons_; // by normalised code std::map<UseKey, CouponUse> uses_; // held or used only; no entry means unused std::map<OrderId, std::vector<UseKey>> holds_; // per order, the uses it holds, until commit or release};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Checks everything first and only then changes anything, as// Inventory::reserve does. The keys are built during the checks, so the// changes are only inserts, which can fail only for lack of memory; if one// does, the catch block takes out what was put in, so that a throw leaves// the book as it was.void CouponBook::reserve(const OrderId& order, const CustomerId& customer, const std::vector<std::string>& codes) { if (holds_.count(order) != 0) throw std::logic_error("coupons already held for " + order.str()); std::vector<UseKey> keys; // one per code, built before anything changes std::set<std::string> seen; // a code twice is a bug: the Pricer refuses the second for (const std::string& entered : codes) { std::string code = normalise_code(entered); if (coupons_.count(code) == 0) throw std::logic_error("not a coupon: " + code); if (use(code, customer) != CouponUse::unused) { throw std::logic_error(code + " is not free for " + customer.str()); } if (!seen.insert(code).second) throw std::logic_error(code + " is entered twice"); keys.emplace_back(std::move(code), customer); }
const auto placed = holds_.emplace(order, std::move(keys)).first; // keys is moved from now std::size_t done = 0; // how many codes are marked held so far try { for (const UseKey& key : placed->second) { uses_.emplace(key, CouponUse::held); ++done; } } catch (...) { // Undo in any order. Each erase uses a key that already exists, so // nothing is allocated and nothing can throw; and each key went in // new (the checks above made sure no entry existed). for (std::size_t i = 0; i < done; ++i) uses_.erase(placed->second[i]); holds_.erase(placed); throw; // the same exception, on to the caller }}
// commit and release use the keys stored by reserve. They make no new// strings, so they allocate nothing, and running out of memory cannot stop// them half way.void CouponBook::commit(const OrderId& order) { const auto found = holds_.find(order); if (found == holds_.end()) throw std::logic_error("no coupons held for " + order.str()); // at, not []: every held code has an entry, and at would throw rather // than quietly add one if that were ever not so. for (const UseKey& key : found->second) uses_.at(key) = CouponUse::used; holds_.erase(found); // a second commit or release now throws}
void CouponBook::release(const OrderId& order) { const auto found = holds_.find(order); if (found == holds_.end()) throw std::logic_error("no coupons held for " + order.str()); // No entry in uses_ means unused, so freeing a code is erasing its entry. for (const UseKey& key : found->second) uses_.erase(key); holds_.erase(found);}“Once per customer” cannot be a check at pricing time alone. Between
the quote and the payment, the same customer can open a second tab and
submit the same coupon again. So a coupon goes through the same three
steps as the stock: reserve it for an order (held), then commit
it when the order is paid (used), or release it when the payment is
declined (unused again). Each customer and code has at most one entry
in uses_, so INV-8 holds by the shape of the data: a code cannot be
both held and used.
reserve follows the pattern of Inventory::reserve: check every code
first, change nothing until all pass, and undo what was put in if an
insert throws. It throws std::logic_error on a code that is not free,
because the Pricer has already refused such a code; reaching it would
be a bug in the shop, not a mistake by the customer. commit and
release erase the hold, so a second call for the same order throws
(AC-6.16): an order cannot use its coupons twice, or give them back
after using them.
Checkout holds the coupons with the stock
Section titled “Checkout holds the coupons with the stock”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Five steps, each of which may end the call early with a refusal. Every// refusal comes before anything is recorded, so it changes nothing and// the same key can be sent again once the customer has fixed the problem.SubmitResult Checkout::submit(const SubmitRequest& request, Cart& cart) { // 1. A key seen before: a repeat of that request, or a mistake. Compare // the request, not the cart: the first submission emptied it. if (const auto found = attempts_.find(request.key); found != attempts_.end()) { const Attempt& first = found->second; if (first.customer != request.customer || first.expected_total != request.expected_total || first.coupons != request.coupons) { return {SubmitStatus::key_reused, std::nullopt, {}, {}}; } // The four values fill the SubmitResult members in order; {} leaves // one empty. orders_.at copies the order into the result. Nothing // is reserved or charged again: the coupons stay with the first // order, held or used, and are not held a second time. return {SubmitStatus::duplicate, orders_.at(first.order), {}, {}}; }
// 2. Check the cart against today's catalog and what the customer saw. // The quote includes the coupons. A coupon that was refused when // the customer saw the total, and is refused again now, leaves the // total as shown, and the order goes ahead without it. A coupon // whose answer has changed (say, used meanwhile by another order) // changes the total, and the order is refused. if (cart.empty()) return {SubmitStatus::empty_cart, std::nullopt, {}, {}}; Quote quote = pricer_->quote(cart, request.customer, request.coupons); // The refusals hand back the quote (moved, not copied), so that the page // can show the customer what changed. if (!quote.unavailable.empty()) return {SubmitStatus::unavailable_product, std::nullopt, std::move(quote), {}}; if (quote.total != request.expected_total) { return {SubmitStatus::price_changed, std::nullopt, std::move(quote), {}}; }
// 3. Reserve the stock, all or nothing. // The number is used up only once the order is recorded (below), so a // refusal here lets the next order take the same id. OrderId id("order-" + std::to_string(next_number_)); ReserveResult reserved = inventory_->reserve(id, cart.lines()); if (!reserved.ok) return {SubmitStatus::out_of_stock, std::nullopt, std::move(quote), std::move(reserved.short_skus)};
// 4. Hold the coupons the quote applied, record the order and the // key. If any of that throws, undo what was done, so that a refusal // of any kind leaves nothing behind. // Three nested try blocks undo in reverse order: if the key cannot // be recorded, the order is erased; if that or the order fails, the // coupons are freed; if anything fails, the stock goes back. // `throw;` passes the same exception on to the caller. std::vector<std::string> codes; // the normalised codes of the coupons applied for (const AppliedCoupon& coupon : quote.coupons) codes.push_back(coupon.code); Order* order = nullptr; // points into orders_; a std::map never moves its entries try { coupons_->reserve(id, request.customer, codes); try { // emplace returns a pair (iterator, inserted); .first->second is the new Order. order = &orders_.emplace(id, Order(id, request.customer, quote)).first->second; try { attempts_.emplace(request.key, Attempt{request.customer, request.expected_total, request.coupons, id}); } catch (...) { orders_.erase(id); throw; } } catch (...) { coupons_->release(id); throw; } } catch (...) { inventory_->release(id); throw; } ++next_number_; cart.clear(); // the cart is now the order
// 5. Charge. Whatever the answer, the order exists and the key is used. charge(*order); return {SubmitStatus::placed, *order, std::move(quote), {}};}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each answer moves the stock, the coupons, and the order together:// approved sells the stock, marks the coupons used, and marks the order// paid; declined frees the stock and the coupons and fails the order;// unavailable changes nothing, so the order can be charged again, and its// coupons stay held, so that no other order can use them meanwhile.void Checkout::charge(Order& order) { if (order.total() == Money{}) { // promotions and coupons took it all: nothing to charge inventory_->commit(order.id()); coupons_->commit(order.id()); order.mark_paid(); return; } // The order id is the payment key: a retry of the same order cannot // charge twice, even if an earlier attempt was applied and its answer lost. const ChargeReply reply = gateway_->charge(order.id().str(), order.customer(), order.total()); switch (reply.status) { case ChargeStatus::approved: inventory_->commit(order.id()); coupons_->commit(order.id()); order.mark_paid(); return; case ChargeStatus::declined: inventory_->release(order.id()); coupons_->release(order.id()); // the customer may use them on another order order.mark_failed(reply.reason); return; case ChargeStatus::unavailable: return; // no answer: the order waits, and its stock and coupons stay held case ChargeStatus::conflict: // Each order has its own id and a total that never changes, so // this is a bug, not something the customer did. throw std::logic_error("the payment key " + order.id().str() + " was used for another charge"); }}
// Visits every order and charges only those still waiting. Each charge// uses the order id as its key, so a charge that was applied before, with// its answer lost, is answered again rather than taken twice.std::size_t Checkout::retry_payments() { std::size_t waiting = 0; for (auto& [id, order] : orders_) { // auto&: change the stored orders, not copies if (order.status() != OrderStatus::awaiting_payment) continue; charge(order); if (order.status() == OrderStatus::awaiting_payment) ++waiting; } return waiting;}The five steps of submit stay. Three things change:
- Step 1 compares the coupons too. The same key with other codes is
a mistake,
key_reused(AC-6.13), not a duplicate. - Step 2 prices the cart with the codes. A coupon taken meanwhile
(by the same customer’s other order) is refused now, the total rises,
and the order is refused with
price_changed(AC-6.14), with the new quote so that the page can say why. A code refused both times leaves the total as shown, so the order goes ahead without it. - Step 4 holds only the coupons the quote applied, after the
stock and before the order is recorded, and the nested
tryblocks free them again if a later step throws.
charge then settles the coupons on the same answer as the stock:
| Gateway answer | Stock | Coupons | Order |
|---|---|---|---|
| approved | sold | used (commit) |
paid |
| total is 0.00, no call | sold | used (commit) |
paid |
| declined | released | unused (release) |
payment failed |
| no answer | stays held | stays held | awaiting payment |
The “no answer” row is AC-6.12: the charge may have gone through, so the coupon must not be free for another order. The retry asks again with the same key, gets the one answer, and commits once.
How this code works: Alice's coupon through a lost answer
From the step 2 demo, using the fake gateway, which is set to lose the first answer:
| Step | SAVE10 for alice |
order-1001 | Gateway calls |
|---|---|---|---|
| quote with SAVE10 and TAKE5: 40.36 | unused | (none) | 0 |
| submit: hold, record, charge, no answer | held | awaiting payment | 1 |
| press again, same key | held | duplicate returned | 1 |
| a new cart with SAVE10 | held: refused | awaiting payment | 1 |
retry_payments: approved |
used | paid | 2 |
| a new cart with SAVE10 again | used: refused | paid | 2 |
The customer was charged 40.36 once, in two calls with the same key, and the coupon was used once.
Coupons: flawed designs and better ones
Section titled “Coupons: flawed designs and better ones”A note on Strategy again: coupons are not a Promotion subclass,
and there is no CouponRule interface either. There are two kinds of
coupon value, fixed by the business, and a std::variant with
std::get covers them with no virtual calls and no heap. If marketing
starts inventing new kinds every month, an interface would start to pay
for itself; that is a change for when it happens.
Testing the change
Section titled “Testing the change”All 29 step 1 tests are kept. Their World gains a coupon book, and the
random test is renamed inv_stock_coupons_and_money_add_up, because it
now checks coupons too. Sixteen tests are added, one or more for each
of AC-6.1 to AC-6.16.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// These tests read coupons and rejected with .at(i), not [i]: if a bug// leaves the list shorter, .at throws, which the test runner reports as a// failure, where [i] would read past the end.
// Codes are trimmed and upper-cased before every lookup, so " save10\t"// and "Save10" find SAVE10; a space inside a code is kept, and a code that// is the same as another once normalised cannot be added.LLD_TEST(ac_6_1_codes_are_normalised_before_lookup) { LLD_CHECK_EQ(normalise_code(" save10\t"), std::string("SAVE10")); LLD_CHECK_EQ(normalise_code("\n Take 3 \r"), std::string("TAKE 3")); LLD_CHECK_EQ(normalise_code(" "), std::string()); World w; LLD_CHECK(w.coupons.find(" Save10 ") != nullptr); LLD_CHECK(w.coupons.find("SAVE 10") == nullptr); LLD_CHECK_THROWS(w.coupons.add({" save10", PercentOff{5}, Money{}, false}), std::invalid_argument); const Quote quote = w.with(cart_of({{mug, 1}}), {" save10 "}); LLD_CHECK_EQ(quote.coupons.size(), std::size_t{1}); LLD_CHECK_EQ(quote.coupons.at(0).code, std::string("SAVE10")); LLD_CHECK_EQ(quote.total, Money{1080});}
// Two amount coupons both apply; a second percentage coupon is refused,// whichever of the two is entered first.LLD_TEST(ac_6_2_amount_coupons_stack_but_only_one_percentage_coupon_applies) { World w; const Cart cart = cart_of({{kettle, 1}}); // 35.00, no promotion applies const Quote amounts = w.with(cart, {"TAKE3", "TAKE1"}); LLD_CHECK_EQ(amounts.coupons.size(), std::size_t{2}); LLD_CHECK_EQ(amounts.total, Money{3100}); LLD_CHECK(amounts.rejected.empty()); const Quote percentages = w.with(cart, {"SAVE20", "SAVE10"}); LLD_CHECK_EQ(percentages.coupons.size(), std::size_t{1}); LLD_CHECK_EQ(percentages.coupons.at(0).code, std::string("SAVE20")); LLD_CHECK_EQ(percentages.total, Money{2800}); LLD_CHECK_EQ(percentages.rejected.size(), std::size_t{1}); LLD_CHECK_EQ(percentages.rejected.at(0).entered, std::string("SAVE10")); LLD_CHECK_EQ(percentages.rejected.at(0).reason, CouponRefusal::one_percentage_only);}
// A third coupon is refused, of either kind; a refused coupon does not// take one of the two places.LLD_TEST(ac_6_3_at_most_two_coupons_apply) { World w; const Cart cart = cart_of({{kettle, 1}}); const Quote three = w.with(cart, {"SAVE10", "TAKE3", "TAKE1"}); LLD_CHECK_EQ(three.coupons.size(), std::size_t{2}); LLD_CHECK_EQ(three.rejected.size(), std::size_t{1}); LLD_CHECK_EQ(three.rejected.at(0).entered, std::string("TAKE1")); LLD_CHECK_EQ(three.rejected.at(0).reason, CouponRefusal::too_many_coupons); const Quote amounts = w.with(cart, {"TAKE3", "TAKE1", "GIFT10"}); LLD_CHECK_EQ(amounts.rejected.size(), std::size_t{1}); LLD_CHECK_EQ(amounts.rejected.at(0).reason, CouponRefusal::too_many_coupons); const Quote after_refusal = w.with(cart, {"NOPE", "TAKE3", "TAKE1"}); LLD_CHECK_EQ(after_refusal.coupons.size(), std::size_t{2}); LLD_CHECK_EQ(after_refusal.rejected.at(0).reason, CouponRefusal::unknown_code);}
// The demo cart is 50.40 after its two promotions. Entered as TAKE3 then// SAVE10, the percentage still goes first: 10% of 50.40 is 5.04, then 3.00,// so 42.36. Amounts first would give 10% of 47.40 = 4.74, so 42.66.LLD_TEST(ac_6_4_promotions_then_the_percentage_coupon_then_amount_coupons) { World w; const Quote quote = w.with(cart_of({{tea, 3}, {mug, 1}, {kettle, 1}}), {"TAKE3", "SAVE10"}); LLD_CHECK_EQ(quote.discounts.size(), std::size_t{2}); LLD_CHECK_EQ(quote.after_promotions, Money{5040}); LLD_CHECK_EQ(quote.coupons.size(), std::size_t{2}); LLD_CHECK_EQ(quote.coupons.at(0).code, std::string("SAVE10")); LLD_CHECK_EQ(quote.coupons.at(0).amount, Money{504}); LLD_CHECK_EQ(quote.coupons.at(1).code, std::string("TAKE3")); LLD_CHECK_EQ(quote.coupons.at(1).amount, dollars(3)); LLD_CHECK_EQ(quote.total, Money{4236}); // Two amount coupons go in the order entered: the second takes what is // left, so the order shows in the amounts. const Quote amounts = w.with(cart_of({{mug, 1}}), {"GIFT10", "TAKE3"}); LLD_CHECK_EQ(amounts.coupons.at(0).amount, dollars(10)); LLD_CHECK_EQ(amounts.coupons.at(1).amount, dollars(2));}
// WELCOME15 and FIRST2 are marked "not with promotions": refused on the// demo cart, where two promotions applied, but fine on a cart where the// promotions exist and take nothing.LLD_TEST(ac_6_5_a_not_with_promotions_coupon_is_refused_if_any_promotion_applied) { World w; // 3 for 2 applies to three teas. const Quote with_promotion = w.with(cart_of({{tea, 3}}), {"WELCOME15", "FIRST2"}); LLD_CHECK_EQ(with_promotion.discounts.size(), std::size_t{1}); LLD_CHECK(with_promotion.coupons.empty()); LLD_CHECK_EQ(with_promotion.rejected.size(), std::size_t{2}); LLD_CHECK_EQ(with_promotion.rejected.at(0).reason, CouponRefusal::not_with_promotions); LLD_CHECK_EQ(with_promotion.rejected.at(1).reason, CouponRefusal::not_with_promotions); LLD_CHECK_EQ(with_promotion.total, Money{900}); const Quote without = w.with(cart_of({{mug, 1}}), {"WELCOME15", "FIRST2"}); LLD_CHECK(without.discounts.empty()); LLD_CHECK_EQ(without.coupons.size(), std::size_t{2}); LLD_CHECK_EQ(without.total, Money{820}); // 12.00 - 1.80 - 2.00}
// TAKE5 needs 30.00 after promotions. Six teas and two spoons are 31.00,// but 22.00 once two teas are free: refused. Exactly 30.00 is enough, and// a percentage coupon applied first does not count against the minimum.LLD_TEST(ac_6_6_a_minimum_spend_is_checked_against_the_total_after_promotions) { World w; const Quote below = w.with(cart_of({{tea, 6}, {spoon, 2}}), {"TAKE5"}); LLD_CHECK_EQ(below.subtotal, Money{3100}); LLD_CHECK_EQ(below.after_promotions, Money{2200}); LLD_CHECK(below.coupons.empty()); LLD_CHECK_EQ(below.rejected.at(0).reason, CouponRefusal::minimum_spend_not_met); LLD_CHECK_EQ(below.rejected.at(0).text, std::string("TAKE5 needs a spend of 30.00 after promotions; this order is 22.00.")); const Quote exactly = w.with(cart_of({{mug, 1}, {spoon, 9}}), {"SAVE10", "TAKE5"}); LLD_CHECK_EQ(exactly.after_promotions, dollars(30)); LLD_CHECK_EQ(exactly.coupons.size(), std::size_t{2}); LLD_CHECK_EQ(exactly.total, Money{2200}); // 30.00 - 3.00 - 5.00; 27.00 after SAVE10 is fine w.catalog.set_price(spoon, Money{199}); // now 29.91: short by 9 cents // A named Quote, not a temporary: LLD_CHECK_EQ binds a reference to // what .at(0) returns, which would dangle once a temporary Quote died. const Quote short_by_9 = w.with(cart_of({{mug, 1}, {spoon, 9}}), {"TAKE5"}); LLD_CHECK_EQ(short_by_9.rejected.at(0).reason, CouponRefusal::minimum_spend_not_met);}
// A percentage coupon rounds to the nearest cent, a half cent up: 15% of// 16.50 is 2.475, so 2.48; 15% of 16.49 is 2.4735, so 2.47. 10% of 0.05 is// half a cent, so 0.01; 10% of 0.04 rounds to 0.00, so that coupon is// refused as taking nothing off, and not used up.LLD_TEST(ac_6_7_a_percentage_coupon_rounds_to_the_nearest_cent_half_up) { World w; const Quote up = w.with(cart_of({{tea, 1}, {mug, 1}}), {"WELCOME15"}); LLD_CHECK_EQ(up.coupons.at(0).amount, Money{248}); LLD_CHECK_EQ(up.total, Money{1402}); w.catalog.set_price(mug, Money{1199}); const Quote down = w.with(cart_of({{tea, 1}, {mug, 1}}), {"WELCOME15"}); // named: see ac_6_6_a LLD_CHECK_EQ(down.coupons.at(0).amount, Money{247}); const Sku sticker("sticker"); w.catalog.add({sticker, "Sticker", Money{5}}); const Quote half_cent = w.with(cart_of({{sticker, 1}}), {"SAVE10"}); LLD_CHECK_EQ(half_cent.coupons.at(0).amount, Money{1}); w.catalog.set_price(sticker, Money{4}); const Quote nothing = w.with(cart_of({{sticker, 1}}), {"SAVE10"}); LLD_CHECK(nothing.coupons.empty()); LLD_CHECK_EQ(nothing.rejected.at(0).reason, CouponRefusal::nothing_to_take_off); LLD_CHECK_EQ(nothing.total, Money{4});}
// GIFT10 on a 4.50 tea takes 4.50, not 10.00, and leaves nothing for// TAKE3, which is refused rather than used up. ALL100 takes everything,// and a coupon it leaves nothing for keeps its place from a third one.// Such an order is paid without a charge, and its coupon is used.LLD_TEST(ac_6_8_coupons_never_take_the_total_below_zero) { World w; const Quote quote = w.with(cart_of({{tea, 1}}), {"GIFT10", "TAKE3"}); LLD_CHECK_EQ(quote.coupons.size(), std::size_t{1}); LLD_CHECK_EQ(quote.coupons.at(0).amount, Money{450}); LLD_CHECK_EQ(quote.total, Money{}); LLD_CHECK_EQ(quote.rejected.at(0).entered, std::string("TAKE3")); LLD_CHECK_EQ(quote.rejected.at(0).reason, CouponRefusal::nothing_to_take_off); const Quote all = w.with(cart_of({{kettle, 1}}), {"ALL100", "TAKE1"}); LLD_CHECK_EQ(all.coupons.at(0).amount, dollars(35)); LLD_CHECK_EQ(all.total, Money{}); LLD_CHECK_EQ(all.rejected.at(0).reason, CouponRefusal::nothing_to_take_off); // A coupon refused in pass 2 keeps its place: TAKE1, refused in pass 1 // as the third, stays refused. Pass 1 refusals are listed first. const Quote kept = w.with(cart_of({{kettle, 1}}), {"ALL100", "TAKE3", "TAKE1"}); LLD_CHECK_EQ(kept.coupons.size(), std::size_t{1}); LLD_CHECK_EQ(kept.rejected.size(), std::size_t{2}); LLD_CHECK_EQ(kept.rejected.at(0).entered, std::string("TAKE1")); LLD_CHECK_EQ(kept.rejected.at(0).reason, CouponRefusal::too_many_coupons); LLD_CHECK_EQ(kept.rejected.at(1).entered, std::string("TAKE3")); LLD_CHECK_EQ(kept.rejected.at(1).reason, CouponRefusal::nothing_to_take_off); Cart cart = cart_of({{tea, 1}}); const SubmitResult result = w.place("k-1", alice, cart, {"GIFT10", "TAKE3"}); LLD_CHECK_EQ(result.order->status(), OrderStatus::paid); LLD_CHECK_EQ(w.gateway.calls(), std::size_t{0}); LLD_CHECK_EQ(w.coupons.use("GIFT10", alice), CouponUse::used); LLD_CHECK_EQ(w.coupons.use("TAKE3", alice), CouponUse::unused);}
// Each refusal keeps the code as typed, a reason, and a sentence, in the// order the codes were entered. An unknown code and a code entered twice// (in another case) are refused; nothing is dropped in silence.LLD_TEST(ac_6_9_every_refused_coupon_is_reported_with_a_reason) { World w; const Quote quote = w.with(cart_of({{kettle, 1}}), {"nope", "take3", " TAKE3 ", ""}); LLD_CHECK_EQ(quote.coupons.size(), std::size_t{1}); LLD_CHECK_EQ(quote.rejected.size(), std::size_t{3}); LLD_CHECK_EQ(quote.rejected.at(0).entered, std::string("nope")); LLD_CHECK_EQ(quote.rejected.at(0).reason, CouponRefusal::unknown_code); LLD_CHECK_EQ(quote.rejected.at(0).text, std::string("There is no coupon NOPE.")); LLD_CHECK_EQ(quote.rejected.at(1).entered, std::string(" TAKE3 ")); LLD_CHECK_EQ(quote.rejected.at(1).reason, CouponRefusal::entered_twice); LLD_CHECK_EQ(quote.rejected.at(2).reason, CouponRefusal::unknown_code); for (const RejectedCoupon& rejected : quote.rejected) LLD_CHECK(!rejected.text.empty()); LLD_CHECK_EQ(to_string(CouponRefusal::held_by_another_order), std::string_view("held by another order"));}
// A paid order marks its coupon used for that customer: the next quote// refuses it as already used. Another customer can still use it.LLD_TEST(ac_6_10_a_coupon_is_used_once_per_customer_when_the_order_is_paid) { World w; Cart cart = cart_of({{kettle, 1}}); const SubmitResult result = w.place("k-1", alice, cart, {"save10"}); LLD_CHECK_EQ(result.order->status(), OrderStatus::paid); LLD_CHECK_EQ(result.order->total(), Money{3150}); LLD_CHECK_EQ(w.gateway.charged(alice), Money{3150}); LLD_CHECK_EQ(w.coupons.use("SAVE10", alice), CouponUse::used); const Quote again = w.with(cart_of({{mug, 1}}), {"SAVE10"}); LLD_CHECK_EQ(again.rejected.at(0).reason, CouponRefusal::already_used); LLD_CHECK_EQ(again.total, dollars(12)); LLD_CHECK_EQ(w.pricer.quote(cart_of({{mug, 1}}), bob, {"SAVE10"}).total, Money{1080}); LLD_CHECK_EQ(w.coupons.use("SAVE10", bob), CouponUse::unused);}
// A declined card fails the order, and its coupons are free again: the// same customer can use them on the next order.LLD_TEST(ac_6_11_a_declined_payment_releases_the_coupon) { World w; w.gateway.decline(alice); Cart cart = cart_of({{kettle, 1}}); const SubmitResult failed = w.place("k-1", alice, cart, {"SAVE10", "TAKE3"}); LLD_CHECK_EQ(failed.order->status(), OrderStatus::payment_failed); LLD_CHECK_EQ(w.coupons.use("SAVE10", alice), CouponUse::unused); LLD_CHECK_EQ(w.coupons.use("TAKE3", alice), CouponUse::unused); LLD_CHECK_EQ(w.with(cart_of({{kettle, 1}}), {"SAVE10", "TAKE3"}).coupons.size(), std::size_t{2});}
// A lost answer leaves the order waiting and its coupon held: a repeat of// the request (same key) returns the same order and holds nothing more;// a new order meanwhile is refused the coupon and placed without it. The// retry pays the first order once, and then the coupon is used.LLD_TEST(ac_6_12_a_lost_answer_holds_the_coupon_and_a_retry_uses_it_once) { for (const bool applied : {false, true}) { World w; Cart cart = cart_of({{kettle, 1}}); w.gateway.fail_next(applied); const SubmitRequest request{RequestKey("k-1"), alice, Money{3150}, {"SAVE10"}}; LLD_CHECK_EQ(w.checkout.submit(request, cart).order->status(), OrderStatus::awaiting_payment); LLD_CHECK_EQ(w.coupons.use("SAVE10", alice), CouponUse::held);
Cart empty; const SubmitResult again = w.checkout.submit(request, empty); LLD_CHECK_EQ(again.status, SubmitStatus::duplicate); LLD_CHECK_EQ(again.order->id().str(), std::string("order-1001")); LLD_CHECK_EQ(w.coupons.use("SAVE10", alice), CouponUse::held);
Cart other = cart_of({{mug, 1}}); const Quote other_quote = w.with(other, {"SAVE10"}); LLD_CHECK_EQ(other_quote.rejected.at(0).reason, CouponRefusal::held_by_another_order); const SubmitResult second = w.place("k-2", alice, other, {"SAVE10"}); LLD_CHECK_EQ(second.order->total(), dollars(12)); // placed without the coupon LLD_CHECK(second.order->quote().coupons.empty());
LLD_CHECK_EQ(w.checkout.retry_payments(), std::size_t{0}); LLD_CHECK_EQ(w.checkout.find(OrderId("order-1001"))->status(), OrderStatus::paid); LLD_CHECK_EQ(w.coupons.use("SAVE10", alice), CouponUse::used); LLD_CHECK_EQ(w.gateway.charged(alice), Money{3150} + dollars(12)); LLD_CHECK_EQ(w.checkout.submit(request, empty).status, SubmitStatus::duplicate); LLD_CHECK_EQ(w.coupons.use("SAVE10", alice), CouponUse::used); }}
// The same key with other coupons is another request, and is refused.LLD_TEST(ac_6_13_the_same_key_with_other_coupons_is_refused) { World w; Cart cart = cart_of({{kettle, 1}}); static_cast<void>(w.place("k-1", alice, cart, {"TAKE3"})); Cart other = cart_of({{kettle, 1}}); const SubmitRequest changed{RequestKey("k-1"), alice, Money{3200}, {"TAKE1"}}; LLD_CHECK_EQ(w.checkout.submit(changed, other).status, SubmitStatus::key_reused); LLD_CHECK_EQ(w.coupons.use("TAKE1", alice), CouponUse::unused);}
// Alice sees SAVE10 applied in two tabs, and orders from the first. The// second tab's total (with SAVE10) no longer matches: it is refused, and// its quote says why.LLD_TEST(ac_6_14_a_coupon_taken_meanwhile_changes_the_total_and_refuses_the_order) { World w; Cart first = cart_of({{kettle, 1}}); Cart second = cart_of({{mug, 1}}); const Money shown = w.with(second, {"SAVE10"}).total; LLD_CHECK_EQ(shown, Money{1080}); static_cast<void>(w.place("k-1", alice, first, {"SAVE10"})); const SubmitResult result = w.checkout.submit({RequestKey("k-2"), alice, shown, {"SAVE10"}}, second); LLD_CHECK_EQ(result.status, SubmitStatus::price_changed); LLD_CHECK_EQ(result.quote.total, dollars(12)); LLD_CHECK_EQ(result.quote.rejected.at(0).reason, CouponRefusal::already_used);}
// Coupons that make no sense are refused when added.LLD_TEST(ac_6_15_a_coupon_that_makes_no_sense_is_refused_when_added) { CouponBook book; LLD_CHECK_THROWS(book.add({" \t", PercentOff{10}, Money{}, false}), std::invalid_argument); LLD_CHECK_THROWS(book.add({"P0", PercentOff{0}, Money{}, false}), std::invalid_argument); LLD_CHECK_THROWS(book.add({"P101", PercentOff{101}, Money{}, false}), std::invalid_argument); LLD_CHECK_THROWS(book.add({"A0", AmountOff{Money{}}, Money{}, false}), std::invalid_argument); LLD_CHECK_THROWS(book.add({"MIN", AmountOff{Money{1}}, Money{-1}, false}), std::invalid_argument); book.add({"P100", PercentOff{100}, Money{}, false}); book.add({"P1", PercentOff{1}, Money{}, false}); LLD_CHECK(book.find("p100") != nullptr); LLD_CHECK(book.find("P0") == nullptr);}
// The book itself: a hold is all or nothing, once per order, and settled// once. A code that is unknown, entered twice, or not free is a bug in// the caller (the Pricer refuses those) and throws, changing nothing.LLD_TEST(ac_6_16_the_coupon_book_holds_all_or_nothing_and_settles_once) { World w; const OrderId order("order-1"); LLD_CHECK_THROWS(w.coupons.reserve(order, alice, {"SAVE10", "NOPE"}), std::logic_error); LLD_CHECK_THROWS(w.coupons.reserve(order, alice, {"SAVE10", "save10"}), std::logic_error); LLD_CHECK_EQ(w.coupons.use("SAVE10", alice), CouponUse::unused); LLD_CHECK_THROWS(w.coupons.commit(order), std::logic_error); // no hold was made w.coupons.reserve(order, alice, {"SAVE10", "TAKE3"}); LLD_CHECK_THROWS(w.coupons.reserve(order, alice, {"TAKE1"}), std::logic_error); LLD_CHECK_THROWS(w.coupons.reserve(OrderId("order-2"), alice, {"TAKE1", "TAKE3"}), std::logic_error); LLD_CHECK_EQ(w.coupons.use("TAKE1", alice), CouponUse::unused); w.coupons.commit(order); LLD_CHECK_EQ(w.coupons.use("SAVE10", alice), CouponUse::used); LLD_CHECK_EQ(w.coupons.use("TAKE3", alice), CouponUse::used); LLD_CHECK_THROWS(w.coupons.commit(order), std::logic_error); LLD_CHECK_THROWS(w.coupons.release(order), std::logic_error); w.coupons.reserve(OrderId("order-3"), alice, {}); // an order with no coupons w.coupons.release(OrderId("order-3")); w.coupons.reserve(OrderId("order-4"), bob, {"save10"}); w.coupons.release(OrderId("order-4")); LLD_CHECK_EQ(w.coupons.use("SAVE10", bob), CouponUse::unused); LLD_CHECK_EQ(w.coupons.use("SAVE10", alice), CouponUse::used);}How this code works: What the coupon tests pin down
The values below are the ones the tests check (the test world’s coupons: SAVE10, SAVE20, WELCOME15 and FIRST2 not with promotions, ALL100, TAKE5 with a 30.00 minimum, TAKE3, TAKE1, GIFT10):
| Test | Cart and codes | Expected |
|---|---|---|
| AC-6.1 | a mug, " save10 " |
SAVE10 applied, total 10.80 |
| AC-6.2 | a kettle, TAKE3 and TAKE1 | both applied, 31.00 |
| AC-6.2 | a kettle, SAVE20 and SAVE10 | SAVE20 only, 28.00; SAVE10 refused, one percentage only |
| AC-6.4 | the demo cart, TAKE3 typed before SAVE10 | SAVE10 takes 5.04 first, then TAKE3 3.00: 42.36, not 42.66 |
| AC-6.5 | three teas (3 for 2 applies), WELCOME15 and FIRST2 | both refused, total 9.00 |
| AC-6.6 | a mug and nine spoons, exactly 30.00, SAVE10 and TAKE5 | both apply, 22.00: exactly the minimum is enough, and SAVE10 taking it to 27.00 does not matter |
| AC-6.7 | WELCOME15 on 16.50, then on 16.49 | 2.48 (2.475 rounds up), then 2.47 (2.4735 rounds down) |
| AC-6.7 | 10% of a 0.05 item, and of a 0.04 item | 0.01, and refused as nothing to take off |
| AC-6.10 | a kettle with save10, paid; then a mug with SAVE10 | paid 31.50; then refused for alice (already used), 12.00; bob still gets it, 10.80 |
The random test runs 3,000 steps with four customers and seven codes:
adding to carts, submitting with random codes (sometimes with a wrong
total), pressing again, changing prices, and losing or declining
payments. After every step it checks the stock piles, as in step 1,
and, for each customer and code, that at most one order holds or used
it and that CouponBook::use says the same as the orders. At the end
it checks that each customer was charged exactly what their paid
orders add up to, and that the run placed more than 100 orders and
more than 30 with coupons, so that a quiet run cannot pass by doing
nothing.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Random carts, coupons, customers, price changes, repeated presses, lost// answers of both kinds, declines, and retries. After every step, no unit// of stock is made or lost, reserved and sold stock match the orders, and// each customer's use of each coupon matches their orders: held by at most// one waiting order, used by at most one paid order, and never both.// At the end, once every answer arrives, each customer was charged// exactly the totals of their paid orders.LLD_TEST(inv_stock_coupons_and_money_add_up) { std::mt19937 random(2026); // pick(n) is a random number from 0 to n - 1. A fixed seed makes each // run the same, so a failure can be repeated. auto pick = [&](int n) { return static_cast<int>(random() % static_cast<unsigned>(n)); }; World w; const std::vector<Sku> skus{tea, mug, kettle, spoon}; std::map<Sku, int> received{{tea, 10}, {mug, 5}, {kettle, 2}, {spoon, 20}}; for (const Sku& sku : skus) { w.inventory.receive(sku, 200); received[sku] += 200; } const std::vector<CustomerId> customers{alice, bob, CustomerId("carol"), CustomerId("dave")}; w.gateway.decline(customers[3]); const std::vector<std::string> codes{"SAVE10", "save20 ", "TAKE3", "TAKE1", "WELCOME15", "TAKE5", "nope"}; const std::vector<std::string> real{"SAVE10", "SAVE20", "TAKE3", "TAKE1", "WELCOME15", "TAKE5"}; std::vector<OrderId> placed; std::vector<SubmitRequest> sent;
for (int step = 0; step < 3000; ++step) { switch (pick(6)) { case 0: case 1: { Cart cart; for (int i = 0; i < 1 + pick(3); ++i) static_cast<void>(cart.add(skus[static_cast<std::size_t>(pick(4))], 1 + pick(4))); std::vector<std::string> entered; for (int i = pick(4); i > 0; --i) entered.push_back(codes[static_cast<std::size_t>(pick(7))]); const CustomerId& customer = customers[static_cast<std::size_t>(pick(4))]; const SubmitRequest request{RequestKey("k-" + std::to_string(step)), customer, pick(8) == 0 ? Money{1} : w.pricer.quote(cart, customer, entered).total, entered}; if (pick(4) == 0) w.gateway.fail_next(pick(2) == 1); const SubmitResult result = w.checkout.submit(request, cart); if (result.status == SubmitStatus::placed) placed.push_back(result.order->id()); sent.push_back(request); break; } case 2: if (!sent.empty()) { // a repeat of an earlier press Cart empty; const SubmitResult result = w.checkout.submit(sent[static_cast<std::size_t>(pick(static_cast<int>(sent.size())))], empty); LLD_CHECK(result.status != SubmitStatus::placed); } break; case 3: w.catalog.set_price(skus[static_cast<std::size_t>(pick(4))], Money{100 * (1 + pick(40))}); break; case 4: if (pick(3) == 0) w.gateway.fail_next(pick(2) == 1); static_cast<void>(w.checkout.retry_payments()); break; case 5: w.gateway.fail_next(pick(2) == 1); break; } // Work out from the orders alone what should be reserved and sold, // and compare with the inventory's own piles. std::map<Sku, int> reserved; std::map<Sku, int> sold; for (const OrderId& id : placed) { const Order* order = w.checkout.find(id); for (const PricedLine& line : order->quote().lines) { if (order->status() == OrderStatus::awaiting_payment) reserved[line.sku] += line.quantity; if (order->status() == OrderStatus::paid) sold[line.sku] += line.quantity; } } for (const Sku& sku : skus) { LLD_CHECK_EQ(w.inventory.available(sku) + w.inventory.reserved(sku) + w.inventory.sold(sku), received[sku]); LLD_CHECK_EQ(w.inventory.reserved(sku), reserved[sku]); LLD_CHECK_EQ(w.inventory.sold(sku), sold[sku]); } // Per customer and code: how many waiting and paid orders applied it. std::map<std::pair<CustomerId, std::string>, std::pair<int, int>> applied; for (const OrderId& id : placed) { const Order* order = w.checkout.find(id); for (const AppliedCoupon& coupon : order->quote().coupons) { auto& [waiting, paid] = applied[{order->customer(), coupon.code}]; if (order->status() == OrderStatus::awaiting_payment) ++waiting; if (order->status() == OrderStatus::paid) ++paid; } } for (const CustomerId& customer : customers) { for (const std::string& code : real) { const auto [waiting, paid] = applied[{customer, code}]; LLD_CHECK(waiting + paid <= 1); // A chained ?: paid wins, then waiting, else unused. const CouponUse expected = paid == 1 ? CouponUse::used : waiting == 1 ? CouponUse::held : CouponUse::unused; LLD_CHECK_EQ(w.coupons.use(code, customer), expected); } } }
w.gateway.fail_next(true); w.gateway.fail_next(false); // a failure set and not used is replaced, not queued // Retry until nothing waits: the planned failure is used by the first // charge, so this ends. while (w.checkout.retry_payments() != 0) { } std::map<CustomerId, Money> paid; for (const OrderId& id : placed) { const Order* order = w.checkout.find(id); if (order->status() == OrderStatus::paid) paid[order->customer()] = paid[order->customer()] + order->total(); } for (const CustomerId& customer : customers) LLD_CHECK_EQ(w.gateway.charged(customer), paid[customer]); LLD_CHECK(placed.size() > 100); std::size_t with_coupons = 0; // the run must really exercise coupons for (const OrderId& id : placed) with_coupons += w.checkout.find(id)->quote().coupons.empty() ? 0U : 1U; LLD_CHECK(with_coupons > 30);}The step 2 demo
Section titled “The step 2 demo”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
const Sku tea("tea-500g");const Sku mug("mug-blue");const Sku kettle("kettle-1l");Catalog catalog;catalog.add({tea, "Tea, 500 g", Money{450}});catalog.add({mug, "Blue mug", dollars(12)});catalog.add({kettle, "Kettle, 1 l", dollars(35)});
Inventory inventory;inventory.receive(tea, 10);inventory.receive(mug, 5);inventory.receive(kettle, 2);
// The shop's coupons. Each member of Coupon in order: the code, what// it takes off, the minimum spend, and "not with promotions".CouponBook coupons;coupons.add({"SAVE10", PercentOff{10}, Money{}, false});coupons.add({"WELCOME15", PercentOff{15}, Money{}, true});coupons.add({"TAKE5", AmountOff{dollars(5)}, dollars(30), false});coupons.add({"TAKE3", AmountOff{dollars(3)}, Money{}, false});coupons.add({"GIFT10", AmountOff{dollars(10)}, Money{}, false});
std::vector<std::unique_ptr<Promotion>> promotions;promotions.push_back(std::make_unique<MultiBuy>("3 for 2 on tea", tea, 3, 2));promotions.push_back(std::make_unique<SpendAndSave>("10% off orders of 50.00 or more", dollars(50), 10));const Pricer pricer(catalog, std::move(promotions), coupons);
FakeGateway gateway;Checkout checkout(pricer, inventory, coupons, gateway);
// Alice types four codes, in any case and with stray spaces.const CustomerId alice("alice");Cart cart;add(cart, tea, 3);add(cart, mug, 1);add(cart, kettle, 1);const std::vector<std::string> codes{" save10 ", "welcome15", "take5", "Take3"};std::cout << "alice's cart with " << codes.size() << " codes:\n";const Quote quote = pricer.quote(cart, alice, codes);show(quote);
gateway.fail_next(true); // the card is charged; the answer is lostconst SubmitRequest place{RequestKey("k-1"), alice, quote.total, codes};std::cout << "place order: " << describe(checkout.submit(place, cart)) << "\n";std::cout << "the button again: " << describe(checkout.submit(place, cart)) << "\n";std::cout << "SAVE10 for alice: " << describe(coupons.use("SAVE10", alice)) << "\n";
// A second order while the first waits: its coupon is not free.Cart more;add(more, mug, 1);std::cout << "alice's next cart, with SAVE10:\n";show(pricer.quote(more, alice, {"SAVE10"}));
std::cout << "retry payments: " << checkout.retry_payments() << " still waiting\n";std::cout << "SAVE10 for alice: " << describe(coupons.use("SAVE10", alice)) << "; alice was charged " << to_string(gateway.charged(alice)) << " in " << gateway.calls() << " calls\n";std::cout << "alice's next cart, with SAVE10 again:\n";show(pricer.quote(more, alice, {"SAVE10"}));
// Bob: no promotion applies, so WELCOME15 is allowed. 15% of 16.50 is// 2.475, which rounds half a cent up to 2.48.const CustomerId bob("bob");gateway.decline(bob);Cart bobs;add(bobs, tea, 1);add(bobs, mug, 1);const std::vector<std::string> bobs_codes{"WELCOME15", "TAKE5"};std::cout << "bob's cart:\n";const Quote bobs_quote = pricer.quote(bobs, bob, bobs_codes);show(bobs_quote);std::cout << "bob: " << describe(checkout.submit({RequestKey("k-2"), bob, bobs_quote.total, bobs_codes}, bobs)) << "\n";std::cout << "WELCOME15 for bob: " << describe(coupons.use("WELCOME15", bob)) << "\n";
// Carol: a 10.00 coupon on 4.50 takes 4.50, and leaves nothing for the// second; the order is paid without a charge.const CustomerId carol("carol");Cart carols;add(carols, tea, 1);const std::vector<std::string> carols_codes{"GIFT10", "TAKE3"};std::cout << "carol's cart:\n";const Quote carols_quote = pricer.quote(carols, carol, carols_codes);show(carols_quote);std::cout << "carol: " << describe(checkout.submit({RequestKey("k-3"), carol, carols_quote.total, carols_codes}, carols)) << "; GIFT10 " << describe(coupons.use("GIFT10", carol)) << ", TAKE3 " << describe(coupons.use("TAKE3", carol)) << "\n";alice's cart with 4 codes: 3 x Tea, 500 g @ 4.50 = 13.50 1 x Blue mug @ 12.00 = 12.00 1 x Kettle, 1 l @ 35.00 = 35.00 subtotal 60.50 3 for 2 on tea: -4.50 10% off orders of 50.00 or more: -5.60 after promotions 50.40 coupon SAVE10: -5.04 coupon TAKE5: -5.00 total 40.36 refused "welcome15" (not with promotions): WELCOME15 cannot be used with a promotion. refused "Take3" (too many coupons): At most 2 coupons can be used per order.place order: placed order-1001, awaiting paymentthe button again: duplicate: order-1001, awaiting paymentSAVE10 for alice: heldalice's next cart, with SAVE10: 1 x Blue mug @ 12.00 = 12.00 subtotal 12.00 after promotions 12.00 total 12.00 refused "SAVE10" (held by another order): SAVE10 is held by your order that is waiting for payment.retry payments: 0 still waitingSAVE10 for alice: used; alice was charged 40.36 in 2 callsalice's next cart, with SAVE10 again: 1 x Blue mug @ 12.00 = 12.00 subtotal 12.00 after promotions 12.00 total 12.00 refused "SAVE10" (already used): You have already used SAVE10.bob's cart: 1 x Tea, 500 g @ 4.50 = 4.50 1 x Blue mug @ 12.00 = 12.00 subtotal 16.50 after promotions 16.50 coupon WELCOME15: -2.48 total 14.02 refused "TAKE5" (minimum spend not met): TAKE5 needs a spend of 30.00 after promotions; this order is 16.50.bob: placed order-1002, payment failed (Your card was declined.)WELCOME15 for bob: unusedcarol's cart: 1 x Tea, 500 g @ 4.50 = 4.50 subtotal 4.50 after promotions 4.50 coupon GIFT10: -4.50 total 0.00 refused "TAKE3" (nothing to take off): TAKE3 would take nothing off this order.carol: placed order-1003, paid; GIFT10 used, TAKE3 unusedHow this code works: Reading the step 2 output
| Who | What happens | Rule shown |
|---|---|---|
| alice | " save10 " and "take5" apply: 50.40, minus 5.04, minus 5.00, is 40.36 |
normalising; percentage first; two in all |
| alice | "welcome15" refused; "Take3" refused as the third |
not with promotions; at most two |
| alice | lost answer: SAVE10 held, so her next cart cannot use it | held by another order |
| alice | the retry is approved: SAVE10 used, 40.36 charged once in two calls | once per customer, used on payment |
| bob | 15% of 16.50 is 2.475, shown as 2.48; TAKE5 needs 30.00, he has 16.50 | rounding; minimum spend after promotions |
| bob | declined: WELCOME15 is unused again | release on decline |
| carol | GIFT10 takes all 4.50; TAKE3 refused, nothing to take off; paid with no charge | never below zero; a coupon not used for nothing |
Presenting it in an interview
Section titled “Presenting it in an interview”A plan for 45 minutes, using the time boxes from The design workflow:
| Time | What to do | What to say |
|---|---|---|
| About 5 min | Ask how money is rounded, when prices are fixed, what a promotion is, when stock is taken, and what the payment provider promises. | “If the provider does not answer, may it still have charged the card?” |
| 5 min | Sketch Cart, Catalog, Pricer with its promotions, Inventory, PaymentGateway, Order, and Checkout. Say who owns what. |
“The cart holds only SKUs and quantities. The price is worked out at checkout, every time.” |
| 10–15 min | Write Money in cents, the Quote, and submit: key, checks, reserve, record, charge. State INV-2 to INV-4. |
“Everything that can be refused comes before the charge, and a refusal leaves nothing behind.” |
| 10 min | Walk the failures: a double press, a declined card, a lost answer, and the retry with the same key. | “The key makes the press safe to repeat; the order id makes the charge safe to repeat.” |
| About 5 min | Take the change: coupons. | “Coupons are pricing rules, in one place, plus a book of who used which, held like the stock.” |
What is usually expected at each level
| Level | Usually expected |
|---|---|
| Junior | A cart of lines; a catalog; a total; one or two promotions; checking stock before an order; a payment interface with a fake; a few tests. |
| Mid-level | All of the above, plus: money in integer cents; prices taken at checkout and compared with what was shown; stock reserved all or nothing and released on failure; order states; refusals as values; promotions in a set order. |
| Senior | All of the above, plus: an idempotency key per press and per charge; a lost answer as a waiting state with a retry; undo on every failure path; coupons held, then used or released, like stock; a random test of the totals. |
These are this site’s judgement of common practice, as on How to approach a case study, not any company’s rubric.
Questions an interviewer may ask
Section titled “Questions an interviewer may ask”- Why not keep the price in the cart? Because the price that matters is the one at payment. The cart keeps quantities; the checkout prices them and compares with the total the customer saw.
- What if two customers buy the last kettle? One request at a time
here (NFR-4), so the first reserves it and the second is told
out_of_stock. With many servers, the reserve becomes one atomic step in the database, and the same rule holds. - What if the customer presses the button twice? The same key
returns the first order (
duplicate). A different request under the same key iskey_reused. - The provider timed out. Charge again? Only with the same key, the order id, so that the provider returns the first answer instead of charging twice. Until then, the order waits, and its stock and coupons stay held.
- Is Strategy worth it for two promotions? Barely. It pays when promotions are added often and each one is a small class with its own tests; with two that never change, a function would do.
- Why does a refused coupon not take one of the two places? Because the customer could then lose a good coupon to a typo.
- Why is the minimum spend after promotions? That is what the customer actually spends. It is a business choice, asked for, and written in one place.
Production limitations
Section titled “Production limitations”- Not thread-safe (NFR-4). Two requests at once could both see the last kettle. A real shop puts the reserve and the coupon hold in one database transaction, or locks per SKU and per customer.
- Everything is in memory. The orders, the stock, the keys, and the coupon book vanish when the process ends. A crash between the charge and recording its answer is not modelled; with a stored order and the same key, a restart could ask the provider again.
- Waiting orders wait for ever. An order with a lost answer holds its stock and its coupons until a retry gets an answer. A real shop gives up after a time, asks the provider for the charge’s status, and either settles or cancels it.
- Keys are kept for ever. A real shop keeps them for a set time, as most providers do.
- No cancellations, refunds, returns, or partial shipments. Each would add order states and give stock and coupons back.
- No tax, shipping, or currencies.
Moneyhas one currency, and tax rounding rules differ by country. - Coupons have no expiry dates, no total use limit, and no guard against guessing. A real shop limits how many codes one customer can try. A total use limit is the Exercise.
- The best combination is not searched. Pass 1 keeps the first coupons that pass, as the team asked.
- The promotions are fixed in code. Marketing cannot add one without a release.
Traceability
Section titled “Traceability”| Requirement | Design element | Code | Tests | Status |
|---|---|---|---|---|
| FR-1 cart | Cart, CartChange, the limits |
step 1 cart.* |
ac_1_1_… to ac_1_5_… |
Tested |
| FR-2 prices | Catalog, Quote, Pricer::quote |
step 1 catalog.*, pricing.* |
ac_2_1_…, ac_2_6_…, ac_3_7_… |
Tested |
| FR-3 promotions | Promotion, MultiBuy, SpendAndSave, the order in Pricer |
step 1 pricing.* |
ac_2_2_… to ac_2_5_…, ac_2_7_… |
Tested |
| FR-4 checkout checks | steps 2 and 3 of submit |
step 1 checkout.cpp |
ac_3_2_…, ac_3_3_…, ac_3_4_… |
Tested |
| FR-5 stock | Inventory::reserve, commit, release |
step 1 inventory.* |
ac_3_1_…, ac_3_3_…, ac_5_2_…, ac_5_3_…, random test |
Tested |
| FR-6 payment | PaymentGateway, Checkout::charge |
step 1 payment.hpp, checkout.cpp |
ac_3_1_…, ac_3_5_…, ac_3_6_… |
Tested |
| FR-7 one order per press | RequestKey, the attempts map, the order id as charge key |
step 1 checkout.* |
ac_4_1_…, ac_4_2_…, ac_4_5_… |
Tested |
| FR-8 lost answers | awaiting_payment, retry_payments |
step 1 checkout.cpp, order.* |
ac_4_3_…, ac_4_4_…, ac_4_6_…, random test |
Tested |
| NFR-1 exact money | Money in cents, percent_of |
step 1 money.hpp |
ac_2_4_… and every total |
Tested |
| NFR-2 testable without a provider | PaymentGateway, FakeGateway |
step 1 payment.hpp, fake_gateway.hpp |
every checkout test | Tested |
| NFR-3 refusals are values | CartChange, SubmitStatus, CouponRefusal |
both steps | every refusal test | Tested |
| NFR-4 not thread-safe | documented on Checkout |
step 1 checkout.hpp |
none: a statement, not a behaviour | Stated |
| NFR-5 ids | Id<Tag> |
step 1 ids.hpp |
compile-time only: mixing ids does not build | Stated |
| FR-9 coupons | Coupon, apply_coupons, CouponBook, the hold in submit and charge |
step 2 coupon*, pricing.cpp, checkout.cpp |
ac_6_1_… to ac_6_16_…, step 2 random test |
Tested |
Exercise
Section titled “Exercise”Exercise: The first 100 orders only
Marketing wants a coupon, LAUNCH20, that only the first 100 orders can use, across all customers, on top of the once-per-customer rule. Start from step 2.
- Which class knows how many orders have used a coupon? What does it need to keep?
- Does an order waiting for payment count as one of the 100? What about a declined one?
- Where is the new refusal decided, and what does a customer see if the last use is taken between their quote and their press?
- What does
CouponBook::reservedo if it is asked for a coupon with no uses left? - Which tests would you add, and what would the random test check?
Show the explained answer
-
The
CouponBook. It already records who holds or used which coupon. It needs the limit on the coupon, and a count per code of the orders that hold or used it. ThePricerasks it, as it asksusetoday.IllustrativeA fragment for explanation; not compiled on its own.
// Illustrative, not compiled: a limit on uses across all customers.struct Coupon {std::string code;CouponValue value;Money minimum_spend;bool not_with_promotions = false;std::optional<int> max_uses; // std::nullopt: no limit};class CouponBook {public:// How many more orders can take the coupon: those holding it and// those that used it both count. std::nullopt: no limit.[[nodiscard]] std::optional<int> uses_left(std::string_view code) const;// ... add, find, use, reserve, commit, release as in step 2 ...private:std::map<std::string, int> taken_; // code -> orders holding or having used it}; -
A waiting order counts; a declined one does not. If only paid orders counted, 100 waiting orders and 20 more could all be paid, and the shop would give 120. So
reserveadds one totaken_,commitleaves it, andreleasetakes one off, which gives the use back to the next customer. A lost answer keeps its use held, as it keeps the coupon held for that customer today. -
In pass 1 of
apply_coupons, next to the once-per-customer check, with a newCouponRefusal, sayall_taken:IllustrativeA fragment for explanation; not compiled on its own.
// Illustrative: in pass 1, after the use(code, customer) checks.// left is set only for a coupon with a limit; *left reads its value.if (const std::optional<int> left = coupons_->uses_left(code); left.has_value() && *left == 0) {refuse(entered, CouponRefusal::all_taken, code + " has been used by as many orders as it allows.");continue;}A use taken between the quote and the press needs no new code in
Checkout:submitprices again, LAUNCH20 is now refused, the total rises, and the order is refused asprice_changedwith the new quote, as in AC-6.14. The customer sees the new total and why. -
It throws
std::logic_error, as it does for a coupon the customer already holds. ThePricerrefused such a coupon a moment earlier, on the same thread, so reachingreservewith it is a bug. The check must come before anything changes, so that a throw leaves the book as it was. -
Tests: the 100th order gets it and the 101st is refused; a declined order gives its use back, and the next customer gets it; a lost answer keeps the use until the retry; the last use taken between quote and submit gives
price_changed. With a limit of 100 on one coupon, the step 2 random test would never reach it, so give one test coupon a small limit, say 3, and check after every step thattaken_for each code equals the number of orders that hold or used it, and never exceeds the limit.
The answer has not been written into the example; the sketches above are illustrative and were not compiled.
Summary
Section titled “Summary”- Keep money in integer cents with one rounding function, so every total and every comparison is exact.
- The cart keeps what and how many; the price is worked out at checkout and compared with what the customer saw.
- Promotions are a small Strategy with a fixed order. It earns its place only if promotions keep changing; say so rather than assume it.
- Put every refusal before the charge, and make each refusal leave nothing behind: check all, then change, then undo on failure.
- Hold, then settle: stock and coupons are held while an order waits, then sold or used on approval, or freed on a decline. A lost answer keeps them held.
- One key per press makes the button safe to press twice; the order id as the charge key makes the retry safe.
- Write stacking rules once, in the pricer, in two passes: decide which coupons are accepted in the order typed, then apply them in a fixed order, so that, for the coupons accepted, the total does not depend on the order they were typed in.