Keep an Order Log

Step 4: Keep an Order Log

A good facade can also become the natural home for cross-cutting bookkeeping, because every order already flows through it. Here the facade keeps a running log of everything it has fulfilled, in self.orders (already initialized to an empty list in the constructor).

This step adds no new method. You extend place_order one more time. Right before returning the successful result, append a record of the order to self.orders:

  • Store a dict with keys item, qty, amount, and tracking.
  • Only successful orders are logged. An out-of-stock or declined order must not add anything to the list.

Because the log lives on the facade instance, callers can inspect the full history without ever touching a subsystem.

Hints
Starter code
class Inventory:
    def __init__(self, stock):
        self.stock = dict(stock)

    def reserve(self, item, qty):
        if self.stock.get(item, 0) >= qty:
            self.stock[item] -= qty
            return True
        return False

    def release(self, item, qty):
        self.stock[item] = self.stock.get(item, 0) + qty


class Payment:
    def __init__(self, balance):
        self.balance = balance

    def charge(self, amount):
        if amount <= self.balance:
            self.balance -= amount
            return True
        return False


class Shipping:
    def schedule(self, item):
        return "trk-" + item


class CheckoutFacade:
    def __init__(self, inventory, payment, shipping):
        self.inventory = inventory
        self.payment = payment
        self.shipping = shipping
        self.orders = []

    def place_order(self, item, qty, amount):
        if not self.inventory.reserve(item, qty):
            return {"ok": False, "reason": "out_of_stock"}
        if not self.payment.charge(amount):
            self.inventory.release(item, qty)
            return {"ok": False, "reason": "payment_declined"}
        tracking = self.shipping.schedule(item)
        # TODO: record this successful order in self.orders as a dict with keys
        # item, qty, amount, and tracking before returning.
        return {"ok": True, "tracking": tracking}
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.