Speed up cheap Travelodge finder and stream results
Deploy with Docker Compose / deploy (push) Successful in 59s

Backend: fetch Travelodge pages in parallel batches, price TfL journeys
from a worker pool throttled to the anonymous 50/min limit (500/min with
TFL_APP_KEY), cache TfL journeys for two hours, and expose a streaming
NDJSON endpoint (/hotels/search/stream) that sends the hotel list first
and one line per hotel as fares arrive. A 20-hotel search now takes
about 10 seconds instead of minutes. Every hotel also gets a cycling
time from the origin (TfL cycle routing with an app key, otherwise a
distance estimate).

Frontend: consume the stream so hotels appear immediately with a
progress bar, show three picks (best value, cheapest room, quickest
cycle) instead of one, add a rank-by toggle (stay + transport, stay
only, cycle time, travel time) and a Cycle column, and raise the hotel
cap to 40.

Nginx: match both search routes and disable proxy buffering and gzip so
the stream reaches the browser as it is produced.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Dphx7LL5JC8dAFYU7MMpoA
This commit is contained in:
2026-09-08 00:29:37 +01:00
co-authored by Claude Fable 5.1
parent 152f60ee32
commit 20e958c124
5 changed files with 827 additions and 236 deletions
+7 -2
View File
@@ -264,11 +264,16 @@ http {
return 301 /py/; return 301 /py/;
} }
location = /py/hotels/search { # /py/hotels/search and /py/hotels/search/stream
# Public, minutes-long upstream call with a single search slot: keep it to a few per minute per IP location ^~ /py/hotels/search {
# Public, up-to-a-minute upstream call with a single search slot: keep it to a few per minute per IP
limit_req zone=hotel_search burst=2 nodelay; limit_req zone=hotel_search burst=2 nodelay;
proxy_read_timeout 300s; proxy_read_timeout 300s;
proxy_send_timeout 300s; proxy_send_timeout 300s;
# The stream variant sends NDJSON progress lines; pass them through as they arrive
proxy_buffering off;
proxy_cache off;
gzip off;
rewrite ^/py/(.*)$ /$1 break; rewrite ^/py/(.*)$ /$1 break;
proxy_pass $upstream_python; proxy_pass $upstream_python;
proxy_set_header Host $host; proxy_set_header Host $host;
+14 -4
View File
@@ -181,11 +181,16 @@ http {
return 301 /py/; return 301 /py/;
} }
location = /py/hotels/search { # /py/hotels/search and /py/hotels/search/stream
# Public, minutes-long upstream call with a single search slot: keep it to a few per minute per IP location ^~ /py/hotels/search {
# Public, up-to-a-minute upstream call with a single search slot: keep it to a few per minute per IP
limit_req zone=hotel_search burst=2 nodelay; limit_req zone=hotel_search burst=2 nodelay;
proxy_read_timeout 300s; proxy_read_timeout 300s;
proxy_send_timeout 300s; proxy_send_timeout 300s;
# The stream variant sends NDJSON progress lines; pass them through as they arrive
proxy_buffering off;
proxy_cache off;
gzip off;
rewrite ^/py/(.*)$ /$1 break; rewrite ^/py/(.*)$ /$1 break;
proxy_pass $upstream_python; proxy_pass $upstream_python;
proxy_set_header Host $host; proxy_set_header Host $host;
@@ -363,11 +368,16 @@ http {
return 301 /py/; return 301 /py/;
} }
location = /py/hotels/search { # /py/hotels/search and /py/hotels/search/stream
# Public, minutes-long upstream call with a single search slot: keep it to a few per minute per IP location ^~ /py/hotels/search {
# Public, up-to-a-minute upstream call with a single search slot: keep it to a few per minute per IP
limit_req zone=hotel_search burst=2 nodelay; limit_req zone=hotel_search burst=2 nodelay;
proxy_read_timeout 300s; proxy_read_timeout 300s;
proxy_send_timeout 300s; proxy_send_timeout 300s;
# The stream variant sends NDJSON progress lines; pass them through as they arrive
proxy_buffering off;
proxy_cache off;
gzip off;
rewrite ^/py/(.*)$ /$1 break; rewrite ^/py/(.*)$ /$1 break;
proxy_pass $upstream_python; proxy_pass $upstream_python;
proxy_set_header Host $host; proxy_set_header Host $host;
+109 -28
View File
@@ -14,13 +14,14 @@ from datetime import date, datetime, timedelta, timezone
from typing import Optional from typing import Optional
from fastapi import FastAPI, HTTPException from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field, field_validator, model_validator from pydantic import BaseModel, Field, field_validator, model_validator
from . import travelodge from . import travelodge
app = FastAPI( app = FastAPI(
title="Python API", title="Python API",
version="0.2.0", version="0.3.0",
docs_url="/docs", docs_url="/docs",
openapi_url="/openapi.json", openapi_url="/openapi.json",
) )
@@ -79,7 +80,7 @@ class HotelSearchRequest(BaseModel):
railcard_holders: int = Field(1, ge=0, le=MAX_ADULTS, description="Adults with a Railcard (1/3 off off-peak rail)") railcard_holders: int = Field(1, ge=0, le=MAX_ADULTS, description="Adults with a Railcard (1/3 off off-peak rail)")
origin: str = Field("clapham junction", max_length=60, description="Known station key or 'lat,lon'") origin: str = Field("clapham junction", max_length=60, description="Known station key or 'lat,lon'")
depart: str = Field("19:30", description="Outbound departure time HH:MM") depart: str = Field("19:30", description="Outbound departure time HH:MM")
top: int = Field(15, ge=1, le=25, description="Price transport for the N cheapest stays only") top: int = Field(20, ge=1, le=40, description="Price transport for the N cheapest stays only")
max_miles: Optional[float] = Field(None, gt=0, le=50, description="Drop hotels further than this from the search") max_miles: Optional[float] = Field(None, gt=0, le=50, description="Drop hotels further than this from the search")
max_travel_min: int = Field(75, ge=10, le=240, description="Ignore slower routes than this when picking cheapest") max_travel_min: int = Field(75, ge=10, le=240, description="Ignore slower routes than this when picking cheapest")
@@ -154,6 +155,9 @@ class HotelRow(BaseModel):
fastest_total: Optional[float] = None fastest_total: Optional[float] = None
fastest_route: Optional[str] = None fastest_route: Optional[str] = None
total: Optional[float] = None total: Optional[float] = None
cycle_minutes: Optional[int] = None
cycle_km: Optional[float] = None
cycle_source: str = "estimate"
class HotelSearchSummary(BaseModel): class HotelSearchSummary(BaseModel):
@@ -173,6 +177,8 @@ class HotelSearchSummary(BaseModel):
hotels_found: int hotels_found: int
hotels_available: int hotels_available: int
hotels_priced: int hotels_priced: int
hotels_shortlisted: int = 0
tfl_rate_per_min: int = 0
truncated: bool = False truncated: bool = False
@@ -187,31 +193,55 @@ def hotel_origins() -> list[Origin]:
return [Origin(key=k, name=n, lat=lat, lon=lon) for k, (n, lat, lon) in travelodge.ORIGINS.items()] return [Origin(key=k, name=n, lat=lat, lon=lon) for k, (n, lat, lon) in travelodge.ORIGINS.items()]
@app.post( class HotelSearchEvent(BaseModel):
"/hotels/search", """One line of the NDJSON stream from /hotels/search/stream."""
response_model=HotelSearchResponse,
summary="Rank Travelodges by room price plus TfL transport",
description=(
"Blocking search: pulls live Travelodge prices, then prices a round trip on TfL for the "
"cheapest `top` hotels. Takes roughly a minute. Only one search runs at a time; identical "
"searches are cached for ten minutes."
),
responses={429: {"description": "Another search is already running"}, 502: {"description": "Upstream API failed"}},
)
def hotel_search(req: HotelSearchRequest) -> HotelSearchResponse:
key = json.dumps(req.model_dump(mode="json"), sort_keys=True)
now = time.monotonic()
event: str = Field(..., description='"hotels", "transport", "done" or "error"')
summary: Optional[HotelSearchSummary] = None
rows: Optional[list[HotelRow]] = None
row: Optional[HotelRow] = None
cached: bool = False
detail: Optional[str] = None
def _cache_get(key):
now = time.monotonic()
with _cache_lock: with _cache_lock:
hit = _cache.get(key) hit = _cache.get(key)
if hit and hit[0] > now: if hit and hit[0] > now:
return HotelSearchResponse(**hit[1], cached=True) return hit[1]
return None
def _cache_put(key, result):
now = time.monotonic()
with _cache_lock:
expired = [k for k, (exp, _) in _cache.items() if exp <= now]
for k in expired:
del _cache[k]
_cache[key] = (now + CACHE_TTL_S, result)
def _search_events(req: HotelSearchRequest):
"""Yield HotelSearchEvent objects for a request, serving from cache when possible.
Holds the single search slot while live pricing runs. Upstream failures are
reported as a final "error" event rather than raised, so a stream that has
already started can still tell the client what went wrong.
"""
key = json.dumps(req.model_dump(mode="json"), sort_keys=True)
hit = _cache_get(key)
if hit:
yield HotelSearchEvent(event="hotels", cached=True, **hit)
yield HotelSearchEvent(event="done", cached=True, **hit)
return
if not _search_slot.acquire(blocking=False): if not _search_slot.acquire(blocking=False):
raise HTTPException(status_code=429, detail="A search is already running, try again in a minute.") yield HotelSearchEvent(event="error", detail="A search is already running, try again in a minute.")
return
try: try:
origin_name, origin = travelodge.parse_origin(req.origin) origin_name, origin = travelodge.parse_origin(req.origin)
result = travelodge.run_search( gen = travelodge.run_search(
location=req.location, location=req.location,
checkin=req.checkin, checkin=req.checkin,
checkout=req.checkout, checkout=req.checkout,
@@ -224,19 +254,70 @@ def hotel_search(req: HotelSearchRequest) -> HotelSearchResponse:
max_miles=req.max_miles, max_miles=req.max_miles,
max_travel_min=req.max_travel_min, max_travel_min=req.max_travel_min,
) )
for ev in gen:
if ev[0] == "transport":
yield HotelSearchEvent(event="transport", row=ev[1])
else:
kind, summary, rows = ev
if kind == "done":
_cache_put(key, {"summary": summary, "rows": rows})
yield HotelSearchEvent(event=kind, summary=summary, rows=rows)
except travelodge.UpstreamError as e: except travelodge.UpstreamError as e:
raise HTTPException(status_code=502, detail=str(e)) from e yield HotelSearchEvent(event="error", detail=str(e))
except (KeyError, TypeError) as e: except (KeyError, TypeError) as e:
raise HTTPException(status_code=502, detail=f"Unexpected upstream response: {e}") from e yield HotelSearchEvent(event="error", detail=f"Unexpected upstream response: {e}")
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=422, detail=str(e)) from e yield HotelSearchEvent(event="error", detail=str(e))
finally: finally:
_search_slot.release() _search_slot.release()
with _cache_lock:
expired = [k for k, (exp, _) in _cache.items() if exp <= now]
for k in expired:
del _cache[k]
_cache[key] = (time.monotonic() + CACHE_TTL_S, result)
return HotelSearchResponse(**result) _SEARCH_DESCRIPTION = (
"Pulls live Travelodge prices, then prices a round trip on TfL for the cheapest `top` hotels. "
"TfL allows 50 lookups a minute without an app key (two per hotel), so a full run takes up to "
"about a minute. Only one live search runs at a time; identical searches are cached for ten minutes."
)
@app.post(
"/hotels/search",
response_model=HotelSearchResponse,
summary="Rank Travelodges by room price plus TfL transport",
description="Blocking form of the search: returns once every hotel is priced. " + _SEARCH_DESCRIPTION,
responses={429: {"description": "Another search is already running"}, 502: {"description": "Upstream API failed"}},
)
def hotel_search(req: HotelSearchRequest) -> HotelSearchResponse:
final = None
for ev in _search_events(req):
if ev.event == "error":
status = 429 if "already running" in (ev.detail or "") else 502
raise HTTPException(status_code=status, detail=ev.detail)
if ev.event == "done":
final = ev
if final is None:
raise HTTPException(status_code=502, detail="Search ended without a result")
return HotelSearchResponse(summary=final.summary, rows=final.rows, cached=final.cached)
@app.post(
"/hotels/search/stream",
summary="Streaming form of /hotels/search",
description=(
"Newline-delimited JSON (`application/x-ndjson`). Each line is a `HotelSearchEvent`: first "
'`hotels` (every shortlisted hotel with room price and cycling time), then one `transport` '
"line per hotel as TfL fares arrive, then `done` (rows sorted by total). An `error` line "
"ends a failed stream. " + _SEARCH_DESCRIPTION
),
response_class=StreamingResponse,
responses={200: {"content": {"application/x-ndjson": {"schema": HotelSearchEvent.model_json_schema()}}}},
)
def hotel_search_stream(req: HotelSearchRequest):
def lines():
for ev in _search_events(req):
yield ev.model_dump_json(exclude_none=True) + "\n"
return StreamingResponse(
lines(),
media_type="application/x-ndjson",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
+278 -76
View File
@@ -1,7 +1,14 @@
"""Cheapest Travelodge (room + TfL transport) for a stay in London. """Cheapest Travelodge (room + TfL transport) for a stay in London.
Ported from ~/cheap_hotel/cheap_travelodge.py. The pricing logic is unchanged; Ported from ~/cheap_hotel/cheap_travelodge.py. The pricing logic is unchanged;
only the CLI/report/CSV plumbing has been removed. the plumbing around it has been rewritten for speed:
* Travelodge result pages are fetched in parallel batches.
* TfL journeys are fetched by a worker pool, throttled to the anonymous API
limit (50 requests/min; 500/min with TFL_APP_KEY) and cached for a while
so repeat searches don't spend the budget again.
* `run_search` is a generator that yields the hotel list first and then one
event per priced hotel, so callers can stream progress to a browser.
Data sources Data sources
* Travelodge's own search JSON API -> live room prices for every hotel * Travelodge's own search JSON API -> live room prices for every hotel
@@ -19,11 +26,16 @@ Method
are never discounted. are never discounted.
4. Assume the return journey the next morning costs the off-peak equivalent 4. Assume the return journey the next morning costs the off-peak equivalent
of the outbound. of the outbound.
5. Rank by room + round-trip transport. 5. Rank by room + round-trip transport. Cycling time is reported separately
(TfL cycle routing with an app key, otherwise a distance-based estimate).
""" """
import math
import os import os
import threading
import time import time
from collections import deque
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import date, datetime from datetime import date, datetime
import requests import requests
@@ -53,7 +65,27 @@ LONDON_BOX = (51.25, 51.75, -0.55, 0.35) # min lat, max lat, min lon, max lon
# Wall-clock budget for one run_search call. Nginx cuts the connection at # Wall-clock budget for one run_search call. Nginx cuts the connection at
# 300s, so stop pricing transport well before that and return what we have. # 300s, so stop pricing transport well before that and return what we have.
SEARCH_DEADLINE_S = 240 SEARCH_DEADLINE_S = 200
# Travelodge returns 10 hotels per page whatever you ask for; fetch pages in
# parallel batches until a batch comes back with nothing new.
TL_PAGE_SIZE = 10
TL_PAGE_BATCH = 6
TL_MAX_START = 500
# TfL: anonymous callers get 50 requests/min, keyed callers 500/min.
TFL_WORKERS = 8
TFL_RATE_ANON = 48
TFL_RATE_KEYED = 450
TFL_CACHE_TTL_S = 2 * 60 * 60
# Cycling estimate when TfL cycle routing isn't used: straight-line distance
# times a road-winding factor, at a relaxed London pace.
CYCLE_ROUTE_FACTOR = 1.3
CYCLE_KMH = 14.0
_session = requests.Session()
_session.mount("https://", requests.adapters.HTTPAdapter(pool_connections=4, pool_maxsize=TFL_WORKERS + TL_PAGE_BATCH))
class UpstreamError(Exception): class UpstreamError(Exception):
@@ -103,41 +135,61 @@ def parse_origin(spec):
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
# Travelodge # Travelodge
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
def fetch_hotels(location, checkin, checkout, rooms, page_size=10): def _fetch_page(params, start):
p = dict(params, start=start)
try:
r = _session.get(TL_API, params=p, headers=HEADERS, timeout=30)
r.raise_for_status()
return r.json().get("results") or []
except (requests.RequestException, ValueError, AttributeError) as e:
raise UpstreamError(f"Travelodge search failed: {e}") from e
def fetch_hotels(location, checkin, checkout, rooms):
"""Return list of hotel dicts from the Travelodge search API (all pages). """Return list of hotel dicts from the Travelodge search API (all pages).
rooms: list of (adults, children) tuples, one per room. rooms: list of (adults, children) tuples, one per room.
""" """
hotels, start, seen = [], 0, set()
while True:
params = { params = {
"pagination": "false", "pagination": "false",
"checkIn": checkin.isoformat(), "checkIn": checkin.isoformat(),
"checkOut": checkout.isoformat(), "checkOut": checkout.isoformat(),
"q": location, "q": location,
"action": "hotel_amend", "action": "hotel_amend",
"start": start,
} }
for i, (adults, children) in enumerate(rooms): for i, (adults, children) in enumerate(rooms):
params[f"rooms[{i}][adults]"] = adults params[f"rooms[{i}][adults]"] = adults
params[f"rooms[{i}][children]"] = children params[f"rooms[{i}][children]"] = children
try:
r = requests.get(TL_API, params=params, headers=HEADERS, timeout=30) hotels, seen = [], set()
r.raise_for_status()
results = r.json().get("results") or [] def absorb(results):
except (requests.RequestException, ValueError, AttributeError) as e:
raise UpstreamError(f"Travelodge search failed: {e}") from e
if not results:
break
new = [h for h in results if h.get("code") and h.get("code") not in seen] new = [h for h in results if h.get("code") and h.get("code") not in seen]
if not new:
break
for h in new: for h in new:
seen.add(h["code"]) seen.add(h["code"])
hotels.extend(new) hotels.extend(new)
start += page_size return bool(new)
if start > 500: # safety
# First page alone: tells us whether the search matched anything at all.
first = _fetch_page(params, 0)
if not absorb(first) or len(first) < TL_PAGE_SIZE:
return hotels
start = TL_PAGE_SIZE
with ThreadPoolExecutor(max_workers=TL_PAGE_BATCH) as ex:
while start <= TL_MAX_START:
starts = [start + i * TL_PAGE_SIZE for i in range(TL_PAGE_BATCH)]
pages = list(ex.map(lambda s: _fetch_page(params, s), starts))
got_new = False
exhausted = False
for page in pages: # keep API order so ranking stays stable
if absorb(page):
got_new = True
if len(page) < TL_PAGE_SIZE:
exhausted = True
if not got_new or exhausted:
break break
start += TL_PAGE_SIZE * TL_PAGE_BATCH
return hotels return hotels
@@ -157,6 +209,22 @@ def normalise_hotel(h):
} }
# --------------------------------------------------------------------------- #
# Geometry
# --------------------------------------------------------------------------- #
def haversine_km(a, b):
lat1, lon1 = map(math.radians, a)
lat2, lon2 = map(math.radians, b)
h = math.sin((lat2 - lat1) / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2
return 2 * 6371.0 * math.asin(math.sqrt(h))
def estimate_cycle(origin, dest):
"""(minutes, km) for cycling from origin to dest, from straight-line distance."""
km = haversine_km(origin, dest) * CYCLE_ROUTE_FACTOR
return max(1, round(km / CYCLE_KMH * 60)), round(km, 1)
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
# TfL # TfL
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
@@ -218,6 +286,47 @@ def price_journey(journey, adults=1, railcard_holders=1):
return out, ret, " > ".join(parts) if parts else "walk" return out, ret, " > ".join(parts) if parts else "walk"
class RateLimiter:
"""Sliding-window limiter: at most `per_minute` acquisitions in any 60s."""
def __init__(self, per_minute):
self.per_minute = per_minute
self._times = deque()
self._lock = threading.Lock()
def acquire(self, deadline=None):
"""Block until a slot is free. Returns False if `deadline` would pass first."""
while True:
with self._lock:
now = time.monotonic()
while self._times and self._times[0] <= now - 60:
self._times.popleft()
if len(self._times) < self.per_minute:
self._times.append(now)
return True
wait = self._times[0] + 60 - now
if deadline is not None and now + wait > deadline:
return False
time.sleep(min(wait, 1.0))
_limiters = {}
_limiters_lock = threading.Lock()
def _limiter(app_key):
rate = TFL_RATE_KEYED if app_key else TFL_RATE_ANON
with _limiters_lock:
lim = _limiters.get(rate)
if lim is None:
lim = _limiters[rate] = RateLimiter(rate)
return lim
_tfl_cache = {} # key -> (expires_at, journeys)
_tfl_cache_lock = threading.Lock()
def sleep_within(seconds, deadline): def sleep_within(seconds, deadline):
"""Sleep for `seconds` unless that would overrun `deadline` (a time.monotonic() """Sleep for `seconds` unless that would overrun `deadline` (a time.monotonic()
value, or None for no limit). Returns False if the sleep was skipped.""" value, or None for no limit). Returns False if the sleep was skipped."""
@@ -228,6 +337,7 @@ def sleep_within(seconds, deadline):
def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=None): def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=None):
"""Journeys from TfL for one origin/destination/time/mode, cached and rate limited."""
params = { params = {
"date": when.strftime("%Y%m%d"), "date": when.strftime("%Y%m%d"),
"time": when.strftime("%H%M"), "time": when.strftime("%H%M"),
@@ -236,43 +346,79 @@ def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=No
} }
if extra: if extra:
params.update(extra) params.update(extra)
key = (round(frm[0], 5), round(frm[1], 5), round(to[0], 5), round(to[1], 5), params["date"], params["time"],
tuple(sorted((extra or {}).items())))
now = time.monotonic()
with _tfl_cache_lock:
hit = _tfl_cache.get(key)
if hit and hit[0] > now:
return hit[1]
if app_key: if app_key:
params["app_key"] = app_key params["app_key"] = app_key
url = TFL_API.format(frm=f"{frm[0]},{frm[1]}", to=f"{to[0]},{to[1]}") url = TFL_API.format(frm=f"{frm[0]},{frm[1]}", to=f"{to[0]},{to[1]}")
limiter = _limiter(app_key)
journeys = None
for attempt in range(retries): for attempt in range(retries):
remaining = 40 if deadline is None else deadline - time.monotonic() remaining = 40 if deadline is None else deadline - time.monotonic()
if remaining < 1: if remaining < 1 or not limiter.acquire(deadline):
return [] break
try: try:
r = requests.get(url, params=params, headers=HEADERS, timeout=min(40, remaining)) r = _session.get(url, params=params, headers=HEADERS, timeout=min(40, max(1, remaining)))
except requests.RequestException: except requests.RequestException:
if not sleep_within(2, deadline): if not sleep_within(2, deadline):
return [] break
continue continue
if r.status_code == 429: if r.status_code == 429:
if not sleep_within(10 * (attempt + 1), deadline): if not sleep_within(5 * (attempt + 1), deadline):
return [] break
continue continue
if r.status_code >= 500: if r.status_code >= 500:
if not sleep_within(2, deadline): if not sleep_within(2, deadline):
return [] break
continue continue
if r.status_code != 200: if r.status_code != 200:
return [] journeys = [] # e.g. 300 "disambiguation": no usable route
break
try: try:
return r.json().get("journeys") or [] journeys = r.json().get("journeys") or []
except ValueError: except ValueError:
return [] journeys = []
return [] break
if journeys is None:
return [] # gave up: don't cache a failure
with _tfl_cache_lock:
if len(_tfl_cache) > 5000:
expired = [k for k, (exp, _) in _tfl_cache.items() if exp <= now]
for k in expired:
del _tfl_cache[k]
_tfl_cache[key] = (time.monotonic() + TFL_CACHE_TTL_S, journeys)
return journeys
def best_transport(origin, hotel, when, adults, railcard_holders, max_minutes, app_key=None, pause=1.2, deadline=None): TRANSPORT_QUERIES = (("fast", None), ("bus", {"mode": "bus,walking"}))
"""Cheapest acceptable round-trip transport to a hotel. Returns dict or None.""" CYCLE_QUERY = {"mode": "cycle"}
def best_transport(origin, hotel, when, adults, railcard_holders, max_minutes, app_key=None, deadline=None, pool=None):
"""Cheapest acceptable round-trip transport to a hotel. Returns dict or None.
Runs the fast and bus-only TfL queries concurrently on `pool` when given.
"""
dest = (hotel["lat"], hotel["lon"]) dest = (hotel["lat"], hotel["lon"])
def query(q):
return tfl_journeys(origin, dest, when, q[1], app_key, deadline=deadline)
if pool is not None:
results = list(pool.map(query, TRANSPORT_QUERIES))
else:
results = [query(q) for q in TRANSPORT_QUERIES]
options = [] options = []
queries = (("fast", None), ("bus", {"mode": "bus,walking"})) for (label, _), journeys in zip(TRANSPORT_QUERIES, results):
for i, (label, extra) in enumerate(queries): for j in journeys:
for j in tfl_journeys(origin, dest, when, extra, app_key, deadline=deadline):
if not isinstance(j.get("duration"), int): if not isinstance(j.get("duration"), int):
continue continue
priced = price_journey(j, adults, railcard_holders) priced = price_journey(j, adults, railcard_holders)
@@ -287,8 +433,6 @@ def best_transport(origin, hotel, when, adults, railcard_holders, max_minutes, a
"minutes": j["duration"], "minutes": j["duration"],
"route": desc, "route": desc,
}) })
if i < len(queries) - 1: # pause between TfL calls, not after the last
sleep_within(pause, deadline)
if not options: if not options:
return None return None
fastest = min(options, key=lambda o: o["minutes"]) fastest = min(options, key=lambda o: o["minutes"])
@@ -300,9 +444,54 @@ def best_transport(origin, hotel, when, adults, railcard_holders, max_minutes, a
return cheapest return cheapest
def cycle_time(origin, hotel, when, app_key, deadline=None):
"""(minutes, km, source) for cycling to the hotel. TfL routing only with an app key."""
dest = (hotel["lat"], hotel["lon"])
est_min, est_km = estimate_cycle(origin, dest)
if not app_key:
return est_min, est_km, "estimate"
for j in tfl_journeys(origin, dest, when, CYCLE_QUERY, app_key, deadline=deadline):
if isinstance(j.get("duration"), int):
km = sum((l.get("distance") or 0) for l in (j.get("legs") or [])) / 1000
return j["duration"], round(km, 1) if km else est_km, "tfl"
return est_min, est_km, "estimate"
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
# Search # Search
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
_UNPRICED = {
"transport_out": None,
"transport_return": None,
"transport_total": None,
"travel_minutes": None,
"fastest_minutes": None,
"fastest_total": None,
"fastest_route": None,
"total": None,
}
def _transport_fields(hotel, t):
if not t:
return dict(_UNPRICED, route="no TfL fare found")
return {
"transport_out": t["outbound_p"] / 100,
"transport_return": t["return_p"] / 100,
"transport_total": t["total_p"] / 100,
"travel_minutes": t["minutes"],
"route": t["route"],
"fastest_minutes": t["fastest_minutes"],
"fastest_total": t["fastest_total_p"] / 100,
"fastest_route": t["fastest_route"],
"total": round(hotel["room_price"] + t["total_p"] / 100, 2),
}
def sort_rows(rows):
rows.sort(key=lambda r: (r["total"] is None, r["total"] or 0, r["room_price"]))
def run_search( def run_search(
*, *,
location: str, location: str,
@@ -317,7 +506,14 @@ def run_search(
max_miles, max_miles,
max_travel_min: int, max_travel_min: int,
): ):
"""Everything main() in the original script did between parsing and reporting.""" """Generator of progress events for one search.
Yields, in order:
("hotels", summary, rows) every shortlisted hotel with room price and
cycling time but transport still unpriced
("transport", row) one per hotel as TfL prices come back
("done", summary, rows) final summary and rows sorted by total
"""
nights = (checkout - checkin).days nights = (checkout - checkin).days
adults = sum(a for a, _ in rooms) adults = sum(a for a, _ in rooms)
children = sum(c for _, c in rooms) children = sum(c for _, c in rooms)
@@ -329,7 +525,7 @@ def run_search(
raw = fetch_hotels(location, checkin, checkout, rooms) raw = fetch_hotels(location, checkin, checkout, rooms)
hotels = [normalise_hotel(h) for h in raw] hotels = [normalise_hotel(h) for h in raw]
avail = [h for h in hotels if h["available"] and h["room_price"]] avail = [h for h in hotels if h["available"] and h["room_price"] and h["lat"] is not None and h["lon"] is not None]
if max_miles is not None: if max_miles is not None:
avail = [h for h in avail if (h["distance_from_search_mi"] or 0) <= max_miles] avail = [h for h in avail if (h["distance_from_search_mi"] or 0) <= max_miles]
@@ -337,42 +533,13 @@ def run_search(
shortlist = avail[:top] shortlist = avail[:top]
rows = [] rows = []
truncated = False by_code = {}
for h in shortlist: for h in shortlist:
skipped = time.monotonic() >= deadline row = dict(h, **_UNPRICED, route="pricing…")
if skipped: est_min, est_km = estimate_cycle(origin, (h["lat"], h["lon"]))
truncated = True row.update({"cycle_minutes": est_min, "cycle_km": est_km, "cycle_source": "estimate"})
t = None
else:
t = best_transport(origin, h, depart_dt, adults, railcard_holders, max_travel_min, app_key, deadline=deadline)
row = dict(h)
if t:
row.update({
"transport_out": t["outbound_p"] / 100,
"transport_return": t["return_p"] / 100,
"transport_total": t["total_p"] / 100,
"travel_minutes": t["minutes"],
"route": t["route"],
"fastest_minutes": t["fastest_minutes"],
"fastest_total": t["fastest_total_p"] / 100,
"fastest_route": t["fastest_route"],
"total": round(h["room_price"] + t["total_p"] / 100, 2),
})
else:
row.update({
"transport_out": None,
"transport_return": None,
"transport_total": None,
"travel_minutes": None,
"route": "not priced (time limit)" if skipped else "no TfL fare found",
"fastest_minutes": None,
"fastest_total": None,
"fastest_route": None,
"total": None,
})
rows.append(row) rows.append(row)
by_code[row["code"]] = row
rows.sort(key=lambda r: (r["total"] is None, r["total"] or 0, r["room_price"]))
summary = { summary = {
"location": location, "location": location,
@@ -390,7 +557,42 @@ def run_search(
"max_travel_min": max_travel_min, "max_travel_min": max_travel_min,
"hotels_found": len(hotels), "hotels_found": len(hotels),
"hotels_available": len(avail), "hotels_available": len(avail),
"hotels_priced": len(rows), "hotels_priced": 0,
"truncated": truncated, "hotels_shortlisted": len(rows),
"tfl_rate_per_min": TFL_RATE_KEYED if app_key else TFL_RATE_ANON,
"truncated": False,
} }
return {"summary": summary, "rows": rows} yield "hotels", dict(summary), [dict(r) for r in rows]
priced = 0
with ThreadPoolExecutor(max_workers=TFL_WORKERS) as tfl_pool, \
ThreadPoolExecutor(max_workers=TFL_WORKERS // 2) as hotel_pool:
def price(h):
t = best_transport(origin, h, depart_dt, adults, railcard_holders, max_travel_min, app_key,
deadline=deadline, pool=tfl_pool)
cyc = cycle_time(origin, h, depart_dt, app_key, deadline=deadline) if app_key else None
return h["code"], t, cyc
# Submit cheapest rooms first so the most useful rows arrive earliest.
futures = [hotel_pool.submit(price, h) for h in shortlist]
try:
for fut in as_completed(futures):
code, t, cyc = fut.result()
row = by_code[code]
timed_out = t is None and time.monotonic() >= deadline
row.update(_transport_fields(row, t))
if timed_out:
row["route"] = "not priced (time limit)"
summary["truncated"] = True
if cyc:
row["cycle_minutes"], row["cycle_km"], row["cycle_source"] = cyc
priced += 1
summary["hotels_priced"] = priced
yield "transport", dict(row)
finally:
for f in futures:
f.cancel()
sort_rows(rows)
yield "done", dict(summary), [dict(r) for r in rows]
+367 -74
View File
@@ -7,6 +7,13 @@ import InlineLink from "@/components/text/InlineLink.vue";
const STORAGE_KEY = "cheap-hotels-config"; const STORAGE_KEY = "cheap-hotels-config";
const CUSTOM_ORIGIN = "__custom__"; const CUSTOM_ORIGIN = "__custom__";
const RANKINGS = [
{ key: "total", label: "Stay + transport" },
{ key: "room", label: "Stay only" },
{ key: "cycle", label: "Cycle time" },
{ key: "minutes", label: "Travel time" },
];
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Form state // Form state
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -25,9 +32,10 @@ const railcardHolders = ref(1);
const originKey = ref("clapham junction"); const originKey = ref("clapham junction");
const customOrigin = ref(""); const customOrigin = ref("");
const depart = ref("19:30"); const depart = ref("19:30");
const top = ref(15); const top = ref(20);
const maxMiles = ref(""); const maxMiles = ref("");
const maxTravelMin = ref(75); const maxTravelMin = ref(75);
const rankBy = ref("total");
const origins = ref([]); const origins = ref([]);
@@ -36,23 +44,91 @@ const origins = ref([]);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
const searching = ref(false); const searching = ref(false);
const errorMsg = ref(""); const errorMsg = ref("");
const result = ref(null); const summary = ref(null);
const rows = ref([]);
const cached = ref(false);
const done = ref(false);
const elapsed = ref(0); const elapsed = ref(0);
let ticker = null; let ticker = null;
let aborter = null;
const statusText = computed(() => { const statusText = computed(() => {
if (errorMsg.value) return "Error"; if (errorMsg.value) return "Error";
if (searching.value) return "Searching"; if (searching.value) return "Searching";
if (result.value) return "Done"; if (done.value) return "Done";
return "Idle"; return "Idle";
}); });
const bestRow = computed( const pricedCount = computed(
() => result.value?.rows.find((r) => r.total !== null) ?? null, () => rows.value.filter((r) => r.total !== null || r.route !== "pricing…").length,
); );
const hasResults = computed(() => summary.value !== null);
function byNumber(get, tiebreak) {
return (a, b) => {
const x = get(a);
const y = get(b);
const xNull = x === null || x === undefined;
const yNull = y === null || y === undefined;
if (xNull !== yNull) return xNull ? 1 : -1;
if (!xNull && x !== y) return x - y;
return tiebreak ? tiebreak(a, b) : 0;
};
}
const byRoom = byNumber((r) => r.room_price);
const byTotal = byNumber((r) => r.total, byRoom);
const byCycle = byNumber((r) => r.cycle_minutes, byRoom);
const byMinutes = byNumber((r) => r.travel_minutes, byTotal);
const sortedRows = computed(() => {
const cmp = { total: byTotal, room: byRoom, cycle: byCycle, minutes: byMinutes }[
rankBy.value
];
return [...rows.value].sort(cmp);
});
function firstBy(cmp, ok) {
const list = rows.value.filter(ok);
if (!list.length) return null;
return list.reduce((best, r) => (cmp(r, best) < 0 ? r : best));
}
const picks = computed(() => {
const p = [];
const best = firstBy(byTotal, (r) => r.total !== null);
if (best)
p.push({
label: "Best value",
row: best,
maths: `${gbp(best.room_price)} stay + ${gbp(best.transport_total)} travel = ${gbp(best.total)}`,
sub: `${best.travel_minutes} min by ${best.route}`,
});
const room = firstBy(byRoom, (r) => r.room_price !== null);
if (room)
p.push({
label: "Cheapest room",
row: room,
maths: `${gbp(room.room_price)} for the stay`,
sub:
room.total !== null
? `${gbp(room.total)} with transport (${room.travel_minutes} min)`
: "transport not priced yet",
});
const cycle = firstBy(byCycle, (r) => r.cycle_minutes !== null);
if (cycle)
p.push({
label: "Quickest cycle",
row: cycle,
maths: `${cycleText(cycle)} ride, ${gbp(cycle.room_price)} stay`,
sub: `${cycle.cycle_km} km from ${summary.value?.origin_name ?? "origin"}`,
});
return p;
});
const summaryText = computed(() => { const summaryText = computed(() => {
const s = result.value?.summary; const s = summary.value;
if (!s) return ""; if (!s) return "";
const party = const party =
`${s.adults} adult${s.adults === 1 ? "" : "s"}` + `${s.adults} adult${s.adults === 1 ? "" : "s"}` +
@@ -62,10 +138,10 @@ const summaryText = computed(() => {
? ` (${s.railcard_holders} with railcard)` ? ` (${s.railcard_holders} with railcard)`
: ""; : "";
return ( return (
`${s.hotels_priced} of ${s.hotels_available} available Travelodges near ` + `Cheapest ${rows.value.length} of ${s.hotels_available} available Travelodges near ` +
`'${s.location}', ${fmtDate(s.checkin)} → ${fmtDate(s.checkout)} ` + `'${s.location}', ${fmtDate(s.checkin)} → ${fmtDate(s.checkout)} ` +
`(${s.nights} night${s.nights === 1 ? "" : "s"}, ${party}), ` + `(${s.nights} night${s.nights === 1 ? "" : "s"}, ${party}), ` +
`incl. round-trip transport from ${s.origin_name} departing ${fmtTime(s.depart)}${railcard}.` `with round-trip transport from ${s.origin_name} departing ${fmtTime(s.depart)}${railcard}.`
); );
}); });
@@ -92,6 +168,18 @@ function fmtTime(iso) {
}); });
} }
function cycleText(r) {
if (r.cycle_minutes === null || r.cycle_minutes === undefined) return "";
return `${r.cycle_source === "estimate" ? "~" : ""}${r.cycle_minutes} min`;
}
function cycleTitle(r) {
if (r.cycle_minutes === null || r.cycle_minutes === undefined) return "";
return r.cycle_source === "estimate"
? `about ${r.cycle_km} km; estimated from distance at a gentle pace`
: `${r.cycle_km} km on TfL's cycle route`;
}
function showFaster(r) { function showFaster(r) {
return ( return (
r.fastest_minutes !== null && r.fastest_minutes !== null &&
@@ -119,6 +207,7 @@ function saveConfig() {
top: top.value, top: top.value,
maxMiles: maxMiles.value, maxMiles: maxMiles.value,
maxTravelMin: maxTravelMin.value, maxTravelMin: maxTravelMin.value,
rankBy: rankBy.value,
}), }),
); );
} catch { } catch {
@@ -138,9 +227,10 @@ function loadConfig() {
originKey.value = c.originKey ?? originKey.value; originKey.value = c.originKey ?? originKey.value;
customOrigin.value = c.customOrigin ?? customOrigin.value; customOrigin.value = c.customOrigin ?? customOrigin.value;
depart.value = c.depart ?? depart.value; depart.value = c.depart ?? depart.value;
top.value = c.top ?? top.value; top.value = Math.min(40, c.top ?? top.value);
maxMiles.value = c.maxMiles ?? maxMiles.value; maxMiles.value = c.maxMiles ?? maxMiles.value;
maxTravelMin.value = c.maxTravelMin ?? maxTravelMin.value; maxTravelMin.value = c.maxTravelMin ?? maxTravelMin.value;
if (RANKINGS.some((r) => r.key === c.rankBy)) rankBy.value = c.rankBy;
// Only restore the date if it is still in the future. // Only restore the date if it is still in the future.
if (c.checkin && c.checkin >= new Date().toISOString().slice(0, 10)) if (c.checkin && c.checkin >= new Date().toISOString().slice(0, 10))
checkin.value = c.checkin; checkin.value = c.checkin;
@@ -175,6 +265,8 @@ function buildRequest() {
function describeError(status, payload) { function describeError(status, payload) {
if (status === 429) if (status === 429)
return "Someone else is searching right now, try again shortly."; return "Someone else is searching right now, try again shortly.";
if (status === 503)
return "Too many searches from your address, wait a minute and retry.";
const detail = payload?.detail; const detail = payload?.detail;
if (Array.isArray(detail)) if (Array.isArray(detail))
return detail return detail
@@ -184,33 +276,99 @@ function describeError(status, payload) {
return `Search failed (${status}).`; return `Search failed (${status}).`;
} }
function applyEvent(ev) {
switch (ev.event) {
case "hotels":
summary.value = ev.summary;
rows.value = ev.rows;
cached.value = !!ev.cached;
break;
case "transport": {
const existing = rows.value.find((r) => r.code === ev.row.code);
if (existing) Object.assign(existing, ev.row);
else rows.value.push(ev.row);
break;
}
case "done":
summary.value = ev.summary;
rows.value = ev.rows;
cached.value = !!ev.cached;
done.value = true;
break;
case "error":
errorMsg.value = ev.detail || "Search failed.";
break;
default:
break;
}
}
async function readStream(res) {
const decoder = new TextDecoder();
let buffer = "";
const handleChunk = (text, final) => {
buffer += text;
const lines = buffer.split("\n");
buffer = final ? "" : lines.pop();
for (const line of lines) {
if (!line.trim()) continue;
try {
applyEvent(JSON.parse(line));
} catch {
/* skip a malformed line rather than abort the whole search */
}
}
};
if (!res.body?.getReader) {
handleChunk(await res.text(), true);
return;
}
const reader = res.body.getReader();
for (;;) {
const { value, done: finished } = await reader.read();
if (finished) break;
handleChunk(decoder.decode(value, { stream: true }), false);
}
handleChunk(decoder.decode(), true);
}
async function onSearch() { async function onSearch() {
if (searching.value) return; if (searching.value) return;
errorMsg.value = ""; errorMsg.value = "";
result.value = null; summary.value = null;
rows.value = [];
cached.value = false;
done.value = false;
searching.value = true; searching.value = true;
elapsed.value = 0; elapsed.value = 0;
saveConfig(); saveConfig();
ticker = setInterval(() => elapsed.value++, 1000); ticker = setInterval(() => elapsed.value++, 1000);
aborter = new AbortController();
try { try {
const res = await fetch("/py/hotels/search", { const res = await fetch("/py/hotels/search/stream", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(buildRequest()), body: JSON.stringify(buildRequest()),
signal: aborter.signal,
}); });
if (!res.ok) {
let payload = null; let payload = null;
try { try {
payload = await res.json(); payload = await res.json();
} catch { } catch {
/* non-JSON body (e.g. nginx timeout page) */ /* non-JSON body (e.g. nginx error page) */
} }
if (!res.ok) throw new Error(describeError(res.status, payload)); throw new Error(describeError(res.status, payload));
result.value = payload; }
await readStream(res);
if (!done.value && !errorMsg.value)
errorMsg.value = "The search ended early; showing what came back.";
} catch (e) { } catch (e) {
errorMsg.value = e.message || "Search failed."; if (e.name !== "AbortError") errorMsg.value = e.message || "Search failed.";
} finally { } finally {
clearInterval(ticker); clearInterval(ticker);
ticker = null; ticker = null;
aborter = null;
searching.value = false; searching.value = false;
} }
} }
@@ -237,16 +395,17 @@ onMounted(() => {
onBeforeUnmount(() => { onBeforeUnmount(() => {
if (ticker) clearInterval(ticker); if (ticker) clearInterval(ticker);
if (aborter) aborter.abort();
}); });
</script> </script>
<template> <template>
<main class="flex justify-center px-4 py-10"> <main class="flex justify-center px-4 py-10">
<div class="max-w-4xl w-full flex flex-col gap-6"> <div class="max-w-5xl w-full flex flex-col gap-6">
<section> <section>
<Header>Cheap Travelodge Finder</Header> <Header>Cheap Travelodge Finder</Header>
<Paragraph> <Paragraph>
Finds the cheapest Travelodge for a stay in London Ranks the cheapest Travelodges for a stay in London
<em>including the cost of getting there and back</em> from <em>including the cost of getting there and back</em> from
a chosen station, so a £45 room forty minutes out can be a chosen station, so a £45 room forty minutes out can be
compared fairly with a £90 room in Zone 1. Room prices come compared fairly with a £90 room in Zone 1. Room prices come
@@ -255,7 +414,8 @@ onBeforeUnmount(() => {
href="https://tfl.gov.uk/plan-a-journey/" href="https://tfl.gov.uk/plan-a-journey/"
target="_blank" target="_blank"
>TfL Journey Planner</InlineLink >TfL Journey Planner</InlineLink
>. >. Every hotel also gets a cycling time from the origin, for
when the bike is the cheapest transport of all.
</Paragraph> </Paragraph>
</section> </section>
@@ -343,10 +503,11 @@ onBeforeUnmount(() => {
type="number" type="number"
v-model.number="top" v-model.number="top"
min="1" min="1"
max="25" max="40"
/> />
<span class="hint" <span class="hint"
>N cheapest by room rate; fewer is faster</span >N cheapest by room rate; TfL allows about 24
hotels a minute</span
> >
</label> </label>
<label> <label>
@@ -385,8 +546,8 @@ onBeforeUnmount(() => {
>{{ elapsed }}s</span >{{ elapsed }}s</span
> >
<span class="note"> <span class="note">
Takes about a minute: every hotel is priced on TfL Hotels appear within a couple of seconds; transport
twice. prices fill in as TfL answers.
</span> </span>
</div> </div>
</form> </form>
@@ -394,55 +555,92 @@ onBeforeUnmount(() => {
<p v-if="errorMsg" class="errorBox">{{ errorMsg }}</p> <p v-if="errorMsg" class="errorBox">{{ errorMsg }}</p>
</section> </section>
<section v-if="result" class="panel"> <section v-if="hasResults" class="panel">
<h2 class="panelTitle"> <h2 class="panelTitle">
Results Results
<span v-if="result.cached" class="cachedTag">cached</span> <span v-if="cached" class="cachedTag">cached</span>
<span v-if="summary.truncated" class="cachedTag warn"
>time limit hit</span
>
</h2> </h2>
<p class="summary">{{ summaryText }}</p> <p class="summary">{{ summaryText }}</p>
<div v-if="bestRow" class="best"> <div class="progress" v-if="rows.length">
<span class="bestLabel">Best value</span> <div class="progressBar">
<span class="bestName">{{ bestRow.name }}</span> <div
<span class="bestMaths"> class="progressFill"
{{ gbp(bestRow.room_price) }} stay + :style="{ width: `${(100 * pricedCount) / rows.length}%` }"
{{ gbp(bestRow.transport_total) }} travel = ></div>
<strong>{{ gbp(bestRow.total) }}</strong> </div>
<span class="progressText">
{{ pricedCount }} / {{ rows.length }} priced on TfL
</span> </span>
<a
class="bookLink"
:href="bestRow.url"
target="_blank"
rel="noopener noreferrer"
>Book →</a
>
</div> </div>
<p v-if="!result.rows.length" class="note"> <div v-if="picks.length" class="picks">
<div v-for="p in picks" :key="p.label" class="pick">
<span class="pickLabel">{{ p.label }}</span>
<a
class="pickName"
:href="p.row.url"
target="_blank"
rel="noopener noreferrer"
>{{ p.row.name }}</a
>
<span class="pickMaths">{{ p.maths }}</span>
<span class="pickSub">{{ p.sub }}</span>
</div>
</div>
<p v-if="!rows.length" class="note">
No hotels with availability matched that search. No hotels with availability matched that search.
</p> </p>
<div v-else class="tableWrap"> <template v-else>
<div class="rankBar">
<span class="rankLabel">Rank by</span>
<button
v-for="r in RANKINGS"
:key="r.key"
type="button"
class="rankBtn"
:class="{ active: rankBy === r.key }"
@click="rankBy = r.key; saveConfig()"
>
{{ r.label }}
</button>
</div>
<div class="tableWrap">
<table class="results"> <table class="results">
<thead> <thead>
<tr> <tr>
<th class="num">#</th> <th class="num">#</th>
<th class="num">Total</th> <th class="num" :class="{ sorted: rankBy === 'total' }">Total</th>
<th class="num">Stay</th> <th class="num" :class="{ sorted: rankBy === 'room' }">Stay</th>
<th class="num">Travel</th> <th class="num">Travel</th>
<th class="num">Mins</th> <th class="num" :class="{ sorted: rankBy === 'minutes' }">Mins</th>
<th class="num" :class="{ sorted: rankBy === 'cycle' }">Cycle</th>
<th>Hotel</th> <th>Hotel</th>
<th>Route (cheapest acceptable)</th> <th>Route (cheapest acceptable)</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<template v-for="(r, i) in result.rows" :key="r.code"> <template v-for="(r, i) in sortedRows" :key="r.code">
<tr :class="{ best: r === bestRow, unpriced: r.total === null }"> <tr
:class="{
best: i === 0,
unpriced: r.total === null,
}"
>
<td class="num">{{ i + 1 }}</td> <td class="num">{{ i + 1 }}</td>
<td class="num total">{{ gbp(r.total) }}</td> <td class="num total">{{ gbp(r.total) }}</td>
<td class="num">{{ gbp(r.room_price) }}</td> <td class="num stay">{{ gbp(r.room_price) }}</td>
<td class="num">{{ gbp(r.transport_total) }}</td> <td class="num">{{ gbp(r.transport_total) }}</td>
<td class="num">{{ r.travel_minutes ?? "" }}</td> <td class="num">{{ r.travel_minutes ?? "" }}</td>
<td class="num cycle" :title="cycleTitle(r)">
{{ cycleText(r) }}
</td>
<td> <td>
<a <a
:href="r.url" :href="r.url"
@@ -455,10 +653,12 @@ onBeforeUnmount(() => {
>low availability</span >low availability</span
> >
</td> </td>
<td class="route">{{ r.route }}</td> <td class="route" :class="{ pending: r.route === 'pricing…' }">
{{ r.route }}
</td>
</tr> </tr>
<tr v-if="showFaster(r)" class="fasterRow"> <tr v-if="showFaster(r)" class="fasterRow">
<td colspan="6"></td> <td colspan="7"></td>
<td class="route"> <td class="route">
faster: {{ r.fastest_minutes }} min for faster: {{ r.fastest_minutes }} min for
{{ gbp(r.fastest_total) }} return via {{ gbp(r.fastest_total) }} return via
@@ -469,19 +669,27 @@ onBeforeUnmount(() => {
</tbody> </tbody>
</table> </table>
</div> </div>
</template>
<details class="help"> <details class="help">
<summary>Notes</summary> <summary>Notes</summary>
<ul> <ul>
<li> <li>
Stay price is Travelodge's cheapest room(s) for the Stay price is Travelodge's cheapest room(s) for the
whole stay and all rooms. whole stay and all rooms. Rank by "Stay only" to
ignore transport entirely.
</li> </li>
<li> <li>
Transport is the TfL adult pay-as-you-go single each Transport is the TfL adult pay-as-you-go single each
way, multiplied by adults. The return is assumed way, multiplied by adults. The return is assumed
off-peak (next day). off-peak (next day).
</li> </li>
<li>
Cycle time is from the origin station on your own
bike. A "~" means it is estimated from the distance
at about 14 km/h; without a tilde it is TfL's cycle
route.
</li>
<li> <li>
Children 10 and under travel free on TfL; 11–15s pay Children 10 and under travel free on TfL; 11–15s pay
child fares with a Zip card (not included). child fares with a Zip card (not included).
@@ -528,6 +736,11 @@ onBeforeUnmount(() => {
letter-spacing: 0.05em; letter-spacing: 0.05em;
} }
.cachedTag.warn {
color: #ffd166;
border-color: currentColor;
}
.configGrid { .configGrid {
display: grid; display: grid;
grid-template-columns: repeat(2, 1fr); grid-template-columns: repeat(2, 1fr);
@@ -636,55 +849,123 @@ onBeforeUnmount(() => {
.summary { .summary {
color: var(--color-muted); color: var(--color-muted);
font-size: 0.9rem; font-size: 0.9rem;
margin-bottom: 0.75rem; margin-bottom: 0.6rem;
} }
.best { .progress {
display: flex; display: flex;
align-items: baseline; align-items: center;
gap: 0.75rem; gap: 0.75rem;
flex-wrap: wrap; margin-bottom: 0.9rem;
}
.progressBar {
flex: 1;
height: 4px;
background: rgba(2, 73, 66, 0.5);
}
.progressFill {
height: 100%;
background: var(--color-primary);
transition: width 0.3s ease;
}
.progressText {
font-family: monospace;
font-size: 0.8rem;
color: var(--color-muted);
white-space: nowrap;
}
.picks {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 0.6rem;
margin-bottom: 0.9rem;
}
.pick {
display: flex;
flex-direction: column;
gap: 0.15rem;
border: 1px solid var(--color-primary); border: 1px solid var(--color-primary);
padding: 0.5rem 0.75rem; padding: 0.5rem 0.75rem;
margin-bottom: 0.9rem;
background: rgba(85, 255, 187, 0.06); background: rgba(85, 255, 187, 0.06);
min-width: 0;
} }
.bestLabel { .pickLabel {
font-family: var(--font-heading); font-family: var(--font-heading);
letter-spacing: 0.05em; letter-spacing: 0.05em;
color: var(--color-primary); color: var(--color-primary);
font-size: 0.85rem;
} }
.bestName { .pickName {
color: #e5f4ee; color: #e5f4ee;
font-weight: bold; font-weight: bold;
text-decoration: none;
transition: color 0.15s ease;
} }
.bestMaths { .pickName:hover {
color: var(--color-tertiary);
}
.pickMaths {
font-family: monospace; font-family: monospace;
color: var(--color-muted); color: var(--color-secondary);
font-size: 0.9rem; font-size: 0.85rem;
} }
.bestMaths strong { .pickSub {
font-size: 0.78rem;
color: var(--color-muted);
}
.rankBar {
display: flex;
align-items: center;
gap: 0.4rem;
flex-wrap: wrap;
margin-bottom: 0.6rem;
}
.rankLabel {
font-family: var(--font-heading);
letter-spacing: 0.05em;
color: var(--color-muted);
font-size: 0.85rem;
margin-right: 0.2rem;
}
.rankBtn {
padding: 0.15rem 0.6rem;
border: 1px solid var(--color-quaternary);
color: var(--color-muted);
font-size: 0.8rem;
cursor: pointer;
transition:
color 0.15s ease,
border-color 0.15s ease;
}
.rankBtn:hover {
color: var(--color-primary); color: var(--color-primary);
} }
.bookLink, .rankBtn.active {
color: var(--color-primary);
border-color: var(--color-primary);
}
.hotelLink { .hotelLink {
color: var(--color-primary); color: var(--color-primary);
text-decoration: none; text-decoration: none;
transition: color 0.15s ease; transition: color 0.15s ease;
} }
.bookLink {
margin-left: auto;
font-family: var(--font-heading);
letter-spacing: 0.05em;
}
.bookLink:hover,
.hotelLink:hover { .hotelLink:hover {
color: var(--color-tertiary); color: var(--color-tertiary);
} }
@@ -711,6 +992,11 @@ onBeforeUnmount(() => {
white-space: nowrap; white-space: nowrap;
} }
.results th.sorted {
text-decoration: underline;
text-underline-offset: 3px;
}
.results td { .results td {
padding: 0.3rem 0.5rem; padding: 0.3rem 0.5rem;
border-bottom: 1px solid rgba(2, 73, 66, 0.4); border-bottom: 1px solid rgba(2, 73, 66, 0.4);
@@ -727,11 +1013,16 @@ onBeforeUnmount(() => {
color: var(--color-secondary); color: var(--color-secondary);
} }
.results .cycle {
color: var(--color-muted);
}
.results tr.best td { .results tr.best td {
background: rgba(85, 255, 187, 0.08); background: rgba(85, 255, 187, 0.08);
} }
.results tr.unpriced td { .results tr.unpriced td.total,
.results tr.unpriced td.route {
opacity: 0.6; opacity: 0.6;
} }
@@ -739,6 +1030,11 @@ onBeforeUnmount(() => {
color: var(--color-muted); color: var(--color-muted);
} }
.results .route.pending {
font-style: italic;
opacity: 0.5;
}
.fasterRow td { .fasterRow td {
border-bottom: 1px solid rgba(2, 73, 66, 0.4); border-bottom: 1px solid rgba(2, 73, 66, 0.4);
font-size: 0.8rem; font-size: 0.8rem;
@@ -782,12 +1078,9 @@ onBeforeUnmount(() => {
} }
@media (max-width: 640px) { @media (max-width: 640px) {
.configGrid { .configGrid,
.picks {
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
.bookLink {
margin-left: 0;
}
} }
</style> </style>