The cheapest Tern price for a cart, in pence, for checkout (needs from the docs: D1 grams, D2 current endpoint)
diff --git a/shop/shipping.py b/shop/shipping.py
index 5c4358a..4dd6187 100644
--- a/shop/shipping.py
+++ b/shop/shipping.py
@@ -1,13 +1,24 @@
"""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", "/v1/quotes", {
+ "from_postcode": settings.WAREHOUSE_POSTCODE,
+ "to_postcode": postcode,
+ "weight": cart.total_weight_kg(),
+ })
+ if status != 200:
+ raise RuntimeError(f"Tern quote failed ({status}): {body}")
+ prices = [q["amount"] for q in body.get("quotes", []) if q.get("currency") == "GBP"]
+ if not prices:
+ raise RuntimeError("Tern offered no GBP quotes for this parcel")
+ return min(prices)
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..a1d3e2f
--- /dev/null
+++ b/tests/test_shipping.py
@@ -0,0 +1,28 @@
+import pytest
+
+from shop import shipping
+from shop.cart import Cart, Item
+
+TEA = Item("TEA1", "Assam", 500, 0.25)
+
+
+def test_quote_at_checkout_picks_cheapest(monkeypatch):
+ calls = []
+
+ def fake(method, path, body=None, **kw):
+ calls.append((method, path, body))
+ return 200, {"quotes": [{"amount": 1295, "currency": "GBP"}, {"amount": 495, "currency": "GBP"},
+ {"amount": 695, "currency": "GBP"}]}
+
+ monkeypatch.setattr(shipping.tern, "call", fake)
+ cart = Cart()
+ cart.add(TEA, 4)
+ assert shipping.quote_at_checkout(cart, "SW1A 1AA") == 495
+ assert calls == [("POST", "/v1/quotes",
+ {"from_postcode": "EH6 6QT", "to_postcode": "SW1A 1AA", "weight": 1.0})]
+
+
+def test_quote_at_checkout_error(monkeypatch):
+ monkeypatch.setattr(shipping.tern, "call", lambda *a, **k: (200 and 422, {"error": "too_heavy"}))
+ with pytest.raises(RuntimeError):
+ shipping.quote_at_checkout(Cart(), "SW1A 1AA")