Cancel a shipment unless it is too late (needs from the docs: cancel path, 409 once collected)
diff --git a/shop/shipping.py b/shop/shipping.py
index 5c4358a..6a3762b 100644
--- a/shop/shipping.py
+++ b/shop/shipping.py
@@ -1,6 +1,7 @@
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
from datetime import date
+from shop import tern
from shop.cart import Cart
from shop.orders import Order
@@ -33,4 +34,11 @@ 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 not order.shipment_id:
+ raise ValueError(f"order {order.id} has no Tern shipment to cancel")
+ status, body = tern.call("POST", f"/v2/shipments/{order.shipment_id}/cancel")
+ if status == 200:
+ return True
+ if status == 409 and body.get("error") == "conflict":
+ return False
+ raise RuntimeError(f"Tern cancel failed for {order.shipment_id}: {status} {body}")