stage 6 of 6 · try of restructure

cancel-before-pickup

right

Cancel a shipment unless it is too late (needs from the docs: cancel path, 409 once collected)

Made
28 Nov 2026, 20:52 UTC
Model
claude-sonnet-5-5
Steps
6
Tool calls
4
Friction
2 flagged steps
Tokens read
129k
Time
16s
Cost
$0.040
Address
tern-docs/try/20261128-2029-u6xp/cancel-before-pickup
1quote-at-checkoutright2quote-optionsright3book-shipmentright4sync-shipmentsright5order-statusright6cancel-before-pickupright
diff --git a/shop/shipping.py b/shop/shipping.py
index 5c4358a..4c3dd12 100644
--- a/shop/shipping.py
+++ b/shop/shipping.py
@@ -3,6 +3,7 @@ from datetime import date
 
 from shop.cart import Cart
 from shop.orders import Order
+from shop.tern import call
 
 
 def quote_at_checkout(cart: Cart, postcode: str) -> int:
@@ -33,4 +34,15 @@ def order_status(shipment_id: str) -> str:
 
 def cancel(order: Order) -> bool:
     """Cancel the order's Tern shipment. True if Tern cancelled it; False if it is too late to cancel."""
-    raise NotImplementedError
+    if order.shipment_id is None:
+        return True  # never booked with Tern, so there is nothing to cancel
+    path = f"/v2/shipments/{order.shipment_id}"
+    status, body = call("POST", path + "/cancel")
+    if status == 200:
+        return True
+    if status == 409:
+        # Tern also answers 409 for a shipment that is already cancelled; that counts as cancelled.
+        status, body = call("GET", path)
+        if status == 200:
+            return body.get("status") == "cancelled"
+    raise RuntimeError(f"Tern cancel failed for {order.shipment_id}: {status} {body}")
Previous stage: 5. order-statusLast stage of this try