Book an order with Tern, safe to retry (needs from the docs: D3 idempotency)
diff --git a/shop/shipping.py b/shop/shipping.py
index 5c4358a..54d6222 100644
--- a/shop/shipping.py
+++ b/shop/shipping.py
@@ -1,9 +1,13 @@
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
+import http.client
from datetime import date
+from shop import settings, tern
from shop.cart import Cart
from shop.orders import Order
+_BOOK_ATTEMPTS = 5
+
def quote_at_checkout(cart: Cart, postcode: str) -> int:
"""The cheapest price Tern offers to ship this cart from the warehouse to postcode, in pence."""
@@ -18,7 +22,28 @@ 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
+ 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,
+ }
+ # The same key on every attempt makes Tern return the shipment it already booked instead of booking again.
+ headers = {"Idempotency-Key": f"order-{order.id}"}
+ for attempt in range(_BOOK_ATTEMPTS):
+ last = attempt == _BOOK_ATTEMPTS - 1
+ try:
+ status, shipment = tern.call("POST", "/v2/shipments", body, headers=headers)
+ except (OSError, http.client.HTTPException, ValueError):
+ if last:
+ raise
+ continue
+ if status >= 500 and not last:
+ continue
+ if status >= 300:
+ raise RuntimeError(f"Tern refused the booking for order {order.id}: {status} {shipment}")
+ return shipment["id"]
def shipments_since(day: date) -> list[dict]: