Every Tern service for a cart, cheapest first (needs from the docs: D1 grams, D2 current endpoint)
diff --git a/shop/shipping.py b/shop/shipping.py
index 5c4358a..c3f2743 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 settings, tern
from shop.cart import Cart
from shop.orders import Order
@@ -13,7 +14,16 @@ def quote_at_checkout(cart: Cart, postcode: str) -> int:
def quote_options(cart: Cart, postcode: str) -> list[tuple[str, int, int]]:
"""Every service Tern offers for this cart and postcode, as (service, price in pence, days to deliver),
cheapest first."""
- raise NotImplementedError
+ # v1 is deprecated (sunset 2027-06-01). v2 takes the weight in grams, not kilograms.
+ status, body = tern.call("POST", "/v2/quotes", {
+ "from_postcode": settings.WAREHOUSE_POSTCODE,
+ "to_postcode": postcode,
+ "weight": round(cart.total_weight_kg() * 1000),
+ })
+ if status != 200:
+ raise RuntimeError(f"Tern quote failed ({status}): {body}")
+ options = [(q["service"], q["amount"], q["eta_days"]) for q in body["quotes"]]
+ return sorted(options, key=lambda o: (o[1], o[2]))
def book(order: Order, service: str) -> str:
diff --git a/tests/test_shipping.py b/tests/test_shipping.py
new file mode 100644
index 0000000..c255537
--- /dev/null
+++ b/tests/test_shipping.py
@@ -0,0 +1,20 @@
+from shop import tern
+from shop.cart import Cart, Item
+from shop.shipping import quote_options
+
+
+def test_quote_options_sorted_and_weight_in_grams(monkeypatch):
+ seen = {}
+
+ def fake(method, path, body=None, **kw):
+ seen.update(path=path, body=body)
+ return 200, {"quotes": [
+ {"service": "express", "amount": 795, "currency": "GBP", "eta_days": 1},
+ {"service": "economy", "amount": 295, "currency": "GBP", "eta_days": 5},
+ ]}
+
+ monkeypatch.setattr(tern, "call", fake)
+ cart = Cart()
+ cart.add(Item("a", "Tea", 500, 0.6), 2)
+ assert quote_options(cart, "SW1A 1AA") == [("economy", 295, 5), ("express", 795, 1)]
+ assert seen["path"] == "/v2/quotes" and seen["body"]["weight"] == 1200