stage 5 of 6 · try of as-shipped

order-status

right

The shop's order status from Tern's (needs from the docs: D5 held)

Made
28 Nov 2026, 20:29 UTC
Model
claude-sonnet-5-5
Steps
6
Tool calls
4
Friction
2 flagged steps
Tokens read
130k
Time
16s
Cost
$0.053
Address
tern-docs/try/20261128-2029-yseu/order-status
1quote-at-checkoutright2quote-optionsright3book-shipmentright4sync-shipmentsright5order-statusright6cancel-before-pickupright
TranscriptPromptFilesOpen flagged steps
1
user
This is the backend of Larkspur Tea, a small online tea shop. We ship with Tern, a parcel carrier. Tern's API documentation is at http://loc…
This is the backend of Larkspur Tea, a small online tea shop. We ship with Tern, a parcel carrier. Tern's API documentation is at http://localhost:8080/ and Tern's sandbox API is running at http://localhost:8081 (the test key is already in `shop/settings.py`). Implement `order_status` in `shop/shipping.py`: given a Tern shipment id, return the status our order page should show the customer, one of the constants in `shop/orders.py`. Keep the shop's existing tests passing; add your own if you like.
2
agent · Bash
cd /app; git ls-files; cat shop/shipping.py shop/orders.py shop/settings.py; curl -s localhost:8080/
.gitignore
cd /app; git ls-files; cat shop/shipping.py shop/orders.py shop/settings.py; curl -s localhost:8080/
.gitignore
README.md
pytest.ini
shop/__init__.py
shop/cart.py
shop/orders.py
shop/settings.py
shop/shipping.py
shop/tern.py
tests/__init__.py
tests/test_cart.py
tests/test_orders.py
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
from datetime import date

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


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


def book(order: Order, service: str) -> str:
    """Book the order's parcel with Tern on the given service and return Tern's shipment id."""
    raise NotImplementedError


def shipments_since(day: date) -> list[dict]:
    """Every Tern shipment created on or after day, as Tern describes them."""
    raise NotImplementedError


def order_status(shipment_id: str) -> str:
    """The shop's status (one of shop.orders.STATUSES) for the order whose Tern shipment this is."""
    raise NotImplementedError


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
from dataclasses import dataclass

from shop.cart import Cart

# The statuses a customer sees on their order page.
PAID = "paid"                # paid for, not yet booked with the carrier
PROCESSING = "processing"    # booked with the carrier, waiting to be collected
SHIPPED = "shipped"          # with the carrier and on its way
DELIVERED = "delivered"      # arrived
PROBLEM = "problem"          # something went wrong: a person needs to look at it
CANCELLED = "cancelled"      # cancelled before it left us

STATUSES = (PAID, PROCESSING, SHIPPED, DELIVERED, PROBLEM, CANCELLED)


@dataclass
class Order:
    id: str
    cart: Cart
    postcode: str
    status: str = PAID
    shipment_id: str | None = None
import os

TERN_API_URL = os.environ.get("TERN_API_URL", "http://localhost:8081")
TERN_API_KEY = os.environ.get("TERN_API_KEY", "tern_test_larkspur")

# Every parcel leaves from the warehouse.
WAREHOUSE_POSTCODE = "EH6 6QT"
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Tern API documentation · Tern API</title></head>
<body>
<header><p><strong>Tern API</strong> · <a href="/">Home</a> · <a href="/quickstart">Quickstart</a> · <a href="/reference/quotes">Quotes</a> · <a href="/reference/shipments">Shipments</a> · <a href="/reference/statuses">Statuses</a> · <a href="/changelog">Changelog</a></p></header>
<main>
<h1>Tern API documentation</h1>
<p>Tern is a parcel carrier for small shops in the UK. The Tern API quotes, books, tracks and cancels parcels.</p>
<ul>
<li><a href="/quickstart">Quickstart</a>: your first quote in five minutes.</li>
<li><a href="/reference/quotes">Quotes</a>, <a href="/reference/shipments">Shipments</a> and <a href="/reference/statuses">Statuses</a>: the reference.</li>
<li><a href="/changelog">Changelog</a>: what changed, and what is retired.</li>
</ul>
</main>
</body>
</html>

[stdout]
.gitignore
README.md
pytest.ini
shop/__init__.py
shop/cart.py
shop/orders.py
shop/settings.py
shop/shipping.py
shop/tern.py
tests/__init__.py
tests/test_cart.py
tests/test_orders.py
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
from datetime import date

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


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


def book(order: Order, service: str) -> str:
    """Book the order's parcel with Tern on the given service and return Tern's shipment id."""
    raise NotImplementedError


def shipments_since(day: date) -> list[dict]:
    """Every Tern shipment created on or after day, as Tern describes them."""
    raise NotImplementedError


def order_status(shipment_id: str) -> str:
    """The shop's status (one of shop.orders.STATUSES) for the order whose Tern shipment this is."""
    raise NotImplementedError


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
from dataclasses import dataclass

from shop.cart import Cart

# The statuses a customer sees on their order page.
PAID = "paid"                # paid for, not yet booked with the carrier
PROCESSING = "processing"    # booked with the carrier, waiting to be collected
SHIPPED = "shipped"          # with the carrier and on its way
DELIVERED = "delivered"      # arrived
PROBLEM = "problem"          # something went wrong: a person needs to look at it
CANCELLED = "cancelled"      # cancelled before it left us

STATUSES = (PAID, PROCESSING, SHIPPED, DELIVERED, PROBLEM, CANCELLED)


@dataclass
class Order:
    id: str
    cart: Cart
    postcode: str
    status: str = PAID
    shipment_id: str | None = None
import os

TERN_API_URL = os.environ.get("TERN_API_URL", "http://localhost:8081")
TERN_API_KEY = os.environ.get("TERN_API_KEY", "tern_test_larkspur")

# Every parcel leaves from the warehouse.
WAREHOUSE_POSTCODE = "EH6 6QT"
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Tern API documentation · Tern API</title></head>
<body>
<header><p><strong>Tern API</strong> · <a href="/">Home</a> · <a href="/quickstart">Quickstart</a> · <a href="/reference/quotes">Quotes</a> · <a href="/reference/shipments">Shipments</a> · <a href="/reference/statuses">Statuses</a> · <a href="/changelog">Changelog</a></p></header>
<main>
<h1>Tern API documentation</h1>
<p>Tern is a parcel carrier for small shops in the UK. The Tern API quotes, books, tracks and cancels parcels.</p>
<ul>
<li><a href="/quickstart">Quickstart</a>: your first quote in five minutes.</li>
<li><a href="/reference/quotes">Quotes</a>, <a href="/reference/shipments">Shipments</a> and <a href="/reference/statuses">Statuses</a>: the reference.</li>
<li><a href="/changelog">Changelog</a>: what changed, and what is retired.</li>
</ul>
</main>
</body>
</html>
[metadata] {"noOutputExpected": false}
3
agent · Bash
cd /app; cat shop/tern.py; for p in reference/statuses reference/shipments changelog; do echo "=== $p"; curl -s localhost:8080/$p | sed 's/<…
"""A thin client for Tern's API: the key, JSON in and out. Which paths and fields to use is up to the caller."""
cd /app; cat shop/tern.py; for p in reference/statuses reference/shipments changelog; do echo "=== $p"; curl -s localhost:8080/$p | sed 's/<[^>]*>/ /g' | grep -v '^\s*$'; done
"""A thin client for Tern's API: the key, JSON in and out. Which paths and fields to use is up to the caller."""
import json
import urllib.error
import urllib.parse
import urllib.request

from shop import settings


def call(method: str, path: str, body: dict | None = None, params: dict | None = None,
         headers: dict | None = None, timeout: float = 10) -> tuple[int, dict]:
    """One request to Tern. Returns (HTTP status, decoded JSON body); an error status is returned, not raised.
    A connection that fails or drops raises, as urllib does."""
    url = settings.TERN_API_URL.rstrip("/") + path
    if params:
        url += "?" + urllib.parse.urlencode(params)
    data = json.dumps(body).encode() if body is not None else None
    request = urllib.request.Request(url, data=data, method=method)
    request.add_header("Authorization", f"Bearer {settings.TERN_API_KEY}")
    request.add_header("Accept", "application/json")
    if data is not None:
        request.add_header("Content-Type", "application/json")
    for name, value in (headers or {}).items():
        request.add_header(name, value)
    try:
        with urllib.request.urlopen(request, timeout=timeout) as response:
            return response.status, json.loads(response.read() or b"{}")
    except urllib.error.HTTPError as e:
        raw = e.read()
        return e.code, json.loads(raw) if raw else {}
=== reference/statuses
   Statuses · Tern API  
   Tern API  ·  Home  ·  Quickstart  ·  Quotes  ·  Shipments  ·  Statuses  ·  Changelog   
 Statuses 
 A shipment's  status  is one of these. 
  Status  Meaning  
   booked   Booked; not yet collected. It can still be cancelled.  
   collected   Collected by a Tern driver. It is on its way.  
   in_transit   Moving through Tern's network.  
   held   At customs, waiting for clearance. This is normal for parcels to Northern Ireland, the
Channel Islands and abroad, clears within two working days, and needs nothing from you: the parcel is still on its
way.  
   delivered   Delivered.  
   returned   Could not be delivered and is coming back to you. Contact the customer.  
   cancelled   Cancelled before collection.  
=== reference/shipments
   Shipments · Tern API  
   Tern API  ·  Home  ·  Quickstart  ·  Quotes  ·  Shipments  ·  Statuses  ·  Changelog   
 Shipments 
 POST /v2/shipments 
 Book a parcel. Fields:  service ,  from_postcode ,  to_postcode ,
 weight  (grams) and  reference , your own reference for the order. The response is the
shipment, status  booked , with its  id . 
 Retrying safely 
 Send an  Idempotency-Key  header with a value unique to the booking, such as your order reference.
If the connection drops before you see the answer, send the same request with the same key: Tern returns the
shipment it already booked rather than booking another.  Without the header, every request books a new
parcel.  
 Idempotency-Key: order-LT-5123 
 GET /v2/shipments 
 Your shipments, oldest first, twenty to a page. Parameters: 
   created_since   A date,  YYYY-MM-DD : only shipments created on or after it.  
   cursor   The  next_cursor  from the previous page.  
 The response holds  shipments  and  next_cursor , which is  null  on the last
page. Keep the same  created_since  when you follow a cursor. 
 GET /v2/shipments/{id} 
 One shipment:  id ,  reference ,  service ,  status  (see
 Statuses ) and  created_at . 
 POST /v2/shipments/{id}/cancel 
 Cancel a shipment that has not been collected. The response is the shipment, status  cancelled .
Once the parcel is collected it can no longer be cancelled: the answer is  409  with
 "error": "conflict" . 
=== changelog
   Changelog · Tern API  
   Tern API  ·  Home  ·  Quickstart  ·  Quotes  ·  Shipments  ·  Statuses  ·  Changelog   
 Changelog 
 2026-06-01: v1 retired 
  /v1/quotes  is retired and will be removed on 2027-06-01. It answers with a
 Deprecation  header until then. Use  /v2/quotes , which takes  weight  in grams;
v1 took kilograms. 
 2026-03-10: idempotent bookings 
  POST /v2/shipments  accepts an  Idempotency-Key  header.

[stdout]
"""A thin client for Tern's API: the key, JSON in and out. Which paths and fields to use is up to the caller."""
import json
import urllib.error
import urllib.parse
import urllib.request

from shop import settings


def call(method: str, path: str, body: dict | None = None, params: dict | None = None,
         headers: dict | None = None, timeout: float = 10) -> tuple[int, dict]:
    """One request to Tern. Returns (HTTP status, decoded JSON body); an error status is returned, not raised.
    A connection that fails or drops raises, as urllib does."""
    url = settings.TERN_API_URL.rstrip("/") + path
    if params:
        url += "?" + urllib.parse.urlencode(params)
    data = json.dumps(body).encode() if body is not None else None
    request = urllib.request.Request(url, data=data, method=method)
    request.add_header("Authorization", f"Bearer {settings.TERN_API_KEY}")
    request.add_header("Accept", "application/json")
    if data is not None:
        request.add_header("Content-Type", "application/json")
    for name, value in (headers or {}).items():
        request.add_header(name, value)
    try:
        with urllib.request.urlopen(request, timeout=timeout) as response:
            return response.status, json.loads(response.read() or b"{}")
    except urllib.error.HTTPError as e:
        raw = e.read()
        return e.code, json.loads(raw) if raw else {}
=== reference/statuses
   Statuses · Tern API  
   Tern API  ·  Home  ·  Quickstart  ·  Quotes  ·  Shipments  ·  Statuses  ·  Changelog   
 Statuses 
 A shipment's  status  is one of these. 
  Status  Meaning  
   booked   Booked; not yet collected. It can still be cancelled.  
   collected   Collected by a Tern driver. It is on its way.  
   in_transit   Moving through Tern's network.  
   held   At customs, waiting for clearance. This is normal for parcels to Northern Ireland, the
Channel Islands and abroad, clears within two working days, and needs nothing from you: the parcel is still on its
way.  
   delivered   Delivered.  
   returned   Could not be delivered and is coming back to you. Contact the customer.  
   cancelled   Cancelled before collection.  
=== reference/shipments
   Shipments · Tern API  
   Tern API  ·  Home  ·  Quickstart  ·  Quotes  ·  Shipments  ·  Statuses  ·  Changelog   
 Shipments 
 POST /v2/shipments 
 Book a parcel. Fields:  service ,  from_postcode ,  to_postcode ,
 weight  (grams) and  reference , your own reference for the order. The response is the
shipment, status  booked , with its  id . 
 Retrying safely 
 Send an  Idempotency-Key  header with a value unique to the booking, such as your order reference.
If the connection drops before you see the answer, send the same request with the same key: Tern returns the
shipment it already booked rather than booking another.  Without the header, every request books a new
parcel.  
 Idempotency-Key: order-LT-5123 
 GET /v2/shipments 
 Your shipments, oldest first, twenty to a page. Parameters: 
   created_since   A date,  YYYY-MM-DD : only shipments created on or after it.  
   cursor   The  next_cursor  from the previous page.  
 The response holds  shipments  and  next_cursor , which is  null  on the last
page. Keep the same  created_since  when you follow a cursor. 
 GET /v2/shipments/{id} 
 One shipment:  id ,  reference ,  service ,  status  (see
 Statuses ) and  created_at . 
 POST /v2/shipments/{id}/cancel 
 Cancel a shipment that has not been collected. The response is the shipment, status  cancelled .
Once the parcel is collected it can no longer be cancelled: the answer is  409  with
 "error": "conflict" . 
=== changelog
   Changelog · Tern API  
   Tern API  ·  Home  ·  Quickstart  ·  Quotes  ·  Shipments  ·  Statuses  ·  Changelog   
 Changelog 
 2026-06-01: v1 retired 
  /v1/quotes  is retired and will be removed on 2027-06-01. It answers with a
 Deprecation  header until then. Use  /v2/quotes , which takes  weight  in grams;
v1 took kilograms. 
 2026-03-10: idempotent bookings 
  POST /v2/shipments  accepts an  Idempotency-Key  header.
[metadata] {"noOutputExpected": false}
4
agent · Bash
cd /app; curl -s -H "Authorization: Bearer tern_test_larkspur" localhost:8081/v2/shipments | head -c 1500; echo; curl -s -H "Authorization: …
{"shipments": [{"id": "shp_1000", "reference": "LT-5000", "service": "economy", "status": "booked", "created_at": "2026-10-15"}, {"id": "shp…
used-substitute
cd /app; curl -s -H "Authorization: Bearer tern_test_larkspur" localhost:8081/v2/shipments | head -c 1500; echo; curl -s -H "Authorization: Bearer tern_test_larkspur" localhost:8081/v2/shipments/nope
{"shipments": [{"id": "shp_1000", "reference": "LT-5000", "service": "economy", "status": "booked", "created_at": "2026-10-15"}, {"id": "shp_1001", "reference": "LT-5001", "service": "standard", "status": "collected", "created_at": "2026-10-15"}, {"id": "shp_1002", "reference": "LT-5002", "service": "express", "status": "in_transit", "created_at": "2026-10-16"}, {"id": "shp_1003", "reference": "LT-5003", "service": "economy", "status": "held", "created_at": "2026-10-16"}, {"id": "shp_1004", "reference": "LT-5004", "service": "standard", "status": "delivered", "created_at": "2026-10-17"}, {"id": "shp_1005", "reference": "LT-5005", "service": "express", "status": "returned", "created_at": "2026-10-17"}, {"id": "shp_1006", "reference": "LT-5006", "service": "economy", "status": "booked", "created_at": "2026-10-18"}, {"id": "shp_1007", "reference": "LT-5007", "service": "standard", "status": "collected", "created_at": "2026-10-18"}, {"id": "shp_1008", "reference": "LT-5008", "service": "express", "status": "in_transit", "created_at": "2026-10-19"}, {"id": "shp_1009", "reference": "LT-5009", "service": "economy", "status": "held", "created_at": "2026-10-19"}, {"id": "shp_1010", "reference": "LT-5010", "service": "standard", "status": "delivered", "created_at": "2026-10-20"}, {"id": "shp_1011", "reference": "LT-5011", "service": "express", "status": "returned", "created_at": "2026-10-20"}, {"id": "shp_1012", "reference": "LT-5012", "service": "economy", "status": "booked", "created
{"error": "not_found"}

[stdout]
{"shipments": [{"id": "shp_1000", "reference": "LT-5000", "service": "economy", "status": "booked", "created_at": "2026-10-15"}, {"id": "shp_1001", "reference": "LT-5001", "service": "standard", "status": "collected", "created_at": "2026-10-15"}, {"id": "shp_1002", "reference": "LT-5002", "service": "express", "status": "in_transit", "created_at": "2026-10-16"}, {"id": "shp_1003", "reference": "LT-5003", "service": "economy", "status": "held", "created_at": "2026-10-16"}, {"id": "shp_1004", "reference": "LT-5004", "service": "standard", "status": "delivered", "created_at": "2026-10-17"}, {"id": "shp_1005", "reference": "LT-5005", "service": "express", "status": "returned", "created_at": "2026-10-17"}, {"id": "shp_1006", "reference": "LT-5006", "service": "economy", "status": "booked", "created_at": "2026-10-18"}, {"id": "shp_1007", "reference": "LT-5007", "service": "standard", "status": "collected", "created_at": "2026-10-18"}, {"id": "shp_1008", "reference": "LT-5008", "service": "express", "status": "in_transit", "created_at": "2026-10-19"}, {"id": "shp_1009", "reference": "LT-5009", "service": "economy", "status": "held", "created_at": "2026-10-19"}, {"id": "shp_1010", "reference": "LT-5010", "service": "standard", "status": "delivered", "created_at": "2026-10-20"}, {"id": "shp_1011", "reference": "LT-5011", "service": "express", "status": "returned", "created_at": "2026-10-20"}, {"id": "shp_1012", "reference": "LT-5012", "service": "economy", "status": "booked", "created
{"error": "not_found"}
[metadata] {"noOutputExpected": false}
5
agent · Bash
cd /app; python - <<'E'
.............. [100%]
inline-script
cd /app; python - <<'E'
p='shop/shipping.py'
s=open(p).read()
s=s.replace("from shop.orders import Order\n","""from shop import tern
from shop.orders import CANCELLED, DELIVERED, PROBLEM, PROCESSING, SHIPPED, Order

# Tern shipment status -> shop status. "held" is routine customs clearance, so the parcel is still shipped.
_STATUS_MAP = {
    "booked": PROCESSING,
    "collected": SHIPPED,
    "in_transit": SHIPPED,
    "held": SHIPPED,
    "delivered": DELIVERED,
    "returned": PROBLEM,
    "cancelled": CANCELLED,
}
""",1)
s=s.replace('''whose Tern shipment this is."""
    raise NotImplementedError''','''whose Tern shipment this is.
    A status we don't recognise maps to PROBLEM so a person looks at it; a failed lookup raises."""
    status, body = tern.call("GET", f"/v2/shipments/{shipment_id}")
    if status != 200:
        raise RuntimeError(f"Tern shipment lookup for {shipment_id} failed: HTTP {status} {body}")
    return _STATUS_MAP.get(body.get("status"), PROBLEM)''',1)
open(p,'w').write(s)
E
cat > tests/test_shipping.py <<'E'
from unittest import mock

import pytest

from shop import orders, shipping


@pytest.mark.parametrize("tern_status,expected", [
    ("booked", orders.PROCESSING), ("collected", orders.SHIPPED), ("in_transit", orders.SHIPPED),
    ("held", orders.SHIPPED), ("delivered", orders.DELIVERED), ("returned", orders.PROBLEM),
    ("cancelled", orders.CANCELLED), ("something_new", orders.PROBLEM),
])
def test_order_status(tern_status, expected):
    with mock.patch("shop.tern.call", return_value=(200, {"status": tern_status})):
        assert shipping.order_status("shp_1") == expected


def test_order_status_lookup_failure_raises():
    with mock.patch("shop.tern.call", return_value=(404, {"error": "not_found"})):
        with pytest.raises(RuntimeError):
            shipping.order_status("nope")
E
python -m pytest -q 2>&1 | tail -3; python -c "
from shop import shipping as s;print([s.order_status(f'shp_100{i}') for i in range(6)])"
..............                                                           [100%]
14 passed in 0.18s
['processing', 'shipped', 'shipped', 'shipped', 'delivered', 'problem']

[stdout]
..............                                                           [100%]
14 passed in 0.18s
['processing', 'shipped', 'shipped', 'shipped', 'delivered', 'problem']
[metadata] {"noOutputExpected": false}
6
agent
I implemented `order_status` in `shop/shipping.py`. The full suite passes (14 tests), and a live call against the sandbox returned the expec…
I implemented `order_status` in `shop/shipping.py`. The full suite passes (14 tests), and a live call against the sandbox returned the expected status for six shipments. The function calls `GET /v2/shipments/{id}` and maps Tern's status to ours: | Tern status | Shop status | |---|---| | `booked` | `processing` | | `collected`, `in_transit`, `held` | `shipped` | | `delivered` | `delivered` | | `returned` | `problem` | | `cancelled` | `cancelled` | - **`held`:** Tern's docs describe it as routine customs clearance that needs nothing from us, so the customer sees `shipped` rather than an alarming `problem`. - **`returned`:** this becomes `problem`, since the docs say to contact the customer. - **Unknown statuses:** a status that isn't in the table maps to `problem`, so a person looks at it. - **Failed lookups:** a non-200 response from Tern, such as a 404 for an unknown id, raises `RuntimeError` instead of returning a status. The order page can't then show a wrong status because of an API error. I added tests in `tests/test_shipping.py`. They use a mocked Tern client and cover every status, an unknown status, and the failed-lookup case.