stage 3 of 6 · try of restructure

book-shipment

right

Book an order with Tern, safe to retry (needs from the docs: D3 idempotency)

Made
28 Nov 2026, 20:57 UTC
Model
claude-sonnet-5-5
Steps
6
Tool calls
4
Friction
1 flagged step
Tokens read
131k
Time
20s
Cost
$0.039
Address
tern-docs/try/20261128-2029-b08p/book-shipment
1quote-at-checkoutright2quote-optionsright3book-shipmentright4sync-shipmentsright5order-statusright6cancel-before-pickupright
diff --git a/shop/shipping.py b/shop/shipping.py
index 5c4358a..a2d1c31 100644
--- a/shop/shipping.py
+++ b/shop/shipping.py
@@ -1,8 +1,14 @@
 """Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
+import http.client
+import time
 from datetime import date
 
+from shop import settings, tern
+
 from shop.cart import Cart
-from shop.orders import Order
+from shop.orders import PROCESSING, Order
+
+BOOK_ATTEMPTS = 5
 
 
 def quote_at_checkout(cart: Cart, postcode: str) -> int:
@@ -17,8 +23,36 @@ def quote_options(cart: Cart, postcode: str) -> list[tuple[str, int, int]]:
 
 
 def book(order: Order, service: str) -> str:
-    """Book the order's parcel with Tern on the given service and return Tern's shipment id."""
-    raise NotImplementedError
+    """Book the order's parcel with Tern on the given service and return Tern's shipment id.
+
+    The order id is sent as Tern's Idempotency-Key, so retrying after a dropped connection
+    returns the shipment already booked instead of booking another."""
+    if order.shipment_id:
+        return order.shipment_id
+    body = {
+        "service": service,
+        "from_postcode": settings.WAREHOUSE_POSTCODE,
+        "to_postcode": order.postcode,
+        "weight": round(order.cart.total_weight_kg() * 1000),  # Tern takes grams
+        "reference": order.id,
+    }
+    headers = {"Idempotency-Key": f"order-{order.id}"}
+    for attempt in range(BOOK_ATTEMPTS):
+        try:
+            status, data = tern.call("POST", "/v2/shipments", body=body, headers=headers)
+        except OSError:  # includes URLError, timeouts and dropped connections
+            status, data = None, {}
+        except http.client.HTTPException:
+            status, data = None, {}
+        if status is not None and status < 500:
+            if status >= 400:
+                raise RuntimeError(f"Tern refused the booking ({status}): {data}")
+            order.shipment_id = data["id"]
+            order.status = PROCESSING
+            return order.shipment_id
+        if attempt < BOOK_ATTEMPTS - 1:
+            time.sleep(0.2 * 2 ** attempt)
+    raise RuntimeError("Could not book with Tern: no answer after retries")
 
 
 def shipments_since(day: date) -> list[dict]: