stage 1 of 6 · try of restructure

quote-at-checkout

right

The cheapest Tern price for a cart, in pence, for checkout (needs from the docs: D1 grams, D2 current endpoint)

Made
28 Nov 2026, 21:02 UTC
Model
claude-sonnet-5-5
Steps
6
Tool calls
4
Friction
2 flagged steps
Tokens read
129k
Time
15s
Cost
$0.035
Address
tern-docs/try/20261128-2029-euxb/quote-at-checkout
1quote-at-checkoutright2quote-optionsright3book-shipmentright4sync-shipmentsright5order-statusright6cancel-before-pickupright
diff --git a/shop/shipping.py b/shop/shipping.py
index 5c4358a..12649d7 100644
--- a/shop/shipping.py
+++ b/shop/shipping.py
@@ -1,13 +1,21 @@
 """Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
 from datetime import date
 
+from shop import settings, tern
 from shop.cart import Cart
 from shop.orders import Order
 
 
 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."""
-    raise NotImplementedError
+    status, body = tern.call("POST", "/v2/quotes", body={
+        "from_postcode": settings.WAREHOUSE_POSTCODE,
+        "to_postcode": postcode,
+        "weight": round(cart.total_weight_kg() * 1000),  # Tern wants grams
+    })
+    if status != 200:
+        raise RuntimeError(f"Tern quote failed ({status}): {body.get('error', body)}")
+    return min(q["amount"] for q in body["quotes"])  # pence; quotes come in no particular order
 
 
 def quote_options(cart: Cart, postcode: str) -> list[tuple[str, int, int]]:
diff --git a/tests/test_shipping.py b/tests/test_shipping.py
new file mode 100644
index 0000000..f2e7e99
--- /dev/null
+++ b/tests/test_shipping.py
@@ -0,0 +1,25 @@
+from unittest import mock
+
+import pytest
+
+from shop import shipping
+from shop.cart import Cart, Item
+
+
+def _cart():
+    cart = Cart()
+    cart.add(Item("T1", "Tea", 500, 0.6), 2)
+    return cart
+
+
+def test_cheapest_quote_in_pence_and_grams():
+    quotes = [{"amount": 1295}, {"amount": 495}, {"amount": 695}]
+    with mock.patch("shop.tern.call", return_value=(200, {"quotes": quotes})) as call:
+        assert shipping.quote_at_checkout(_cart(), "M1 1AE") == 495
+    assert call.call_args.kwargs["body"] == {"from_postcode": "EH6 6QT", "to_postcode": "M1 1AE", "weight": 1200}
+
+
+def test_error_raises():
+    with mock.patch("shop.tern.call", return_value=(422, {"error": "too_heavy"})):
+        with pytest.raises(RuntimeError, match="too_heavy"):
+            shipping.quote_at_checkout(_cart(), "M1 1AE")