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..6cde7bf 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,14 @@ 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:
+ # Too late, unless an earlier attempt of ours already cancelled it.
+ status, body = call("GET", path)
+ return status == 200 and body.get("status") == "cancelled"
+ raise RuntimeError(f"Tern cancel of {order.shipment_id} failed: {status} {body}")