Add cheapest-night date-range scan to the Travelodge finder
Deploy with Docker Compose / deploy (push) Successful in 52s
Deploy with Docker Compose / deploy (push) Successful in 52s
A second "Cheapest night" tab on /hotels scans every candidate check-in between two dates (filtered by weekday, 1-7 nights, up to ~3 months), keeps the N cheapest hotels per night, and prices TfL transport once per unique hotel so the whole range fits in the streaming window. Backend - travelodge.py: extract _shortlist/_make_row/_price_hotels/_apply_transport from run_search; add a 30-minute per-(location, dates, rooms) Travelodge result cache, a deadline on page fetches, and run_scan (parallel date fetches with per-date failure isolation, one TfL lookup per hotel). - main.py: HotelRequestBase shared by search and scan requests, HotelScanRequest with weekday/range validation, scan event models, _guarded slot wrapper, POST /hotels/scan/stream (NDJSON). - nginx: the streaming location now matches /py/hotels/(search|scan). Frontend - Split CheapHotels.vue into SingleStayPanel, CheapestNightPanel, SharedFields, HotelRows, a shared form composable, stream/format helpers and hotels-shared.css; shared fields keep their values across tabs. - Vite dev server proxies /py to the Python API. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01H5P3C1HbbEwLZEYsjwr7uV
This commit is contained in:
@@ -264,8 +264,8 @@ http {
|
||||
return 301 /py/;
|
||||
}
|
||||
|
||||
# /py/hotels/search and /py/hotels/search/stream
|
||||
location ^~ /py/hotels/search {
|
||||
# /py/hotels/search[/stream] and /py/hotels/scan/stream: long-running NDJSON streams
|
||||
location ~ ^/py/hotels/(search|scan) {
|
||||
# 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;
|
||||
proxy_read_timeout 300s;
|
||||
|
||||
@@ -181,8 +181,8 @@ http {
|
||||
return 301 /py/;
|
||||
}
|
||||
|
||||
# /py/hotels/search and /py/hotels/search/stream
|
||||
location ^~ /py/hotels/search {
|
||||
# /py/hotels/search[/stream] and /py/hotels/scan/stream: long-running NDJSON streams
|
||||
location ~ ^/py/hotels/(search|scan) {
|
||||
# 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;
|
||||
proxy_read_timeout 300s;
|
||||
@@ -368,8 +368,8 @@ http {
|
||||
return 301 /py/;
|
||||
}
|
||||
|
||||
# /py/hotels/search and /py/hotels/search/stream
|
||||
location ^~ /py/hotels/search {
|
||||
# /py/hotels/search[/stream] and /py/hotels/scan/stream: long-running NDJSON streams
|
||||
location ~ ^/py/hotels/(search|scan) {
|
||||
# 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;
|
||||
proxy_read_timeout 300s;
|
||||
|
||||
+222
-42
@@ -57,6 +57,7 @@ def hello(name: str) -> Greeting:
|
||||
MAX_ROOMS = 4
|
||||
MAX_ADULTS = 8
|
||||
MAX_CHILDREN = 8
|
||||
MAX_SCAN_DAYS = travelodge.SCAN_MAX_DAYS
|
||||
CACHE_TTL_S = 10 * 60
|
||||
|
||||
_search_slot = threading.Semaphore(1)
|
||||
@@ -71,16 +72,14 @@ class Origin(BaseModel):
|
||||
lon: float
|
||||
|
||||
|
||||
class HotelSearchRequest(BaseModel):
|
||||
class HotelRequestBase(BaseModel):
|
||||
"""Fields shared by the single-stay search and the date-range scan."""
|
||||
|
||||
location: str = Field("Central London", min_length=1, max_length=80, description="Travelodge search text")
|
||||
checkin: date = Field(..., description="Check-in date (today or later)")
|
||||
checkout: Optional[date] = Field(None, description="Check-out date; overrides nights")
|
||||
nights: int = Field(1, ge=1, le=14, description="Used when checkout is not given")
|
||||
guests: str = Field("1", max_length=40, description='Rooms/guests e.g. "1", "2+1", "2,2+2"')
|
||||
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'")
|
||||
depart: str = Field("19:30", description="Outbound departure time HH:MM")
|
||||
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_travel_min: int = Field(75, ge=10, le=240, description="Ignore slower routes than this when picking cheapest")
|
||||
|
||||
@@ -120,6 +119,26 @@ class HotelSearchRequest(BaseModel):
|
||||
travelodge.parse_origin(v) # raises ValueError with a useful message
|
||||
return v.strip()
|
||||
|
||||
def shared_kwargs(self) -> dict:
|
||||
origin_name, origin = travelodge.parse_origin(self.origin)
|
||||
return {
|
||||
"location": self.location,
|
||||
"rooms": travelodge.parse_guests(self.guests),
|
||||
"railcard_holders": self.railcard_holders,
|
||||
"origin_name": origin_name,
|
||||
"origin": origin,
|
||||
"depart": self.depart,
|
||||
"max_miles": self.max_miles,
|
||||
"max_travel_min": self.max_travel_min,
|
||||
}
|
||||
|
||||
|
||||
class HotelSearchRequest(HotelRequestBase):
|
||||
checkin: date = Field(..., description="Check-in date (today or later)")
|
||||
checkout: Optional[date] = Field(None, description="Check-out date; overrides nights")
|
||||
nights: int = Field(1, ge=1, le=14, description="Used when checkout is not given")
|
||||
top: int = Field(20, ge=1, le=40, description="Price transport for the N cheapest stays only")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_dates(self):
|
||||
if self.checkin < date.today():
|
||||
@@ -134,6 +153,42 @@ class HotelSearchRequest(BaseModel):
|
||||
return self
|
||||
|
||||
|
||||
class HotelScanRequest(HotelRequestBase):
|
||||
start: date = Field(..., description="First candidate check-in date (today or later)")
|
||||
end: date = Field(..., description=f"Last candidate check-in date, at most {MAX_SCAN_DAYS} days after start")
|
||||
weekdays: list[int] = Field(
|
||||
default_factory=lambda: list(range(7)),
|
||||
description="Check-in weekdays to consider, 0=Mon .. 6=Sun (default all)",
|
||||
)
|
||||
nights: int = Field(1, ge=1, le=7, description="Length of each candidate stay")
|
||||
per_night: int = Field(5, ge=1, le=10, description="Keep the N cheapest hotels for each night")
|
||||
|
||||
@field_validator("weekdays")
|
||||
@classmethod
|
||||
def _check_weekdays(cls, v: list[int]) -> list[int]:
|
||||
days = []
|
||||
for d in v:
|
||||
if d < 0 or d > 6:
|
||||
raise ValueError("weekdays must be 0 (Mon) to 6 (Sun)")
|
||||
if d not in days:
|
||||
days.append(d)
|
||||
if not days:
|
||||
raise ValueError("pick at least one weekday")
|
||||
return days
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_dates(self):
|
||||
if self.start < date.today():
|
||||
raise ValueError("start must be today or later")
|
||||
if self.end < self.start:
|
||||
raise ValueError("end must be on or after start")
|
||||
if (self.end - self.start).days > MAX_SCAN_DAYS:
|
||||
raise ValueError(f"scans are limited to {MAX_SCAN_DAYS} days")
|
||||
if not travelodge.candidate_checkins(self.start, self.end, set(self.weekdays), self.nights):
|
||||
raise ValueError("no dates in the range match those weekdays")
|
||||
return self
|
||||
|
||||
|
||||
class HotelRow(BaseModel):
|
||||
code: Optional[str] = None
|
||||
name: Optional[str] = None
|
||||
@@ -204,6 +259,73 @@ class HotelSearchEvent(BaseModel):
|
||||
detail: Optional[str] = None
|
||||
|
||||
|
||||
class TransportFields(BaseModel):
|
||||
"""Transport and cycling columns for one hotel, independent of the night."""
|
||||
|
||||
code: str
|
||||
transport_out: Optional[float] = None
|
||||
transport_return: Optional[float] = None
|
||||
transport_total: Optional[float] = None
|
||||
travel_minutes: Optional[int] = None
|
||||
route: str
|
||||
fastest_minutes: Optional[int] = None
|
||||
fastest_total: Optional[float] = None
|
||||
fastest_route: Optional[str] = None
|
||||
cycle_minutes: Optional[int] = None
|
||||
cycle_km: Optional[float] = None
|
||||
cycle_source: str = "estimate"
|
||||
|
||||
|
||||
class NightRow(BaseModel):
|
||||
checkin: date
|
||||
checkout: date
|
||||
status: str = Field("pending", description='"pending", "ok", "failed" or "skipped"')
|
||||
detail: Optional[str] = Field(None, description="Why a night failed or was skipped")
|
||||
hotels_available: int = 0
|
||||
hotels: list[HotelRow] = Field(default_factory=list, description="Cheapest per_night hotels for this night")
|
||||
best_total: Optional[float] = None
|
||||
best_room: Optional[float] = None
|
||||
best_code: Optional[str] = None
|
||||
|
||||
|
||||
class HotelScanSummary(BaseModel):
|
||||
location: str
|
||||
start: date
|
||||
end: date
|
||||
weekdays: list[int]
|
||||
nights: int
|
||||
per_night: int
|
||||
rooms: int
|
||||
adults: int
|
||||
children: int
|
||||
railcard_holders: int
|
||||
origin_name: str
|
||||
origin_lat: float
|
||||
origin_lon: float
|
||||
depart: datetime
|
||||
max_travel_min: int
|
||||
nights_candidate: int
|
||||
nights_fetched: int = 0
|
||||
nights_failed: int = 0
|
||||
nights_skipped: int = 0
|
||||
hotels_unique: int = 0
|
||||
hotels_priced: int = 0
|
||||
tfl_rate_per_min: int = 0
|
||||
truncated: bool = False
|
||||
|
||||
|
||||
class HotelScanEvent(BaseModel):
|
||||
"""One line of the NDJSON stream from /hotels/scan/stream."""
|
||||
|
||||
event: str = Field(..., description='"scan", "night", "transport", "done" or "error"')
|
||||
summary: Optional[HotelScanSummary] = None
|
||||
nights: Optional[list[NightRow]] = None
|
||||
night: Optional[NightRow] = None
|
||||
transport: Optional[TransportFields] = None
|
||||
cached: bool = False
|
||||
detail: Optional[str] = None
|
||||
|
||||
|
||||
def _cache_get(key):
|
||||
now = time.monotonic()
|
||||
with _cache_lock:
|
||||
@@ -222,37 +344,46 @@ def _cache_put(key, result):
|
||||
_cache[key] = (now + CACHE_TTL_S, result)
|
||||
|
||||
|
||||
def _search_events(req: HotelSearchRequest):
|
||||
"""Yield HotelSearchEvent objects for a request, serving from cache when possible.
|
||||
ALREADY_RUNNING = "A search is already running, try again in a minute."
|
||||
|
||||
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.
|
||||
|
||||
def _guarded(run, make_error):
|
||||
"""Run a live search generator while holding the single search slot.
|
||||
|
||||
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)
|
||||
if not _search_slot.acquire(blocking=False):
|
||||
yield make_error(ALREADY_RUNNING)
|
||||
return
|
||||
try:
|
||||
yield from run()
|
||||
except travelodge.UpstreamError as e:
|
||||
yield make_error(str(e))
|
||||
except (KeyError, TypeError) as e:
|
||||
yield make_error(f"Unexpected upstream response: {e}")
|
||||
except ValueError as e:
|
||||
yield make_error(str(e))
|
||||
finally:
|
||||
_search_slot.release()
|
||||
|
||||
|
||||
def _search_events(req: HotelSearchRequest):
|
||||
"""Yield HotelSearchEvent objects for a request, serving from cache when possible."""
|
||||
key = "search:" + 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):
|
||||
yield HotelSearchEvent(event="error", detail="A search is already running, try again in a minute.")
|
||||
return
|
||||
try:
|
||||
origin_name, origin = travelodge.parse_origin(req.origin)
|
||||
def run():
|
||||
gen = travelodge.run_search(
|
||||
location=req.location,
|
||||
checkin=req.checkin,
|
||||
checkout=req.checkout,
|
||||
rooms=travelodge.parse_guests(req.guests),
|
||||
railcard_holders=req.railcard_holders,
|
||||
origin_name=origin_name,
|
||||
origin=origin,
|
||||
depart=req.depart,
|
||||
top=req.top,
|
||||
max_miles=req.max_miles,
|
||||
max_travel_min=req.max_travel_min,
|
||||
**req.shared_kwargs(),
|
||||
)
|
||||
for ev in gen:
|
||||
if ev[0] == "transport":
|
||||
@@ -262,22 +393,62 @@ def _search_events(req: HotelSearchRequest):
|
||||
if kind == "done":
|
||||
_cache_put(key, {"summary": summary, "rows": rows})
|
||||
yield HotelSearchEvent(event=kind, summary=summary, rows=rows)
|
||||
except travelodge.UpstreamError as e:
|
||||
yield HotelSearchEvent(event="error", detail=str(e))
|
||||
except (KeyError, TypeError) as e:
|
||||
yield HotelSearchEvent(event="error", detail=f"Unexpected upstream response: {e}")
|
||||
except ValueError as e:
|
||||
yield HotelSearchEvent(event="error", detail=str(e))
|
||||
finally:
|
||||
_search_slot.release()
|
||||
|
||||
yield from _guarded(run, lambda detail: HotelSearchEvent(event="error", detail=detail))
|
||||
|
||||
|
||||
def _scan_events(req: HotelScanRequest):
|
||||
"""Yield HotelScanEvent objects for a scan, serving from cache when possible."""
|
||||
key = "scan:" + json.dumps(req.model_dump(mode="json"), sort_keys=True)
|
||||
hit = _cache_get(key)
|
||||
if hit:
|
||||
yield HotelScanEvent(event="scan", cached=True, **hit)
|
||||
yield HotelScanEvent(event="done", cached=True, **hit)
|
||||
return
|
||||
|
||||
def run():
|
||||
gen = travelodge.run_scan(
|
||||
start=req.start,
|
||||
end=req.end,
|
||||
weekdays=set(req.weekdays),
|
||||
nights=req.nights,
|
||||
per_night=req.per_night,
|
||||
**req.shared_kwargs(),
|
||||
)
|
||||
for kind, summary, payload in gen:
|
||||
if kind == "night":
|
||||
yield HotelScanEvent(event=kind, summary=summary, night=payload)
|
||||
elif kind == "transport":
|
||||
yield HotelScanEvent(event=kind, summary=summary, transport=payload)
|
||||
else:
|
||||
if kind == "done":
|
||||
_cache_put(key, {"summary": summary, "nights": payload})
|
||||
yield HotelScanEvent(event=kind, summary=summary, nights=payload)
|
||||
|
||||
yield from _guarded(run, lambda detail: HotelScanEvent(event="error", detail=detail))
|
||||
|
||||
|
||||
_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."
|
||||
"about a minute. Only one live search or scan runs at a time; identical requests are cached for ten minutes."
|
||||
)
|
||||
|
||||
_SCAN_DESCRIPTION = (
|
||||
"Searches Travelodge once per candidate check-in date in `start`..`end` (filtered by `weekdays`), keeps the "
|
||||
"`per_night` cheapest hotels for each, then prices TfL transport once per unique hotel at the first "
|
||||
"night's departure time and reuses it for every night. Up to about three months; a scan can take a few "
|
||||
"minutes and shares the single live-search slot with /hotels/search. Identical scans are cached for ten minutes."
|
||||
)
|
||||
|
||||
|
||||
def _ndjson(events):
|
||||
return StreamingResponse(
|
||||
(ev.model_dump_json(exclude_none=True) + "\n" for ev in events),
|
||||
media_type="application/x-ndjson",
|
||||
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
|
||||
|
||||
@app.post(
|
||||
"/hotels/search",
|
||||
@@ -290,7 +461,7 @@ 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
|
||||
status = 429 if ev.detail == ALREADY_RUNNING else 502
|
||||
raise HTTPException(status_code=status, detail=ev.detail)
|
||||
if ev.event == "done":
|
||||
final = ev
|
||||
@@ -312,12 +483,21 @@ def hotel_search(req: HotelSearchRequest) -> HotelSearchResponse:
|
||||
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 _ndjson(_search_events(req))
|
||||
|
||||
return StreamingResponse(
|
||||
lines(),
|
||||
media_type="application/x-ndjson",
|
||||
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
|
||||
@app.post(
|
||||
"/hotels/scan/stream",
|
||||
summary="Find the cheapest night to stay across a date range",
|
||||
description=(
|
||||
"Newline-delimited JSON (`application/x-ndjson`). Each line is a `HotelScanEvent`: first `scan` "
|
||||
"(every candidate night, pending), then one `night` line per date as Travelodge answers (its cheapest "
|
||||
"hotels, transport unpriced), then one `transport` line per unique hotel as TfL fares arrive (apply it "
|
||||
"to every night containing that hotel code), then `done` (totals filled in, nights sorted by best "
|
||||
"total). An `error` line ends a failed stream. " + _SCAN_DESCRIPTION
|
||||
),
|
||||
response_class=StreamingResponse,
|
||||
responses={200: {"content": {"application/x-ndjson": {"schema": HotelScanEvent.model_json_schema()}}}},
|
||||
)
|
||||
def hotel_scan_stream(req: HotelScanRequest):
|
||||
return _ndjson(_scan_events(req))
|
||||
|
||||
+346
-63
@@ -36,7 +36,7 @@ import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from datetime import date, datetime
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import requests
|
||||
|
||||
@@ -67,6 +67,20 @@ LONDON_BOX = (51.25, 51.75, -0.55, 0.35) # min lat, max lat, min lon, max lon
|
||||
# 300s, so stop pricing transport well before that and return what we have.
|
||||
SEARCH_DEADLINE_S = 200
|
||||
|
||||
# A date-range scan fetches one Travelodge search per candidate night, then
|
||||
# prices TfL once per unique hotel. Stop starting new date fetches after the
|
||||
# soft deadline; stop TfL pricing at the hard one and return what we have.
|
||||
SCAN_FETCH_DEADLINE_S = 150
|
||||
SCAN_DEADLINE_S = 240
|
||||
SCAN_DATE_WORKERS = int(os.environ.get("TL_SCAN_WORKERS", "4"))
|
||||
SCAN_MAX_DAYS = 91
|
||||
|
||||
# Normalised Travelodge results are cached per (location, dates, rooms) so a
|
||||
# re-scan with different weekday/transport settings is free on the Travelodge
|
||||
# side. Prices may therefore be up to TL_CACHE_TTL_S old.
|
||||
TL_CACHE_TTL_S = 30 * 60
|
||||
TL_CACHE_MAX = 600
|
||||
|
||||
# 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
|
||||
@@ -88,7 +102,10 @@ 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))
|
||||
_session.mount(
|
||||
"https://",
|
||||
requests.adapters.HTTPAdapter(pool_connections=4, pool_maxsize=TFL_WORKERS + SCAN_DATE_WORKERS * TL_PAGE_BATCH),
|
||||
)
|
||||
|
||||
|
||||
class UpstreamError(Exception):
|
||||
@@ -138,20 +155,24 @@ def parse_origin(spec):
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Travelodge
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _fetch_page(params, start):
|
||||
def _fetch_page(params, start, deadline=None):
|
||||
p = dict(params, start=start)
|
||||
timeout = 30
|
||||
if deadline is not None:
|
||||
timeout = max(1, min(timeout, deadline - time.monotonic()))
|
||||
try:
|
||||
r = _session.get(TL_API, params=p, headers=HEADERS, timeout=30)
|
||||
r = _session.get(TL_API, params=p, headers=HEADERS, timeout=timeout)
|
||||
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):
|
||||
def fetch_hotels(location, checkin, checkout, rooms, deadline=None):
|
||||
"""Return list of hotel dicts from the Travelodge search API (all pages).
|
||||
|
||||
rooms: list of (adults, children) tuples, one per room.
|
||||
deadline: time.monotonic() value after which page requests are cut short.
|
||||
"""
|
||||
params = {
|
||||
"pagination": "false",
|
||||
@@ -174,7 +195,7 @@ def fetch_hotels(location, checkin, checkout, rooms):
|
||||
return bool(new)
|
||||
|
||||
# First page alone: tells us whether the search matched anything at all.
|
||||
first = _fetch_page(params, 0)
|
||||
first = _fetch_page(params, 0, deadline)
|
||||
if not absorb(first) or len(first) < TL_PAGE_SIZE:
|
||||
return hotels
|
||||
|
||||
@@ -182,7 +203,7 @@ def fetch_hotels(location, checkin, checkout, rooms):
|
||||
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))
|
||||
pages = list(ex.map(lambda s: _fetch_page(params, s, deadline), starts))
|
||||
got_new = False
|
||||
exhausted = False
|
||||
for page in pages: # keep API order so ranking stays stable
|
||||
@@ -212,6 +233,35 @@ def normalise_hotel(h):
|
||||
}
|
||||
|
||||
|
||||
_tl_cache = {} # (location, checkin, checkout, rooms) -> (expires_at, [normalised hotel dicts])
|
||||
_tl_cache_lock = threading.Lock()
|
||||
|
||||
|
||||
def hotels_for(location, checkin, checkout, rooms, deadline=None):
|
||||
"""Normalised hotel list for a search, cached for TL_CACHE_TTL_S.
|
||||
|
||||
Failures are not cached. Callers must treat the returned dicts as read-only.
|
||||
"""
|
||||
key = (location.strip().lower(), checkin, checkout, tuple(rooms))
|
||||
now = time.monotonic()
|
||||
with _tl_cache_lock:
|
||||
hit = _tl_cache.get(key)
|
||||
if hit and hit[0] > now:
|
||||
return hit[1]
|
||||
|
||||
hotels = [normalise_hotel(h) for h in fetch_hotels(location, checkin, checkout, rooms, deadline=deadline)]
|
||||
|
||||
with _tl_cache_lock:
|
||||
now = time.monotonic()
|
||||
expired = [k for k, (exp, _) in _tl_cache.items() if exp <= now]
|
||||
for k in expired:
|
||||
del _tl_cache[k]
|
||||
while len(_tl_cache) >= TL_CACHE_MAX:
|
||||
del _tl_cache[next(iter(_tl_cache))] # oldest insertion
|
||||
_tl_cache[key] = (now + TL_CACHE_TTL_S, hotels)
|
||||
return hotels
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Geometry
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -479,6 +529,8 @@ _UNPRICED = {
|
||||
"total": None,
|
||||
}
|
||||
|
||||
TIME_LIMIT_ROUTE = "not priced (time limit)"
|
||||
|
||||
|
||||
def _transport_fields(hotel, t):
|
||||
if not t:
|
||||
@@ -500,6 +552,79 @@ def sort_rows(rows):
|
||||
rows.sort(key=lambda r: (r["total"] is None, r["total"] or 0, r["room_price"]))
|
||||
|
||||
|
||||
def _shortlist(hotels, max_miles, top):
|
||||
"""(available, shortlist): bookable, priced, geocoded hotels within max_miles
|
||||
sorted by room price, and the cheapest `top` of them."""
|
||||
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:
|
||||
avail = [h for h in avail if (h["distance_from_search_mi"] or 0) <= max_miles]
|
||||
avail.sort(key=lambda h: h["room_price"])
|
||||
return avail, avail[:top]
|
||||
|
||||
|
||||
def _make_row(h, origin):
|
||||
"""Result row for a hotel: unpriced transport plus an estimated cycle time."""
|
||||
row = dict(h, **_UNPRICED, route="pricing…")
|
||||
est_min, est_km = estimate_cycle(origin, (h["lat"], h["lon"]))
|
||||
row.update({"cycle_minutes": est_min, "cycle_km": est_km, "cycle_source": "estimate"})
|
||||
return row
|
||||
|
||||
|
||||
def _price_hotels(hotels, origin, depart_dt, adults, railcard_holders, max_travel_min, app_key, deadline):
|
||||
"""Price TfL transport for each hotel, cheapest rooms first.
|
||||
|
||||
Generator of (code, transport_or_None, cycle_or_None, timed_out) in the order
|
||||
TfL answers. Owns the worker pools; leftover work is cancelled if the
|
||||
consumer stops early.
|
||||
"""
|
||||
with ThreadPoolExecutor(max_workers=TFL_WORKERS) as tfl_pool, \
|
||||
ThreadPoolExecutor(max_workers=TFL_HOTEL_WORKERS) as hotel_pool:
|
||||
|
||||
def price(h):
|
||||
# Kick off the cycle lookup first so it overlaps the fare lookups.
|
||||
cycle_fut = None
|
||||
if app_key:
|
||||
cycle_fut = tfl_pool.submit(
|
||||
tfl_journeys, origin, (h["lat"], h["lon"]), depart_dt, CYCLE_QUERY, app_key, deadline=deadline
|
||||
)
|
||||
t = best_transport(origin, h, depart_dt, adults, railcard_holders, max_travel_min, app_key,
|
||||
deadline=deadline, pool=tfl_pool)
|
||||
cyc = None
|
||||
if cycle_fut is not None:
|
||||
cyc = cycle_time(origin, h, depart_dt, app_key, deadline=deadline, journeys=cycle_fut.result())
|
||||
return h["code"], t, cyc
|
||||
|
||||
futures = [hotel_pool.submit(price, h) for h in hotels]
|
||||
try:
|
||||
for fut in as_completed(futures):
|
||||
code, t, cyc = fut.result()
|
||||
timed_out = t is None and time.monotonic() >= deadline
|
||||
yield code, t, cyc, timed_out
|
||||
finally:
|
||||
for f in futures:
|
||||
f.cancel()
|
||||
|
||||
|
||||
def _apply_transport(row, t, cyc, timed_out):
|
||||
row.update(_transport_fields(row, t))
|
||||
if timed_out:
|
||||
row["route"] = TIME_LIMIT_ROUTE
|
||||
if cyc:
|
||||
row["cycle_minutes"], row["cycle_km"], row["cycle_source"] = cyc
|
||||
return row
|
||||
|
||||
|
||||
def _party(rooms, railcard_holders):
|
||||
adults = sum(a for a, _ in rooms)
|
||||
children = sum(c for _, c in rooms)
|
||||
return adults, children, max(0, min(adults, railcard_holders))
|
||||
|
||||
|
||||
def _depart_dt(day, depart):
|
||||
hh, mm = map(int, depart.split(":"))
|
||||
return datetime(day.year, day.month, day.day, hh, mm)
|
||||
|
||||
|
||||
def run_search(
|
||||
*,
|
||||
location: str,
|
||||
@@ -523,31 +648,16 @@ def run_search(
|
||||
("done", summary, rows) final summary and rows sorted by total
|
||||
"""
|
||||
nights = (checkout - checkin).days
|
||||
adults = sum(a for a, _ in rooms)
|
||||
children = sum(c for _, c in rooms)
|
||||
railcard_holders = max(0, min(adults, railcard_holders))
|
||||
hh, mm = map(int, depart.split(":"))
|
||||
depart_dt = datetime(checkin.year, checkin.month, checkin.day, hh, mm)
|
||||
adults, children, railcard_holders = _party(rooms, railcard_holders)
|
||||
depart_dt = _depart_dt(checkin, depart)
|
||||
app_key = os.environ.get("TFL_APP_KEY") or None
|
||||
deadline = time.monotonic() + SEARCH_DEADLINE_S
|
||||
|
||||
raw = fetch_hotels(location, checkin, checkout, rooms)
|
||||
hotels = [normalise_hotel(h) for h in raw]
|
||||
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:
|
||||
avail = [h for h in avail if (h["distance_from_search_mi"] or 0) <= max_miles]
|
||||
hotels = hotels_for(location, checkin, checkout, rooms, deadline=deadline)
|
||||
avail, shortlist = _shortlist(hotels, max_miles, top)
|
||||
|
||||
avail.sort(key=lambda h: h["room_price"])
|
||||
shortlist = avail[:top]
|
||||
|
||||
rows = []
|
||||
by_code = {}
|
||||
for h in shortlist:
|
||||
row = dict(h, **_UNPRICED, route="pricing…")
|
||||
est_min, est_km = estimate_cycle(origin, (h["lat"], h["lon"]))
|
||||
row.update({"cycle_minutes": est_min, "cycle_km": est_km, "cycle_source": "estimate"})
|
||||
rows.append(row)
|
||||
by_code[row["code"]] = row
|
||||
rows = [_make_row(h, origin) for h in shortlist]
|
||||
by_code = {row["code"]: row for row in rows}
|
||||
|
||||
summary = {
|
||||
"location": location,
|
||||
@@ -572,46 +682,219 @@ def run_search(
|
||||
}
|
||||
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_HOTEL_WORKERS) as hotel_pool:
|
||||
|
||||
def price(h):
|
||||
# Kick off the cycle lookup first so it overlaps the fare lookups. One
|
||||
# attempt only: TfL can take 15s+ to say there is no cycle route (e.g.
|
||||
# motorway services), and the distance estimate is a fine fallback.
|
||||
cycle_fut = None
|
||||
if app_key:
|
||||
cycle_fut = tfl_pool.submit(
|
||||
tfl_journeys, origin, (h["lat"], h["lon"]), depart_dt, CYCLE_QUERY, app_key,
|
||||
retries=1, deadline=deadline,
|
||||
)
|
||||
t = best_transport(origin, h, depart_dt, adults, railcard_holders, max_travel_min, app_key,
|
||||
deadline=deadline, pool=tfl_pool)
|
||||
cyc = None
|
||||
if cycle_fut is not None:
|
||||
cyc = cycle_time(origin, h, depart_dt, app_key, deadline=deadline, journeys=cycle_fut.result())
|
||||
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]
|
||||
for code, t, cyc, timed_out in _price_hotels(
|
||||
shortlist, origin, depart_dt, adults, railcard_holders, max_travel_min, app_key, deadline
|
||||
):
|
||||
row = _apply_transport(by_code[code], t, cyc, timed_out)
|
||||
if timed_out:
|
||||
summary["truncated"] = True
|
||||
summary["hotels_priced"] += 1
|
||||
yield "transport", dict(row)
|
||||
|
||||
sort_rows(rows)
|
||||
yield "done", dict(summary), [dict(r) for r in rows]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Date-range scan
|
||||
# --------------------------------------------------------------------------- #
|
||||
def candidate_checkins(start, end, weekdays, nights):
|
||||
"""[(checkin, checkout)] for every day start..end (inclusive) whose weekday
|
||||
(0=Mon) is in `weekdays`, each for a stay of `nights` nights."""
|
||||
out = []
|
||||
day = start
|
||||
while day <= end:
|
||||
if day.weekday() in weekdays:
|
||||
out.append((day, day + timedelta(days=nights)))
|
||||
day += timedelta(days=1)
|
||||
return out
|
||||
|
||||
|
||||
def _copy_night(n):
|
||||
return dict(n, hotels=[dict(r) for r in n["hotels"]])
|
||||
|
||||
|
||||
def run_scan(
|
||||
*,
|
||||
location: str,
|
||||
start: date,
|
||||
end: date,
|
||||
weekdays,
|
||||
nights: int,
|
||||
per_night: int,
|
||||
rooms: list,
|
||||
railcard_holders: int,
|
||||
origin_name: str,
|
||||
origin: tuple,
|
||||
depart: str,
|
||||
max_miles,
|
||||
max_travel_min: int,
|
||||
):
|
||||
"""Generator of progress events for a cheapest-night scan.
|
||||
|
||||
Every candidate check-in in start..end (filtered by weekday) is searched on
|
||||
Travelodge and its `per_night` cheapest rooms kept. TfL transport is then
|
||||
priced ONCE per unique hotel, at the first candidate night's departure
|
||||
time, and reused for every night that hotel appears in.
|
||||
|
||||
Yields, in order:
|
||||
("scan", summary, nights) every candidate night, status "pending"
|
||||
("night", summary, night) one per night as Travelodge answers:
|
||||
status ok/failed/skipped, hotels sorted
|
||||
by room price, transport unpriced
|
||||
("transport", summary, fields) one per unique hotel as TfL answers;
|
||||
`fields` has the hotel code plus the
|
||||
transport and cycle columns
|
||||
("done", summary, nights) totals filled in, hotels sorted by
|
||||
total, nights sorted by best total
|
||||
"""
|
||||
candidates = candidate_checkins(start, end, weekdays, nights)
|
||||
if not candidates:
|
||||
raise ValueError("no dates in the range match those weekdays")
|
||||
adults, children, railcard_holders = _party(rooms, railcard_holders)
|
||||
depart_dt = _depart_dt(candidates[0][0], depart)
|
||||
app_key = os.environ.get("TFL_APP_KEY") or None
|
||||
t0 = time.monotonic()
|
||||
fetch_deadline = t0 + SCAN_FETCH_DEADLINE_S
|
||||
deadline = t0 + SCAN_DEADLINE_S
|
||||
|
||||
night_list = [
|
||||
{
|
||||
"checkin": ci,
|
||||
"checkout": co,
|
||||
"status": "pending",
|
||||
"detail": None,
|
||||
"hotels_available": 0,
|
||||
"hotels": [],
|
||||
"best_total": None,
|
||||
"best_room": None,
|
||||
"best_code": None,
|
||||
}
|
||||
for ci, co in candidates
|
||||
]
|
||||
by_checkin = {n["checkin"]: n for n in night_list}
|
||||
|
||||
summary = {
|
||||
"location": location,
|
||||
"start": start,
|
||||
"end": end,
|
||||
"weekdays": sorted(weekdays),
|
||||
"nights": nights,
|
||||
"per_night": per_night,
|
||||
"rooms": len(rooms),
|
||||
"adults": adults,
|
||||
"children": children,
|
||||
"railcard_holders": railcard_holders,
|
||||
"origin_name": origin_name,
|
||||
"origin_lat": origin[0],
|
||||
"origin_lon": origin[1],
|
||||
"depart": depart_dt,
|
||||
"max_travel_min": max_travel_min,
|
||||
"nights_candidate": len(night_list),
|
||||
"nights_fetched": 0,
|
||||
"nights_failed": 0,
|
||||
"nights_skipped": 0,
|
||||
"hotels_unique": 0,
|
||||
"hotels_priced": 0,
|
||||
"tfl_rate_per_min": TFL_RATE_KEYED if app_key else TFL_RATE_ANON,
|
||||
"truncated": False,
|
||||
}
|
||||
yield "scan", dict(summary), [_copy_night(n) for n in night_list]
|
||||
|
||||
# Phase 1: room prices, a few nights at a time. One bad night must not
|
||||
# sink the scan, so upstream failures are recorded on that night only.
|
||||
def fetch_night(ci, co):
|
||||
if time.monotonic() > fetch_deadline:
|
||||
return ci, "skipped", [], 0, "not fetched (time limit)"
|
||||
try:
|
||||
hotels = hotels_for(location, ci, co, rooms, deadline=fetch_deadline + 30)
|
||||
except UpstreamError as e:
|
||||
return ci, "failed", [], 0, str(e)
|
||||
avail, short = _shortlist(hotels, max_miles, per_night)
|
||||
return ci, "ok", short, len(avail), None
|
||||
|
||||
with ThreadPoolExecutor(max_workers=SCAN_DATE_WORKERS) as ex:
|
||||
futures = [ex.submit(fetch_night, ci, co) for ci, co in candidates]
|
||||
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)"
|
||||
ci, status, short, n_avail, detail = fut.result()
|
||||
night = by_checkin[ci]
|
||||
night["status"] = status
|
||||
night["detail"] = detail
|
||||
night["hotels_available"] = n_avail
|
||||
if status == "ok":
|
||||
night["hotels"] = [_make_row(h, origin) for h in short]
|
||||
if night["hotels"]:
|
||||
night["best_room"] = night["hotels"][0]["room_price"]
|
||||
summary["nights_fetched"] += 1
|
||||
elif status == "failed":
|
||||
summary["nights_failed"] += 1
|
||||
else:
|
||||
summary["nights_skipped"] += 1
|
||||
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)
|
||||
yield "night", dict(summary), _copy_night(night)
|
||||
finally:
|
||||
for f in futures:
|
||||
f.cancel()
|
||||
|
||||
sort_rows(rows)
|
||||
yield "done", dict(summary), [dict(r) for r in rows]
|
||||
# Phase 2: one TfL price per unique hotel. Hotels that are cheapest on some
|
||||
# night go first, since they are the likely winners if time runs out.
|
||||
index = {} # code -> ((best rank, min room price), row)
|
||||
for n in night_list:
|
||||
for rank, row in enumerate(n["hotels"]):
|
||||
key = (rank, row["room_price"])
|
||||
cur = index.get(row["code"])
|
||||
if cur is None or key < cur[0]:
|
||||
index[row["code"]] = (key, row)
|
||||
ordered = [row for _, row in sorted(index.values(), key=lambda x: x[0])]
|
||||
summary["hotels_unique"] = len(ordered)
|
||||
|
||||
transport = {} # code -> transport + cycle fields
|
||||
for code, t, cyc, timed_out in _price_hotels(
|
||||
ordered, origin, depart_dt, adults, railcard_holders, max_travel_min, app_key, deadline
|
||||
):
|
||||
base = index[code][1]
|
||||
fields = _transport_fields({"room_price": 0}, t)
|
||||
fields.pop("total", None)
|
||||
if timed_out:
|
||||
fields["route"] = TIME_LIMIT_ROUTE
|
||||
summary["truncated"] = True
|
||||
if cyc:
|
||||
fields["cycle_minutes"], fields["cycle_km"], fields["cycle_source"] = cyc
|
||||
else:
|
||||
fields.update({k: base[k] for k in ("cycle_minutes", "cycle_km", "cycle_source")})
|
||||
fields["code"] = code
|
||||
transport[code] = fields
|
||||
summary["hotels_priced"] += 1
|
||||
yield "transport", dict(summary), dict(fields)
|
||||
|
||||
# Phase 3: totals per night.
|
||||
for n in night_list:
|
||||
if n["status"] != "ok":
|
||||
continue
|
||||
for row in n["hotels"]:
|
||||
fields = transport.get(row["code"])
|
||||
if fields is None:
|
||||
row["route"] = TIME_LIMIT_ROUTE
|
||||
continue
|
||||
row.update({k: v for k, v in fields.items() if k != "code"})
|
||||
if row["transport_total"] is not None:
|
||||
row["total"] = round(row["room_price"] + row["transport_total"], 2)
|
||||
sort_rows(n["hotels"])
|
||||
if n["hotels"]:
|
||||
best = n["hotels"][0]
|
||||
n["best_total"] = best["total"]
|
||||
n["best_code"] = best["code"]
|
||||
n["best_room"] = min(r["room_price"] for r in n["hotels"])
|
||||
|
||||
night_list.sort(
|
||||
key=lambda n: (
|
||||
n["best_total"] is None,
|
||||
n["best_total"] or 0,
|
||||
n["best_room"] is None,
|
||||
n["best_room"] or 0,
|
||||
n["checkin"],
|
||||
)
|
||||
)
|
||||
yield "done", dict(summary), [_copy_night(n) for n in night_list]
|
||||
|
||||
@@ -28,6 +28,7 @@ Everything visual is defined in three places:
|
||||
| `src/assets/styles.css` | Fonts, **design tokens**, default element styles (dark theme), reusable classes (`bdr-1`, `bdr-2`, `page-a4`, `halftone`), the `slide` and `fade` transitions, print rules |
|
||||
| `src/layouts/CVLayout.vue` | The **light theme** for `/cv` and `/cv/jobs`: re-points the colour tokens to ink-on-paper values and holds the shared `.cv-btn` styles |
|
||||
| `src/views/CV/cv-shared.css` | Typography and page layout for the CV templates (`.cv-template`, `.cv-page`, `--cv-*` size variables) |
|
||||
| `src/views/hotels/hotels-shared.css` | Panels, forms, tables and tab strip for `/hotels`, shared by the single-stay and cheapest-night panels; every selector is prefixed with the page's `.hotels` root class |
|
||||
|
||||
### Tokens
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,581 @@
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
|
||||
import SharedFields from "./SharedFields.vue";
|
||||
import HotelRows from "./HotelRows.vue";
|
||||
import { runStream } from "./hotelsStream.js";
|
||||
import { todayIso, addDays, loadFrom, saveTo } from "./useHotelForm.js";
|
||||
import {
|
||||
gbp,
|
||||
fmtDate,
|
||||
fmtTime,
|
||||
cycleText,
|
||||
byNumber,
|
||||
byRoom,
|
||||
byTotal,
|
||||
PENDING_ROUTE,
|
||||
} from "./hotelsFormat.js";
|
||||
|
||||
const props = defineProps({
|
||||
form: { type: Object, required: true },
|
||||
});
|
||||
|
||||
const SCAN_KEY = "cheap-hotels-scan";
|
||||
const MAX_SPAN_DAYS = 91;
|
||||
const DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
|
||||
const ALL_DAYS = [0, 1, 2, 3, 4, 5, 6];
|
||||
const WEEKEND = [4, 5];
|
||||
|
||||
const RANKINGS = [
|
||||
{ key: "total", label: "Stay + transport" },
|
||||
{ key: "room", label: "Stay only" },
|
||||
{ key: "date", label: "Date" },
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Form state (this panel's own fields; shared ones live in props.form)
|
||||
// ---------------------------------------------------------------------------
|
||||
const start = ref(todayIso());
|
||||
const end = ref(addDays(start.value, 60));
|
||||
const weekdays = ref([...ALL_DAYS]);
|
||||
const nights = ref(1);
|
||||
const perNight = ref(5);
|
||||
const rankBy = ref("total");
|
||||
|
||||
const endMax = computed(() => addDays(start.value, MAX_SPAN_DAYS));
|
||||
|
||||
function setDays(list) {
|
||||
weekdays.value = [...list];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Scan state
|
||||
// ---------------------------------------------------------------------------
|
||||
const searching = ref(false);
|
||||
const errorMsg = ref("");
|
||||
const summary = ref(null);
|
||||
const nightRows = ref([]);
|
||||
const cached = ref(false);
|
||||
const done = ref(false);
|
||||
const elapsed = ref(0);
|
||||
const expanded = ref(new Set());
|
||||
let transportByCode = {};
|
||||
let ticker = null;
|
||||
let aborter = null;
|
||||
|
||||
const statusText = computed(() => {
|
||||
if (errorMsg.value) return "Error";
|
||||
if (searching.value) return "Scanning";
|
||||
if (done.value) return "Done";
|
||||
return "Idle";
|
||||
});
|
||||
|
||||
const hasResults = computed(() => summary.value !== null);
|
||||
|
||||
const fetchedCount = computed(() => {
|
||||
const s = summary.value;
|
||||
return s ? s.nights_fetched + s.nights_failed + s.nights_skipped : 0;
|
||||
});
|
||||
|
||||
// Best hotel per night (by total, then room) as transport fills in.
|
||||
const bestByNight = computed(() => {
|
||||
const m = new Map();
|
||||
for (const n of nightRows.value) {
|
||||
if (!n.hotels.length) continue;
|
||||
m.set(n.checkin, n.hotels.reduce((b, h) => (byTotal(h, b) < 0 ? h : b)));
|
||||
}
|
||||
return m;
|
||||
});
|
||||
|
||||
function bestOf(n) {
|
||||
return bestByNight.value.get(n.checkin) ?? null;
|
||||
}
|
||||
|
||||
function nightTotal(n) {
|
||||
return bestOf(n)?.total ?? null;
|
||||
}
|
||||
|
||||
function nightRoom(n) {
|
||||
if (!n.hotels.length) return null;
|
||||
return n.hotels.reduce((m, h) => Math.min(m, h.room_price), Infinity);
|
||||
}
|
||||
|
||||
function isWeekend(n) {
|
||||
const d = new Date(n.checkin + "T00:00:00").getDay();
|
||||
return d === 5 || d === 6;
|
||||
}
|
||||
|
||||
const byDate = (a, b) => (a.checkin < b.checkin ? -1 : a.checkin > b.checkin ? 1 : 0);
|
||||
const byNightRoom = byNumber(nightRoom, byDate);
|
||||
const byNightTotal = byNumber(nightTotal, byNightRoom);
|
||||
|
||||
const sortedNights = computed(() => {
|
||||
const cmp = { total: byNightTotal, room: byNightRoom, date: byDate }[rankBy.value];
|
||||
const ok = nightRows.value.filter((n) => n.status === "ok" && n.hotels.length);
|
||||
const rest = nightRows.value.filter((n) => !(n.status === "ok" && n.hotels.length));
|
||||
return [...ok.sort(cmp), ...rest.sort(byDate)];
|
||||
});
|
||||
|
||||
function sortedHotels(n) {
|
||||
return [...n.hotels].sort(rankBy.value === "room" ? byRoom : byTotal);
|
||||
}
|
||||
|
||||
function firstNight(cmp, ok) {
|
||||
const list = nightRows.value.filter((n) => n.hotels.length && ok(n));
|
||||
if (!list.length) return null;
|
||||
return list.reduce((best, n) => (cmp(n, best) < 0 ? n : best));
|
||||
}
|
||||
|
||||
function describeNight(n, h) {
|
||||
return h.total != null
|
||||
? `${gbp(h.room_price)} stay + ${gbp(h.transport_total)} travel = ${gbp(h.total)}`
|
||||
: `${gbp(h.room_price)} stay, transport not priced yet`;
|
||||
}
|
||||
|
||||
const picks = computed(() => {
|
||||
const p = [];
|
||||
const cheapest = firstNight(byNightTotal, (n) => nightTotal(n) !== null);
|
||||
if (cheapest) {
|
||||
const h = bestOf(cheapest);
|
||||
p.push({
|
||||
label: "Cheapest night",
|
||||
night: cheapest,
|
||||
row: h,
|
||||
maths: describeNight(cheapest, h),
|
||||
sub: `${h.travel_minutes} min by ${h.route}`,
|
||||
});
|
||||
}
|
||||
const room = firstNight(byNightRoom, () => true);
|
||||
if (room) {
|
||||
const h = sortedHotels(room).sort(byRoom)[0];
|
||||
p.push({
|
||||
label: "Cheapest room",
|
||||
night: room,
|
||||
row: h,
|
||||
maths: `${gbp(h.room_price)} for the stay`,
|
||||
sub:
|
||||
h.total != null
|
||||
? `${gbp(h.total)} with transport (${h.travel_minutes} min)`
|
||||
: "transport not priced yet",
|
||||
});
|
||||
}
|
||||
const weekend = firstNight(byNightTotal, (n) => isWeekend(n) && nightTotal(n) !== null);
|
||||
if (weekend && weekend !== cheapest) {
|
||||
const h = bestOf(weekend);
|
||||
p.push({
|
||||
label: "Cheapest Fri/Sat night",
|
||||
night: weekend,
|
||||
row: h,
|
||||
maths: describeNight(weekend, h),
|
||||
sub: `${h.travel_minutes} min by ${h.route}`,
|
||||
});
|
||||
}
|
||||
return p;
|
||||
});
|
||||
|
||||
const summaryText = computed(() => {
|
||||
const s = summary.value;
|
||||
if (!s) return "";
|
||||
const party =
|
||||
`${s.adults} adult${s.adults === 1 ? "" : "s"}` +
|
||||
(s.children ? ` + ${s.children} child${s.children === 1 ? "" : "ren"}` : "") +
|
||||
` in ${s.rooms} room${s.rooms === 1 ? "" : "s"}`;
|
||||
const railcard = s.railcard_holders
|
||||
? ` (${s.railcard_holders} with railcard)`
|
||||
: "";
|
||||
const days =
|
||||
s.weekdays.length === 7
|
||||
? "any day"
|
||||
: s.weekdays.map((d) => DAYS[d]).join("/") + " check-ins";
|
||||
return (
|
||||
`${s.nights_candidate} candidate ${s.nights}-night stays near '${s.location}' ` +
|
||||
`between ${fmtDate(s.start)} and ${fmtDate(s.end)} (${days}, ${party}), ` +
|
||||
`keeping the ${s.per_night} cheapest hotels per night, with round-trip transport ` +
|
||||
`from ${s.origin_name} departing ${fmtTime(s.depart)}${railcard}.`
|
||||
);
|
||||
});
|
||||
|
||||
function nightLabel(n) {
|
||||
return `${fmtDate(n.checkin)}${n.checkout !== addDays(n.checkin, 1) ? " → " + fmtDate(n.checkout) : ""}`;
|
||||
}
|
||||
|
||||
function nightNote(n) {
|
||||
if (n.status === "pending") return "fetching…";
|
||||
if (n.status === "failed") return `failed: ${n.detail}`;
|
||||
if (n.status === "skipped") return n.detail || "skipped";
|
||||
if (!n.hotels.length) return "no availability";
|
||||
return "";
|
||||
}
|
||||
|
||||
function toggle(n) {
|
||||
if (!n.hotels.length) return;
|
||||
if (expanded.value.has(n.checkin)) expanded.value.delete(n.checkin);
|
||||
else expanded.value.add(n.checkin);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Persistence
|
||||
// ---------------------------------------------------------------------------
|
||||
function saveConfig() {
|
||||
props.form.save();
|
||||
saveTo(SCAN_KEY, {
|
||||
start: start.value,
|
||||
end: end.value,
|
||||
weekdays: weekdays.value,
|
||||
nights: nights.value,
|
||||
perNight: perNight.value,
|
||||
rankBy: rankBy.value,
|
||||
});
|
||||
}
|
||||
|
||||
function loadConfig() {
|
||||
const c = loadFrom(SCAN_KEY);
|
||||
if (!c) return;
|
||||
const today = todayIso();
|
||||
if (c.start && c.start >= today) start.value = c.start;
|
||||
if (c.end && c.end >= start.value && c.end <= endMax.value) end.value = c.end;
|
||||
if (Array.isArray(c.weekdays) && c.weekdays.length)
|
||||
weekdays.value = c.weekdays.filter((d) => ALL_DAYS.includes(d));
|
||||
nights.value = Math.min(7, Math.max(1, c.nights ?? nights.value));
|
||||
perNight.value = Math.min(10, Math.max(1, c.perNight ?? perNight.value));
|
||||
if (RANKINGS.some((r) => r.key === c.rankBy)) rankBy.value = c.rankBy;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Scan
|
||||
// ---------------------------------------------------------------------------
|
||||
function buildRequest() {
|
||||
return {
|
||||
...props.form.sharedBody(),
|
||||
start: start.value,
|
||||
end: end.value,
|
||||
weekdays: [...weekdays.value].sort(),
|
||||
nights: Number(nights.value),
|
||||
per_night: Number(perNight.value),
|
||||
};
|
||||
}
|
||||
|
||||
function applyTransport(h, fields) {
|
||||
if (!fields) return;
|
||||
Object.assign(h, fields);
|
||||
h.total =
|
||||
h.transport_total !== null && h.transport_total !== undefined
|
||||
? Math.round((h.room_price + h.transport_total) * 100) / 100
|
||||
: null;
|
||||
}
|
||||
|
||||
function applyEvent(ev) {
|
||||
switch (ev.event) {
|
||||
case "scan":
|
||||
summary.value = ev.summary;
|
||||
nightRows.value = ev.nights;
|
||||
cached.value = !!ev.cached;
|
||||
break;
|
||||
case "night": {
|
||||
summary.value = ev.summary;
|
||||
const night = ev.night;
|
||||
for (const h of night.hotels) applyTransport(h, transportByCode[h.code]);
|
||||
const i = nightRows.value.findIndex((n) => n.checkin === night.checkin);
|
||||
if (i >= 0) nightRows.value[i] = night;
|
||||
else nightRows.value.push(night);
|
||||
break;
|
||||
}
|
||||
case "transport": {
|
||||
summary.value = ev.summary;
|
||||
const { code, ...fields } = ev.transport;
|
||||
transportByCode[code] = fields;
|
||||
for (const n of nightRows.value)
|
||||
for (const h of n.hotels) if (h.code === code) applyTransport(h, fields);
|
||||
break;
|
||||
}
|
||||
case "done":
|
||||
summary.value = ev.summary;
|
||||
nightRows.value = ev.nights;
|
||||
cached.value = !!ev.cached;
|
||||
done.value = true;
|
||||
break;
|
||||
case "error":
|
||||
errorMsg.value = ev.detail || "Scan failed.";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
async function onScan() {
|
||||
if (searching.value) return;
|
||||
errorMsg.value = "";
|
||||
summary.value = null;
|
||||
nightRows.value = [];
|
||||
transportByCode = {};
|
||||
expanded.value = new Set();
|
||||
cached.value = false;
|
||||
done.value = false;
|
||||
searching.value = true;
|
||||
elapsed.value = 0;
|
||||
saveConfig();
|
||||
ticker = setInterval(() => elapsed.value++, 1000);
|
||||
aborter = new AbortController();
|
||||
try {
|
||||
await runStream("/py/hotels/scan/stream", buildRequest(), {
|
||||
signal: aborter.signal,
|
||||
onEvent: applyEvent,
|
||||
});
|
||||
if (!done.value && !errorMsg.value)
|
||||
errorMsg.value = "The scan ended early; showing what came back.";
|
||||
} catch (e) {
|
||||
if (e.name !== "AbortError") errorMsg.value = e.message || "Scan failed.";
|
||||
} finally {
|
||||
clearInterval(ticker);
|
||||
ticker = null;
|
||||
aborter = null;
|
||||
searching.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadConfig);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (ticker) clearInterval(ticker);
|
||||
if (aborter) aborter.abort();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="panel">
|
||||
<h2 class="panelTitle">Scan a date range</h2>
|
||||
<form class="configGrid" @submit.prevent="onScan">
|
||||
<SharedFields :form="form" />
|
||||
<label>
|
||||
First check-in
|
||||
<input type="date" v-model="start" :min="todayIso()" required />
|
||||
</label>
|
||||
<label>
|
||||
Last check-in
|
||||
<input type="date" v-model="end" :min="start" :max="endMax" required />
|
||||
<span class="hint">up to about 3 months after the first</span>
|
||||
</label>
|
||||
<label>
|
||||
Nights per stay
|
||||
<input type="number" v-model.number="nights" min="1" max="7" />
|
||||
</label>
|
||||
<label>
|
||||
Hotels per night
|
||||
<input type="number" v-model.number="perNight" min="1" max="10" />
|
||||
<span class="hint"
|
||||
>N cheapest by room rate each night; transport is priced
|
||||
once per hotel</span
|
||||
>
|
||||
</label>
|
||||
<div class="dayRow">
|
||||
<span class="rankLabel">Check-in days</span>
|
||||
<label v-for="(d, i) in DAYS" :key="d" class="chk">
|
||||
<input type="checkbox" :value="i" v-model="weekdays" />
|
||||
{{ d }}
|
||||
</label>
|
||||
<button type="button" class="rankBtn" @click="setDays(ALL_DAYS)">all</button>
|
||||
<button type="button" class="rankBtn" @click="setDays(WEEKEND)">Fri + Sat</button>
|
||||
</div>
|
||||
|
||||
<div class="controls">
|
||||
<button
|
||||
class="btn"
|
||||
type="submit"
|
||||
:disabled="searching || !weekdays.length"
|
||||
>
|
||||
{{ searching ? "Scanning…" : "Scan" }}
|
||||
</button>
|
||||
<span class="statusChip" :class="statusText.toLowerCase()">
|
||||
{{ statusText }}
|
||||
</span>
|
||||
<span v-if="searching" class="stepCounter">{{ elapsed }}s</span>
|
||||
<span class="note">
|
||||
Nights fill in over a minute or so; TfL prices for each
|
||||
hotel follow. Shares the single search slot, so a scan can
|
||||
take a few minutes.
|
||||
</span>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<p v-if="errorMsg" class="errorBox">{{ errorMsg }}</p>
|
||||
</section>
|
||||
|
||||
<section v-if="hasResults" class="panel">
|
||||
<h2 class="panelTitle">
|
||||
Results
|
||||
<span v-if="cached" class="cachedTag">cached</span>
|
||||
<span v-if="summary.truncated" class="cachedTag warn">time limit hit</span>
|
||||
</h2>
|
||||
<p class="summary">{{ summaryText }}</p>
|
||||
|
||||
<div class="progress" v-if="nightRows.length">
|
||||
<div class="progressBar">
|
||||
<div
|
||||
class="progressFill"
|
||||
:style="{ width: `${(100 * fetchedCount) / summary.nights_candidate}%` }"
|
||||
></div>
|
||||
</div>
|
||||
<span class="progressText">
|
||||
{{ fetchedCount }} / {{ summary.nights_candidate }} nights fetched
|
||||
</span>
|
||||
</div>
|
||||
<div class="progress" v-if="summary.hotels_unique">
|
||||
<div class="progressBar">
|
||||
<div
|
||||
class="progressFill"
|
||||
:style="{ width: `${(100 * summary.hotels_priced) / summary.hotels_unique}%` }"
|
||||
></div>
|
||||
</div>
|
||||
<span class="progressText">
|
||||
{{ summary.hotels_priced }} / {{ summary.hotels_unique }} hotels priced on TfL
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="picks.length" class="picks">
|
||||
<div v-for="p in picks" :key="p.label" class="pick">
|
||||
<span class="pickLabel">{{ p.label }}</span>
|
||||
<span class="date">{{ nightLabel(p.night) }}</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="!nightRows.length" class="note">No candidate nights in that range.</p>
|
||||
|
||||
<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>
|
||||
<span class="note">click a night to see its hotels</span>
|
||||
</div>
|
||||
|
||||
<div class="tableWrap">
|
||||
<table class="results">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="num">#</th>
|
||||
<th :class="{ sorted: rankBy === 'date' }">Night</th>
|
||||
<th class="num" :class="{ sorted: rankBy === 'total' }">Total</th>
|
||||
<th class="num" :class="{ sorted: rankBy === 'room' }">Stay</th>
|
||||
<th class="num">Travel</th>
|
||||
<th class="num">Mins</th>
|
||||
<th class="num">Cycle</th>
|
||||
<th>Cheapest hotel</th>
|
||||
<th>Route (cheapest acceptable)</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-for="(n, i) in sortedNights" :key="n.checkin">
|
||||
<tr
|
||||
class="nightRow"
|
||||
:class="{
|
||||
best: i === 0 && nightTotal(n) !== null,
|
||||
muted: !n.hotels.length,
|
||||
open: expanded.has(n.checkin),
|
||||
unpriced: nightTotal(n) === null,
|
||||
}"
|
||||
@click="toggle(n)"
|
||||
>
|
||||
<td class="num">{{ i + 1 }}</td>
|
||||
<td class="date">{{ nightLabel(n) }}</td>
|
||||
<template v-if="bestOf(n)">
|
||||
<td class="num total">{{ gbp(bestOf(n).total) }}</td>
|
||||
<td class="num stay">{{ gbp(bestOf(n).room_price) }}</td>
|
||||
<td class="num">{{ gbp(bestOf(n).transport_total) }}</td>
|
||||
<td class="num">{{ bestOf(n).travel_minutes ?? "" }}</td>
|
||||
<td class="num cycle">{{ cycleText(bestOf(n)) }}</td>
|
||||
<td>
|
||||
<a
|
||||
:href="bestOf(n).url"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="hotelLink"
|
||||
@click.stop
|
||||
>{{ bestOf(n).name }}</a
|
||||
>
|
||||
<span v-if="bestOf(n).low_availability" class="lowTag"
|
||||
>low availability</span
|
||||
>
|
||||
</td>
|
||||
<td
|
||||
class="route"
|
||||
:class="{ pending: bestOf(n).route === PENDING_ROUTE }"
|
||||
>
|
||||
{{ bestOf(n).route }}
|
||||
</td>
|
||||
<td class="num"><span class="chev">▶</span></td>
|
||||
</template>
|
||||
<template v-else>
|
||||
<td colspan="8" class="route">{{ nightNote(n) }}</td>
|
||||
</template>
|
||||
</tr>
|
||||
<tr v-if="expanded.has(n.checkin)" class="expandRow">
|
||||
<td colspan="10">
|
||||
<table class="results sub">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="num">#</th>
|
||||
<th class="num">Total</th>
|
||||
<th class="num">Stay</th>
|
||||
<th class="num">Travel</th>
|
||||
<th class="num">Mins</th>
|
||||
<th class="num">Cycle</th>
|
||||
<th>Hotel</th>
|
||||
<th>Route</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<HotelRows :rows="sortedHotels(n)" :highlight-first="false" />
|
||||
</tbody>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<details class="help">
|
||||
<summary>Notes</summary>
|
||||
<ul>
|
||||
<li>
|
||||
Each night keeps only its N cheapest hotels by room rate, so
|
||||
a dearer room with cheap transport can be missed; raise
|
||||
"Hotels per night" to widen the net.
|
||||
</li>
|
||||
<li>
|
||||
Transport is priced once per hotel at the first candidate
|
||||
date's departure time and reused for every night. Fares
|
||||
are the same every day off-peak; routes can differ at
|
||||
weekends.
|
||||
</li>
|
||||
<li>
|
||||
Room prices may be up to 30 minutes old. A night marked
|
||||
"failed" can be retried by scanning again; "skipped" means
|
||||
the time limit was reached first, so try a shorter range.
|
||||
</li>
|
||||
<li>
|
||||
Everything else (railcard, buses, children, cycling) works
|
||||
as in the single-stay search: see its notes.
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,54 @@
|
||||
<script setup>
|
||||
import {
|
||||
gbp,
|
||||
cycleText,
|
||||
cycleTitle,
|
||||
showFaster,
|
||||
PENDING_ROUTE,
|
||||
} from "./hotelsFormat.js";
|
||||
|
||||
// Table body rows for a list of hotels (already sorted). Columns:
|
||||
// #, Total, Stay, Travel, Mins, Cycle, Hotel, Route.
|
||||
defineProps({
|
||||
rows: { type: Array, required: true },
|
||||
highlightFirst: { type: Boolean, default: true },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<template v-for="(r, i) in rows" :key="r.code">
|
||||
<tr
|
||||
:class="{
|
||||
best: highlightFirst && i === 0,
|
||||
unpriced: r.total == null,
|
||||
}"
|
||||
>
|
||||
<td class="num">{{ i + 1 }}</td>
|
||||
<td class="num total">{{ gbp(r.total) }}</td>
|
||||
<td class="num stay">{{ gbp(r.room_price) }}</td>
|
||||
<td class="num">{{ gbp(r.transport_total) }}</td>
|
||||
<td class="num">{{ r.travel_minutes ?? "" }}</td>
|
||||
<td class="num cycle" :title="cycleTitle(r)">{{ cycleText(r) }}</td>
|
||||
<td>
|
||||
<a
|
||||
:href="r.url"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="hotelLink"
|
||||
>{{ r.name }}</a
|
||||
>
|
||||
<span v-if="r.low_availability" class="lowTag">low availability</span>
|
||||
</td>
|
||||
<td class="route" :class="{ pending: r.route === PENDING_ROUTE }">
|
||||
{{ r.route }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="showFaster(r)" class="fasterRow">
|
||||
<td colspan="7"></td>
|
||||
<td class="route">
|
||||
faster: {{ r.fastest_minutes }} min for {{ gbp(r.fastest_total) }}
|
||||
return via {{ r.fastest_route }}
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</template>
|
||||
@@ -0,0 +1,82 @@
|
||||
<script setup>
|
||||
import { CUSTOM_ORIGIN } from "./useHotelForm.js";
|
||||
|
||||
defineProps({
|
||||
form: { type: Object, required: true },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<label>
|
||||
Search area
|
||||
<input type="text" v-model="form.location" maxlength="80" required />
|
||||
</label>
|
||||
<label>
|
||||
Rooms & guests
|
||||
<input
|
||||
type="text"
|
||||
v-model="form.guests"
|
||||
placeholder='"1", "2+1", "2,2+2"'
|
||||
maxlength="40"
|
||||
/>
|
||||
<span class="hint"
|
||||
>rooms separated by commas, each ADULTS or ADULTS+CHILDREN</span
|
||||
>
|
||||
</label>
|
||||
<label>
|
||||
Railcard holders
|
||||
<input
|
||||
type="number"
|
||||
v-model.number="form.railcardHolders"
|
||||
min="0"
|
||||
max="8"
|
||||
/>
|
||||
<span class="hint">adults getting 1/3 off off-peak rail</span>
|
||||
</label>
|
||||
<label>
|
||||
Origin station
|
||||
<select v-model="form.originKey">
|
||||
<option v-for="o in form.origins" :key="o.key" :value="o.key">
|
||||
{{ o.name }}
|
||||
</option>
|
||||
<option v-if="!form.origins.length" value="clapham junction">
|
||||
Clapham Junction
|
||||
</option>
|
||||
<option :value="CUSTOM_ORIGIN">Custom lat,lon…</option>
|
||||
</select>
|
||||
<input
|
||||
v-if="form.originKey === CUSTOM_ORIGIN"
|
||||
type="text"
|
||||
v-model="form.customOrigin"
|
||||
placeholder="51.5031,-0.1132"
|
||||
class="mt-1"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Leave at
|
||||
<input type="time" v-model="form.depart" required />
|
||||
<span class="hint">16:00–19:00 Mon–Fri is peak (dearer, no railcard)</span>
|
||||
</label>
|
||||
<label>
|
||||
Max miles from search area
|
||||
<input
|
||||
type="number"
|
||||
v-model="form.maxMiles"
|
||||
min="0.5"
|
||||
max="50"
|
||||
step="0.5"
|
||||
placeholder="any"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Max travel minutes
|
||||
<input
|
||||
type="number"
|
||||
v-model.number="form.maxTravelMin"
|
||||
min="10"
|
||||
max="240"
|
||||
/>
|
||||
<span class="hint">slower routes are ignored when picking the cheapest</span>
|
||||
</label>
|
||||
</template>
|
||||
@@ -0,0 +1,375 @@
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
|
||||
import SharedFields from "./SharedFields.vue";
|
||||
import HotelRows from "./HotelRows.vue";
|
||||
import { runStream } from "./hotelsStream.js";
|
||||
import { nextFriday, todayIso } from "./useHotelForm.js";
|
||||
import {
|
||||
gbp,
|
||||
fmtDate,
|
||||
fmtTime,
|
||||
cycleText,
|
||||
byRoom,
|
||||
byTotal,
|
||||
byCycle,
|
||||
byMinutes,
|
||||
PENDING_ROUTE,
|
||||
} from "./hotelsFormat.js";
|
||||
|
||||
const props = defineProps({
|
||||
form: { type: Object, required: true },
|
||||
});
|
||||
|
||||
const RANKINGS = [
|
||||
{ key: "total", label: "Stay + transport" },
|
||||
{ key: "room", label: "Stay only" },
|
||||
{ key: "cycle", label: "Cycle time" },
|
||||
{ key: "minutes", label: "Travel time" },
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Form state (this panel's own fields; shared ones live in props.form)
|
||||
// ---------------------------------------------------------------------------
|
||||
const checkin = ref(nextFriday());
|
||||
const nights = ref(1);
|
||||
const top = ref(20);
|
||||
const rankBy = ref("total");
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Search state
|
||||
// ---------------------------------------------------------------------------
|
||||
const searching = ref(false);
|
||||
const errorMsg = ref("");
|
||||
const summary = ref(null);
|
||||
const rows = ref([]);
|
||||
const cached = ref(false);
|
||||
const done = ref(false);
|
||||
const elapsed = ref(0);
|
||||
let ticker = null;
|
||||
let aborter = null;
|
||||
|
||||
const statusText = computed(() => {
|
||||
if (errorMsg.value) return "Error";
|
||||
if (searching.value) return "Searching";
|
||||
if (done.value) return "Done";
|
||||
return "Idle";
|
||||
});
|
||||
|
||||
const pricedCount = computed(
|
||||
() => rows.value.filter((r) => r.total != null || r.route !== PENDING_ROUTE).length,
|
||||
);
|
||||
|
||||
const hasResults = computed(() => summary.value !== null);
|
||||
|
||||
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 s = summary.value;
|
||||
if (!s) return "";
|
||||
const party =
|
||||
`${s.adults} adult${s.adults === 1 ? "" : "s"}` +
|
||||
(s.children ? ` + ${s.children} child${s.children === 1 ? "" : "ren"}` : "") +
|
||||
` in ${s.rooms} room${s.rooms === 1 ? "" : "s"}`;
|
||||
const railcard = s.railcard_holders
|
||||
? ` (${s.railcard_holders} with railcard)`
|
||||
: "";
|
||||
return (
|
||||
`Cheapest ${rows.value.length} of ${s.hotels_available} available Travelodges near ` +
|
||||
`'${s.location}', ${fmtDate(s.checkin)} → ${fmtDate(s.checkout)} ` +
|
||||
`(${s.nights} night${s.nights === 1 ? "" : "s"}, ${party}), ` +
|
||||
`with round-trip transport from ${s.origin_name} departing ${fmtTime(s.depart)}${railcard}.`
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Persistence
|
||||
// ---------------------------------------------------------------------------
|
||||
function saveConfig() {
|
||||
props.form.save({
|
||||
checkin: checkin.value,
|
||||
nights: nights.value,
|
||||
top: top.value,
|
||||
rankBy: rankBy.value,
|
||||
});
|
||||
}
|
||||
|
||||
function loadConfig() {
|
||||
const c = props.form.stored();
|
||||
nights.value = c.nights ?? nights.value;
|
||||
top.value = Math.min(40, c.top ?? top.value);
|
||||
if (RANKINGS.some((r) => r.key === c.rankBy)) rankBy.value = c.rankBy;
|
||||
// Only restore the date if it is still in the future.
|
||||
if (c.checkin && c.checkin >= todayIso()) checkin.value = c.checkin;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Search
|
||||
// ---------------------------------------------------------------------------
|
||||
function buildRequest() {
|
||||
return {
|
||||
...props.form.sharedBody(),
|
||||
checkin: checkin.value,
|
||||
nights: Number(nights.value),
|
||||
top: Number(top.value),
|
||||
};
|
||||
}
|
||||
|
||||
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 onSearch() {
|
||||
if (searching.value) return;
|
||||
errorMsg.value = "";
|
||||
summary.value = null;
|
||||
rows.value = [];
|
||||
cached.value = false;
|
||||
done.value = false;
|
||||
searching.value = true;
|
||||
elapsed.value = 0;
|
||||
saveConfig();
|
||||
ticker = setInterval(() => elapsed.value++, 1000);
|
||||
aborter = new AbortController();
|
||||
try {
|
||||
await runStream("/py/hotels/search/stream", buildRequest(), {
|
||||
signal: aborter.signal,
|
||||
onEvent: applyEvent,
|
||||
});
|
||||
if (!done.value && !errorMsg.value)
|
||||
errorMsg.value = "The search ended early; showing what came back.";
|
||||
} catch (e) {
|
||||
if (e.name !== "AbortError") errorMsg.value = e.message || "Search failed.";
|
||||
} finally {
|
||||
clearInterval(ticker);
|
||||
ticker = null;
|
||||
aborter = null;
|
||||
searching.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadConfig);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (ticker) clearInterval(ticker);
|
||||
if (aborter) aborter.abort();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="panel">
|
||||
<h2 class="panelTitle">Search</h2>
|
||||
<form class="configGrid" @submit.prevent="onSearch">
|
||||
<SharedFields :form="form" />
|
||||
<label>
|
||||
Check-in
|
||||
<input type="date" v-model="checkin" required />
|
||||
</label>
|
||||
<label>
|
||||
Nights
|
||||
<input type="number" v-model.number="nights" min="1" max="14" />
|
||||
</label>
|
||||
<label>
|
||||
Hotels to price
|
||||
<input type="number" v-model.number="top" min="1" max="40" />
|
||||
<span class="hint"
|
||||
>N cheapest by room rate; TfL allows about 24 hotels a
|
||||
minute</span
|
||||
>
|
||||
</label>
|
||||
|
||||
<div class="controls">
|
||||
<button class="btn" type="submit" :disabled="searching">
|
||||
{{ searching ? "Searching…" : "Search" }}
|
||||
</button>
|
||||
<span class="statusChip" :class="statusText.toLowerCase()">
|
||||
{{ statusText }}
|
||||
</span>
|
||||
<span v-if="searching" class="stepCounter">{{ elapsed }}s</span>
|
||||
<span class="note">
|
||||
Hotels appear within a couple of seconds; transport prices
|
||||
fill in as TfL answers.
|
||||
</span>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<p v-if="errorMsg" class="errorBox">{{ errorMsg }}</p>
|
||||
</section>
|
||||
|
||||
<section v-if="hasResults" class="panel">
|
||||
<h2 class="panelTitle">
|
||||
Results
|
||||
<span v-if="cached" class="cachedTag">cached</span>
|
||||
<span v-if="summary.truncated" class="cachedTag warn">time limit hit</span>
|
||||
</h2>
|
||||
<p class="summary">{{ summaryText }}</p>
|
||||
|
||||
<div class="progress" v-if="rows.length">
|
||||
<div class="progressBar">
|
||||
<div
|
||||
class="progressFill"
|
||||
:style="{ width: `${(100 * pricedCount) / rows.length}%` }"
|
||||
></div>
|
||||
</div>
|
||||
<span class="progressText">
|
||||
{{ pricedCount }} / {{ rows.length }} priced on TfL
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<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.
|
||||
</p>
|
||||
|
||||
<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">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="num">#</th>
|
||||
<th class="num" :class="{ sorted: rankBy === 'total' }">Total</th>
|
||||
<th class="num" :class="{ sorted: rankBy === 'room' }">Stay</th>
|
||||
<th class="num">Travel</th>
|
||||
<th class="num" :class="{ sorted: rankBy === 'minutes' }">Mins</th>
|
||||
<th class="num" :class="{ sorted: rankBy === 'cycle' }">Cycle</th>
|
||||
<th>Hotel</th>
|
||||
<th>Route (cheapest acceptable)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<HotelRows :rows="sortedRows" />
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<details class="help">
|
||||
<summary>Notes</summary>
|
||||
<ul>
|
||||
<li>
|
||||
Stay price is Travelodge's cheapest room(s) for the whole
|
||||
stay and all rooms. Rank by "Stay only" to ignore transport
|
||||
entirely.
|
||||
</li>
|
||||
<li>
|
||||
Transport is the TfL adult pay-as-you-go single each way,
|
||||
multiplied by adults. The return is assumed off-peak (next
|
||||
day).
|
||||
</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>
|
||||
Children 10 and under travel free on TfL; 11–15s pay child
|
||||
fares with a Zip card (not included).
|
||||
</li>
|
||||
<li>
|
||||
The Railcard's 1/3 off applies to off-peak Tube and rail
|
||||
fares only, and only when the Railcard is linked to an
|
||||
Oyster card (not contactless).
|
||||
</li>
|
||||
<li>
|
||||
Bus fares are flat and never discounted. Prices are rounded
|
||||
to 5p. Room prices may be up to 30 minutes old. Everything
|
||||
is an estimate: check the booking page and TfL before
|
||||
paying.
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,458 @@
|
||||
/* Shared styles for the /hotels page and its panels (SingleStayPanel,
|
||||
CheapestNightPanel). Loaded once, unscoped, from CheapHotels.vue; every
|
||||
selector is prefixed with the page's `.hotels` root class so nothing
|
||||
leaks into other pages. */
|
||||
|
||||
.hotels .panel {
|
||||
border: 1px solid var(--color-quaternary);
|
||||
background: rgba(4, 8, 15, 0.55);
|
||||
padding: 0.9rem;
|
||||
}
|
||||
|
||||
.hotels .panelTitle {
|
||||
color: var(--color-primary);
|
||||
font-family: var(--font-heading);
|
||||
font-size: 1.4rem;
|
||||
margin-bottom: 0.5rem;
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.hotels .cachedTag {
|
||||
font-size: 0.8rem;
|
||||
color: var(--color-muted);
|
||||
border: 1px solid var(--color-quaternary);
|
||||
padding: 0 0.4rem;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.hotels .cachedTag.warn {
|
||||
color: #ffd166;
|
||||
border-color: currentColor;
|
||||
}
|
||||
|
||||
.hotels .configGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 0.6rem 1rem;
|
||||
}
|
||||
|
||||
.hotels .configGrid label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
color: var(--color-muted);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.hotels .configGrid input,
|
||||
.hotels .configGrid select {
|
||||
background: var(--color-surface-deep);
|
||||
border: 1px solid var(--color-quaternary);
|
||||
color: #e5f4ee;
|
||||
padding: 0.35rem 0.5rem;
|
||||
font-family: monospace;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
.hotels .configGrid input:focus,
|
||||
.hotels .configGrid select:focus {
|
||||
outline: 1px solid var(--color-primary);
|
||||
}
|
||||
|
||||
.hotels .hint {
|
||||
font-size: 0.72rem;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.hotels .controls {
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-top: 0.4rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.hotels .btn {
|
||||
padding: 0.35rem 1.1rem;
|
||||
border: 1px solid var(--color-primary);
|
||||
color: var(--color-primary);
|
||||
font-family: var(--font-heading);
|
||||
letter-spacing: 0.05em;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background 0.15s ease,
|
||||
color 0.15s ease;
|
||||
}
|
||||
|
||||
.hotels .btn:hover:enabled {
|
||||
background: var(--color-primary);
|
||||
color: var(--color-surface-deep);
|
||||
}
|
||||
|
||||
.hotels .btn:disabled {
|
||||
opacity: 0.35;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.hotels .statusChip {
|
||||
font-family: var(--font-heading);
|
||||
letter-spacing: 0.05em;
|
||||
padding: 0.1rem 0.6rem;
|
||||
border: 1px solid currentColor;
|
||||
color: var(--color-muted);
|
||||
}
|
||||
|
||||
.hotels .statusChip.searching {
|
||||
color: #ffd166;
|
||||
}
|
||||
|
||||
.hotels .statusChip.done {
|
||||
color: var(--color-secondary);
|
||||
}
|
||||
|
||||
.hotels .statusChip.error {
|
||||
color: var(--color-tertiary);
|
||||
}
|
||||
|
||||
.hotels .stepCounter {
|
||||
font-family: monospace;
|
||||
color: var(--color-muted);
|
||||
}
|
||||
|
||||
.hotels .note {
|
||||
color: var(--color-muted);
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.hotels .errorBox {
|
||||
margin-top: 0.75rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border: 1px solid var(--color-tertiary);
|
||||
color: var(--color-tertiary);
|
||||
font-family: monospace;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.hotels .summary {
|
||||
color: var(--color-muted);
|
||||
font-size: 0.9rem;
|
||||
margin-bottom: 0.6rem;
|
||||
}
|
||||
|
||||
.hotels .progress {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.9rem;
|
||||
}
|
||||
|
||||
.hotels .progressBar {
|
||||
flex: 1;
|
||||
height: 4px;
|
||||
background: rgba(2, 73, 66, 0.5);
|
||||
}
|
||||
|
||||
.hotels .progressFill {
|
||||
height: 100%;
|
||||
background: var(--color-primary);
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.hotels .progressText {
|
||||
font-family: monospace;
|
||||
font-size: 0.8rem;
|
||||
color: var(--color-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.hotels .picks {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 0.6rem;
|
||||
margin-bottom: 0.9rem;
|
||||
}
|
||||
|
||||
.hotels .pick {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.15rem;
|
||||
border: 1px solid var(--color-primary);
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: rgba(85, 255, 187, 0.06);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.hotels .pickLabel {
|
||||
font-family: var(--font-heading);
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--color-primary);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.hotels .pickName {
|
||||
color: #e5f4ee;
|
||||
font-weight: bold;
|
||||
text-decoration: none;
|
||||
transition: color 0.15s ease;
|
||||
}
|
||||
|
||||
.hotels .pickName:hover {
|
||||
color: var(--color-tertiary);
|
||||
}
|
||||
|
||||
.hotels .pickMaths {
|
||||
font-family: monospace;
|
||||
color: var(--color-secondary);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.hotels .pickSub {
|
||||
font-size: 0.78rem;
|
||||
color: var(--color-muted);
|
||||
}
|
||||
|
||||
.hotels .rankBar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 0.6rem;
|
||||
}
|
||||
|
||||
.hotels .rankLabel {
|
||||
font-family: var(--font-heading);
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--color-muted);
|
||||
font-size: 0.85rem;
|
||||
margin-right: 0.2rem;
|
||||
}
|
||||
|
||||
.hotels .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;
|
||||
}
|
||||
|
||||
.hotels .rankBtn:hover {
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
.hotels .rankBtn.active {
|
||||
color: var(--color-primary);
|
||||
border-color: var(--color-primary);
|
||||
}
|
||||
|
||||
.hotels .hotelLink {
|
||||
color: var(--color-primary);
|
||||
text-decoration: none;
|
||||
transition: color 0.15s ease;
|
||||
}
|
||||
|
||||
.hotels .hotelLink:hover {
|
||||
color: var(--color-tertiary);
|
||||
}
|
||||
|
||||
.hotels .tableWrap {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.hotels .results {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.9rem;
|
||||
color: #e5f4ee;
|
||||
}
|
||||
|
||||
.hotels .results th {
|
||||
text-align: left;
|
||||
color: var(--color-primary);
|
||||
font-family: var(--font-heading);
|
||||
letter-spacing: 0.05em;
|
||||
font-weight: normal;
|
||||
border-bottom: 1px solid var(--color-quaternary);
|
||||
padding: 0.3rem 0.5rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.hotels .results th.sorted {
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
.hotels .results td {
|
||||
padding: 0.3rem 0.5rem;
|
||||
border-bottom: 1px solid rgba(2, 73, 66, 0.4);
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.hotels .results .num {
|
||||
text-align: right;
|
||||
font-family: monospace;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.hotels .results .total {
|
||||
color: var(--color-secondary);
|
||||
}
|
||||
|
||||
.hotels .results .cycle {
|
||||
color: var(--color-muted);
|
||||
}
|
||||
|
||||
.hotels .results tr.best td {
|
||||
background: rgba(85, 255, 187, 0.08);
|
||||
}
|
||||
|
||||
.hotels .results tr.unpriced td.total,
|
||||
.hotels .results tr.unpriced td.route {
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.hotels .results .route {
|
||||
color: var(--color-muted);
|
||||
}
|
||||
|
||||
.hotels .results .route.pending {
|
||||
font-style: italic;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.hotels .fasterRow td {
|
||||
border-bottom: 1px solid rgba(2, 73, 66, 0.4);
|
||||
font-size: 0.8rem;
|
||||
opacity: 0.75;
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.hotels .fasterRow td:first-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.hotels .lowTag {
|
||||
margin-left: 0.4rem;
|
||||
font-size: 0.72rem;
|
||||
color: var(--color-tertiary);
|
||||
border: 1px solid currentColor;
|
||||
padding: 0 0.3rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.hotels .help {
|
||||
margin-top: 0.9rem;
|
||||
color: var(--color-muted);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.hotels .help summary {
|
||||
cursor: pointer;
|
||||
color: var(--color-primary);
|
||||
font-family: var(--font-heading);
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.hotels .help ul {
|
||||
list-style: disc;
|
||||
padding-left: 1.4rem;
|
||||
margin-top: 0.4rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.hotels .configGrid,
|
||||
.hotels .picks {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- tab strip -------------------------------------------------------- */
|
||||
.hotels .tabBar {
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.hotels .tabBtn {
|
||||
padding: 0.3rem 1rem;
|
||||
font-family: var(--font-heading);
|
||||
letter-spacing: 0.08em;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
/* --- cheapest-night form ----------------------------------------------- */
|
||||
.hotels .dayRow {
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.4rem 0.9rem;
|
||||
}
|
||||
|
||||
/* beats `.hotels .configGrid label`, which lays labels out as columns */
|
||||
.hotels .configGrid .dayRow .chk {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
font-family: monospace;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.hotels .configGrid .dayRow input[type="checkbox"] {
|
||||
padding: 0;
|
||||
accent-color: var(--color-primary);
|
||||
}
|
||||
|
||||
/* --- cheapest-night results -------------------------------------------- */
|
||||
.hotels .progress + .progress {
|
||||
margin-top: -0.5rem;
|
||||
}
|
||||
|
||||
.hotels .nightRow {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.hotels .nightRow:hover td {
|
||||
background: rgba(85, 255, 187, 0.04);
|
||||
}
|
||||
|
||||
.hotels .nightRow.muted td {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.hotels .nightRow .chev {
|
||||
display: inline-block;
|
||||
color: var(--color-muted);
|
||||
transition: transform 0.15s ease;
|
||||
}
|
||||
|
||||
.hotels .nightRow.open .chev {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.hotels .date {
|
||||
white-space: nowrap;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.hotels .expandRow > td {
|
||||
padding: 0.2rem 0.5rem 0.8rem 1.5rem;
|
||||
background: rgba(4, 8, 15, 0.4);
|
||||
}
|
||||
|
||||
.hotels .results.sub {
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.hotels .results.sub th {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Formatting and sorting helpers shared by the hotel panels.
|
||||
|
||||
export const PENDING_ROUTE = "pricing…";
|
||||
|
||||
export function gbp(v) {
|
||||
return v === null || v === undefined ? "?" : `£${v.toFixed(2)}`;
|
||||
}
|
||||
|
||||
export function fmtDate(iso) {
|
||||
const d = new Date(iso + "T00:00:00");
|
||||
return d.toLocaleDateString("en-GB", {
|
||||
weekday: "short",
|
||||
day: "numeric",
|
||||
month: "short",
|
||||
});
|
||||
}
|
||||
|
||||
export function fmtTime(iso) {
|
||||
return new Date(iso).toLocaleTimeString("en-GB", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
export function cycleText(r) {
|
||||
if (r.cycle_minutes === null || r.cycle_minutes === undefined) return "";
|
||||
return `${r.cycle_source === "estimate" ? "~" : ""}${r.cycle_minutes} min`;
|
||||
}
|
||||
|
||||
export 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`;
|
||||
}
|
||||
|
||||
export function showFaster(r) {
|
||||
return (
|
||||
r.fastest_minutes !== null &&
|
||||
r.fastest_minutes !== undefined &&
|
||||
r.travel_minutes !== null &&
|
||||
r.travel_minutes !== undefined &&
|
||||
r.fastest_minutes < r.travel_minutes - 10
|
||||
);
|
||||
}
|
||||
|
||||
/** Comparator on a numeric getter; nulls sort last, ties fall through to `tiebreak`. */
|
||||
export 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;
|
||||
};
|
||||
}
|
||||
|
||||
export const byRoom = byNumber((r) => r.room_price);
|
||||
export const byTotal = byNumber((r) => r.total, byRoom);
|
||||
export const byCycle = byNumber((r) => r.cycle_minutes, byRoom);
|
||||
export const byMinutes = byNumber((r) => r.travel_minutes, byTotal);
|
||||
@@ -0,0 +1,66 @@
|
||||
// POST a JSON body to a Python API endpoint and feed each NDJSON line to onEvent.
|
||||
|
||||
export function describeError(status, payload) {
|
||||
if (status === 429)
|
||||
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;
|
||||
if (Array.isArray(detail))
|
||||
return detail
|
||||
.map((d) => `${(d.loc || []).slice(-1)[0] ?? ""}: ${d.msg}`)
|
||||
.join("; ");
|
||||
if (typeof detail === "string") return detail;
|
||||
return `Search failed (${status}).`;
|
||||
}
|
||||
|
||||
async function readNdjson(res, onEvent) {
|
||||
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;
|
||||
let ev;
|
||||
try {
|
||||
ev = JSON.parse(line);
|
||||
} catch {
|
||||
continue; // skip a malformed line rather than abort the whole search
|
||||
}
|
||||
onEvent(ev);
|
||||
}
|
||||
};
|
||||
if (!res.body?.getReader) {
|
||||
handleChunk(await res.text(), true);
|
||||
return;
|
||||
}
|
||||
const reader = res.body.getReader();
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
handleChunk(decoder.decode(value, { stream: true }), false);
|
||||
}
|
||||
handleChunk(decoder.decode(), true);
|
||||
}
|
||||
|
||||
/** Throws an Error with a user-facing message on a non-2xx response. */
|
||||
export async function runStream(url, body, { signal, onEvent }) {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
if (!res.ok) {
|
||||
let payload = null;
|
||||
try {
|
||||
payload = await res.json();
|
||||
} catch {
|
||||
/* non-JSON body (e.g. nginx error page) */
|
||||
}
|
||||
throw new Error(describeError(res.status, payload));
|
||||
}
|
||||
await readNdjson(res, onEvent);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
// Form state shared by the "Single stay" and "Cheapest night" panels: where
|
||||
// you start from, who is travelling and how far you are willing to go. Kept
|
||||
// in one reactive object owned by CheapHotels.vue so values survive tab
|
||||
// switches, and persisted under the same localStorage key (and field names)
|
||||
// the page has always used.
|
||||
|
||||
import { reactive, ref } from "vue";
|
||||
|
||||
export const STORAGE_KEY = "cheap-hotels-config";
|
||||
export const CUSTOM_ORIGIN = "__custom__";
|
||||
|
||||
export function todayIso() {
|
||||
return new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function addDays(iso, n) {
|
||||
const d = new Date(iso + "T00:00:00");
|
||||
d.setDate(d.getDate() + n);
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function nextFriday() {
|
||||
const d = new Date();
|
||||
const delta = (5 - d.getDay() + 7) % 7 || 7;
|
||||
d.setDate(d.getDate() + delta);
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function loadFrom(key) {
|
||||
try {
|
||||
const saved = localStorage.getItem(key);
|
||||
return saved ? JSON.parse(saved) : null;
|
||||
} catch {
|
||||
return null; // storage unavailable or corrupted: caller keeps defaults
|
||||
}
|
||||
}
|
||||
|
||||
export function saveTo(key, value) {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value));
|
||||
} catch {
|
||||
/* storage unavailable: nothing to do */
|
||||
}
|
||||
}
|
||||
|
||||
export function useHotelForm() {
|
||||
const form = reactive({
|
||||
location: ref("Central London"),
|
||||
guests: ref("1"),
|
||||
railcardHolders: ref(1),
|
||||
originKey: ref("clapham junction"),
|
||||
customOrigin: ref(""),
|
||||
depart: ref("19:30"),
|
||||
maxMiles: ref(""),
|
||||
maxTravelMin: ref(75),
|
||||
origins: ref([]),
|
||||
|
||||
originValue() {
|
||||
return form.originKey === CUSTOM_ORIGIN
|
||||
? form.customOrigin
|
||||
: form.originKey;
|
||||
},
|
||||
|
||||
/** The shared part of a search or scan request body. */
|
||||
sharedBody() {
|
||||
const body = {
|
||||
location: form.location,
|
||||
guests: form.guests,
|
||||
railcard_holders: Number(form.railcardHolders),
|
||||
origin: form.originValue(),
|
||||
depart: form.depart,
|
||||
max_travel_min: Number(form.maxTravelMin),
|
||||
};
|
||||
if (form.maxMiles !== "" && form.maxMiles !== null)
|
||||
body.max_miles = Number(form.maxMiles);
|
||||
return body;
|
||||
},
|
||||
|
||||
/** Stored config object (shared + per-panel fields), or {}. */
|
||||
stored() {
|
||||
return loadFrom(STORAGE_KEY) ?? {};
|
||||
},
|
||||
|
||||
/** Persist the shared fields, merged with any per-panel `extra`. */
|
||||
save(extra = {}) {
|
||||
saveTo(STORAGE_KEY, {
|
||||
...form.stored(),
|
||||
location: form.location,
|
||||
guests: form.guests,
|
||||
railcardHolders: form.railcardHolders,
|
||||
originKey: form.originKey,
|
||||
customOrigin: form.customOrigin,
|
||||
depart: form.depart,
|
||||
maxMiles: form.maxMiles,
|
||||
maxTravelMin: form.maxTravelMin,
|
||||
...extra,
|
||||
});
|
||||
},
|
||||
|
||||
/** Restore the shared fields from storage. */
|
||||
load() {
|
||||
const c = form.stored();
|
||||
form.location = c.location ?? form.location;
|
||||
form.guests = c.guests ?? form.guests;
|
||||
form.railcardHolders = c.railcardHolders ?? form.railcardHolders;
|
||||
form.originKey = c.originKey ?? form.originKey;
|
||||
form.customOrigin = c.customOrigin ?? form.customOrigin;
|
||||
form.depart = c.depart ?? form.depart;
|
||||
form.maxMiles = c.maxMiles ?? form.maxMiles;
|
||||
form.maxTravelMin = c.maxTravelMin ?? form.maxTravelMin;
|
||||
},
|
||||
|
||||
async loadOrigins() {
|
||||
try {
|
||||
const res = await fetch("/py/hotels/origins");
|
||||
if (res.ok) form.origins = await res.json();
|
||||
} catch {
|
||||
/* dropdown falls back to the default key only */
|
||||
}
|
||||
if (
|
||||
form.originKey !== CUSTOM_ORIGIN &&
|
||||
form.origins.length &&
|
||||
!form.origins.some((o) => o.key === form.originKey)
|
||||
)
|
||||
form.originKey = form.origins[0].key;
|
||||
},
|
||||
});
|
||||
return form;
|
||||
}
|
||||
@@ -27,6 +27,11 @@ export default defineConfig({
|
||||
"/api": "http://localhost:8080",
|
||||
"/gitea": "http://localhost:3000",
|
||||
"/radio": "http://localhost:8000",
|
||||
// Python API: nginx strips the /py prefix in production, so do the same here.
|
||||
"/py": {
|
||||
target: "http://localhost:8000",
|
||||
rewrite: (path) => path.replace(/^\/py/, ""),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user