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..dfd0590 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,15 @@ 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
+ 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.get('error', 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..7b239ae
--- /dev/null
+++ b/tests/test_shipping.py
@@ -0,0 +1,21 @@
+from shop import shipping, tern
+from shop.cart import Cart, Item
+
+
+def test_quote_options_sorted_and_in_grams(monkeypatch):
+ sent = {}
+
+ def fake(method, path, body=None, **kw):
+ sent.update(path=path, body=body)
+ return 200, {"quotes": [
+ {"id": "a", "service": "express", "amount": 1295, "currency": "GBP", "eta_days": 1},
+ {"id": "b", "service": "economy", "amount": 495, "currency": "GBP", "eta_days": 5},
+ {"id": "c", "service": "standard", "amount": 695, "currency": "GBP", "eta_days": 3},
+ ]}
+
+ monkeypatch.setattr(tern, "call", fake)
+ cart = Cart()
+ cart.add(Item("x", "Tea", 500, 0.4), 3)
+ assert shipping.quote_options(cart, "M1 1AE") == [
+ ("economy", 495, 5), ("standard", 695, 3), ("express", 1295, 1)]
+ assert sent["path"] == "/v2/quotes" and sent["body"]["weight"] == 1200