-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckout.py
More file actions
91 lines (71 loc) · 2.91 KB
/
Copy pathcheckout.py
File metadata and controls
91 lines (71 loc) · 2.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""A facade in its natural Python form: one function with good defaults.
The subsystem is a small order-fulfillment flow -- inventory, payment,
shipping, notification -- four calls every checkout caller used to
copy-paste, in the right order, with the right rollback. ``place_order``
is the one-call common case; the subsystem classes stay public for callers
who need the full controls (partial shipments, invoice-only, etc.).
"""
from __future__ import annotations
from dataclasses import dataclass, field
@dataclass
class Warehouse:
stock: dict[str, int] = field(default_factory=dict)
def reserve(self, sku: str, quantity: int) -> None:
if self.stock.get(sku, 0) < quantity:
raise LookupError(f"insufficient stock for {sku}")
self.stock[sku] -= quantity
def release(self, sku: str, quantity: int) -> None:
self.stock[sku] = self.stock.get(sku, 0) + quantity
@dataclass
class PaymentGateway:
charges: list[tuple[str, int]] = field(default_factory=list)
declined_cards: set[str] = field(default_factory=set)
def charge(self, card: str, amount_cents: int) -> str:
if card in self.declined_cards:
raise PermissionError(f"card {card} declined")
self.charges.append((card, amount_cents))
return f"txn-{len(self.charges)}"
@dataclass
class Shipping:
labels: list[str] = field(default_factory=list)
def create_label(self, sku: str, address: str) -> str:
label = f"label-{len(self.labels) + 1}:{sku}->{address}"
self.labels.append(label)
return label
@dataclass
class Notifier:
sent: list[str] = field(default_factory=list)
def confirm(self, address: str, txn: str, label: str) -> None:
self.sent.append(f"to {address}: paid {txn}, ships as {label}")
@dataclass(frozen=True)
class OrderResult:
transaction_id: str
shipping_label: str
def place_order(
warehouse: Warehouse,
gateway: PaymentGateway,
shipping: Shipping,
notifier: Notifier,
*,
sku: str,
quantity: int,
price_cents: int,
card: str,
address: str,
) -> OrderResult:
"""The facade: the whole checkout dance, in the right order, with the
rollback nobody remembers to write at the call site."""
warehouse.reserve(sku, quantity)
try:
txn = gateway.charge(card, price_cents * quantity)
except Exception:
# Any charge failure — declined card or gateway blowup — must hand
# the reservation back; this is the step copy-paste always forgets.
warehouse.release(sku, quantity)
raise
# Honest boundary: a crash below this line leaves the charge captured.
# Real systems make charge/label/notify a saga (compensate on failure)
# or an idempotent retry -- the facade pattern doesn't solve that part.
label = shipping.create_label(sku, address)
notifier.confirm(address, txn, label)
return OrderResult(transaction_id=txn, shipping_label=label)