File size: 15,243 Bytes
8ba65bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 | """Deterministic in-process catalogue for the Backcountry offline clone.
Records originate from sanitized source evidence normalised into
``data/catalog.json`` (schema backcountry.clone-catalog.v2). This module only
queries, facets, sorts and paginates them; it performs no network access.
"""
from __future__ import annotations
import json
import re
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
from typing import Any
DATA = Path(__file__).resolve().parent / "data"
PAGE_SIZE = 42 # observed: 42 product tiles per source listing page
SORT_OPTIONS = [
("featured", "Featured"),
("price-low-high", "Price (Low to High)"),
("price-high-low", "Price (High to Low)"),
("top-rated", "Top Rated"),
("most-reviewed", "Most Reviewed"),
("brand-a-z", "Brand (A to Z)"),
]
PRICE_BANDS = [
("under-50", "Under $50", 0.0, 50.0),
("50-100", "$50 - $100", 50.0, 100.0),
("100-200", "$100 - $200", 100.0, 200.0),
("200-300", "$200 - $300", 200.0, 300.0),
("300-plus", "$300 and Up", 300.0, float("inf")),
]
PRICE_BAND_LABELS = {k: label for k, label, _lo, _hi in PRICE_BANDS}
# Facet groups in source sidebar order. "attr:<Name>" reads the product's own
# attribute vocabulary, which the source uses for the same sidebar groups.
FACET_GROUPS: list[tuple[str, str]] = [
("categories", "Categories"),
("brand", "Brand"),
("color", "Color"),
("sale", "Sale"),
("attr:Features", "Features"),
("price", "Price"),
("attr:Age", "Age"),
("attr:Recommended Use", "Recommended Use"),
("attr:Volume", "Volume"),
("attr:Shop By", "Shop By"),
("attr:Access", "Access"),
("attr:Material", "Material"),
("attr:Sustainability", "Responsible Collection"),
]
def _load(name: str) -> dict[str, Any]:
return json.loads((DATA / name).read_text(encoding="utf-8"))
@lru_cache(maxsize=1)
def catalog() -> dict[str, Any]:
return _load("catalog.json")
@lru_cache(maxsize=1)
def nav() -> list[dict[str, Any]]:
return _load("nav.json")["items"]
@lru_cache(maxsize=1)
def chrome() -> dict[str, Any]:
return _load("chrome.json")
@lru_cache(maxsize=1)
def home() -> dict[str, Any]:
return _load("home.json")
@lru_cache(maxsize=1)
def products() -> list[dict[str, Any]]:
return catalog()["products"]
@lru_cache(maxsize=1)
def by_slug() -> dict[str, dict[str, Any]]:
return {p["slug"]: p for p in products()}
def product(slug: str) -> dict[str, Any] | None:
return by_slug().get(slug if slug.startswith("/") else "/" + slug)
# --------------------------------------------------------------------------
# derived product facts
# --------------------------------------------------------------------------
def current_price(p: dict[str, Any]) -> float:
value = p["price"].get("minSale")
if value is None:
value = p["price"].get("minList")
return float(value or 0.0)
def price_range(p: dict[str, Any]) -> tuple[float, float]:
lo = p["price"].get("minSale") or p["price"].get("minList") or 0.0
hi = p["price"].get("maxSale") or p["price"].get("maxList") or lo
return float(lo), float(hi)
def on_sale(p: dict[str, Any]) -> bool:
return bool(p["price"].get("maxDiscount") or p["price"].get("variationsOnSale"))
def list_price(p: dict[str, Any]) -> tuple[float, float]:
lo = p["price"].get("minList") or 0.0
hi = p["price"].get("maxList") or lo
return float(lo), float(hi)
def categories_of(p: dict[str, Any]) -> list[str]:
return [b["name"] for b in p.get("breadcrumbs", []) if b.get("name")]
def color_families(p: dict[str, Any]) -> list[str]:
"""The payload labels each SKU colour with a family; that is the source's
own colour facet vocabulary."""
out: list[str] = []
for s in p.get("skus", []):
fam = (s.get("colorFamily") or "").strip()
if fam:
label = fam.title()
if label not in out:
out.append(label)
return out
def price_band(p: dict[str, Any]) -> str | None:
value = current_price(p)
for key, _label, lo, hi in PRICE_BANDS:
if lo <= value < hi:
return key
return None
def _attr(p: dict[str, Any], name: str) -> list[str]:
return list(p.get("attributes", {}).get(name, []))
def facet_values(p: dict[str, Any], group: str) -> list[str]:
if group == "categories":
return categories_of(p)
if group == "brand":
return [p["brand"]] if p.get("brand") else []
if group == "color":
return color_families(p)
if group == "sale":
return ["On Sale"] if on_sale(p) else []
if group == "price":
band = price_band(p)
return [band] if band else []
if group.startswith("attr:"):
return _attr(p, group[5:])
return []
def in_stock_skus(p: dict[str, Any]) -> list[dict[str, Any]]:
return [s for s in p.get("skus", []) if s.get("status") == "InStock" and (s.get("stockLevel") or 0) > 0]
def sku_for(p: dict[str, Any], color: str | None, size: str | None) -> dict[str, Any] | None:
for s in p.get("skus", []):
if (color is None or s.get("color") == color) and (size is None or s.get("size") == size):
return s
return None
def color_by_name(p: dict[str, Any], name: str | None) -> dict[str, Any] | None:
for c in p.get("colors", []):
if c.get("name") == name:
return c
return None
def default_color(p: dict[str, Any]) -> dict[str, Any] | None:
key = p.get("selectedColorKey")
for c in p.get("colors", []):
if c.get("key") == key:
return c
return p["colors"][0] if p.get("colors") else None
def gallery_for(p: dict[str, Any], color: dict[str, Any] | None) -> list[str]:
images: list[str] = []
if color:
if color.get("large"):
images.append(color["large"])
images.extend(p.get("detailImagesByColor", {}).get(color.get("id") or "", []))
if not images:
images = [i for i in [p.get("mainImage")] if i] + list(p.get("detailImages", []))
out: list[str] = []
for i in images:
if i and i not in out:
out.append(i)
return out
# --------------------------------------------------------------------------
# listing
# --------------------------------------------------------------------------
def _matches(p: dict[str, Any], selected: dict[str, list[str]]) -> bool:
for group, wanted in selected.items():
if wanted and not set(facet_values(p, group)) & set(wanted):
return False
return True
@dataclass(frozen=True)
class Listing:
items: list[dict[str, Any]]
total: int
page: int
pages: int
facets: list[dict[str, Any]]
sort: str
selected: dict[str, list[str]]
def facet_counts(pool: list[dict[str, Any]], selected: dict[str, list[str]]) -> list[dict[str, Any]]:
"""Count each value against the pool filtered by every *other* group, so
sibling options stay selectable exactly as they do in the source sidebar."""
out = []
for group, label in FACET_GROUPS:
others = {g: v for g, v in selected.items() if g != group}
subset = [p for p in pool if _matches(p, others)]
counts: dict[str, int] = {}
for p in subset:
for value in facet_values(p, group):
counts[value] = counts.get(value, 0) + 1
if not counts:
continue
if group == "price":
keys = [k for k, _l, _lo, _hi in PRICE_BANDS if k in counts]
values = [{"value": k, "label": PRICE_BAND_LABELS[k], "count": counts[k],
"selected": k in selected.get(group, [])} for k in keys]
else:
values = [{"value": v, "label": v, "count": counts[v],
"selected": v in selected.get(group, [])}
for v in sorted(counts, key=lambda v: (-counts[v], v))]
out.append({"group": group, "label": label, "options": values})
return out
def sort_items(items: list[dict[str, Any]], sort: str) -> list[dict[str, Any]]:
if sort == "price-low-high":
return sorted(items, key=current_price)
if sort == "price-high-low":
return sorted(items, key=current_price, reverse=True)
if sort == "top-rated":
return sorted(items, key=lambda p: (-(p["reviews"].get("average") or 0),
-(p["reviews"].get("count") or 0)))
if sort == "most-reviewed":
return sorted(items, key=lambda p: -(p["reviews"].get("count") or 0))
if sort == "brand-a-z":
return sorted(items, key=lambda p: ((p.get("brand") or "").lower(), (p.get("title") or "").lower()))
return sorted(items, key=lambda p: p.get("listingIndex") or 10 ** 6)
def listing(pool: list[dict[str, Any]], *, page: int = 1, sort: str = "featured",
selected: dict[str, list[str]] | None = None) -> Listing:
selected = {g: v for g, v in (selected or {}).items() if v}
facets = facet_counts(pool, selected)
filtered = [p for p in pool if _matches(p, selected)]
ordered = sort_items(filtered, sort)
total = len(ordered)
pages = max(1, (total + PAGE_SIZE - 1) // PAGE_SIZE)
page = max(1, min(page, pages))
start = (page - 1) * PAGE_SIZE
return Listing(items=ordered[start:start + PAGE_SIZE], total=total, page=page,
pages=pages, facets=facets, sort=sort, selected=selected)
# --------------------------------------------------------------------------
# pools
# --------------------------------------------------------------------------
def slugify(label: str) -> str:
return re.sub(r"[^a-z0-9]+", "-", (label or "").lower()).strip("-")
@lru_cache(maxsize=1)
def landings() -> dict[str, list[str]]:
"""Slugs each captured top-level landing page shows, in listing order."""
return catalog().get("landings", {})
@lru_cache(maxsize=1)
def landing_routes() -> dict[str, str]:
"""Map each landing route path to the nav key whose products it serves."""
routes: dict[str, str] = {}
for item in nav():
href = (item.get("href") or "").split("?")[0]
if href and item["key"] in landings():
routes[href] = item["key"]
return routes
@lru_cache(maxsize=1)
def landing_meta_all() -> dict[str, dict[str, Any]]:
return _load("landings.json")
def landing_meta(key: str) -> dict[str, Any]:
return landing_meta_all().get(key, {"h1": key.title(), "subnav": [], "resultCount": None})
def landing_pool(key: str) -> list[dict[str, Any]]:
wanted = landings().get(key, [])
order = {slug: i for i, slug in enumerate(wanted)}
pool = [p for p in products() if p["slug"] in order]
return sorted(pool, key=lambda p: order[p["slug"]])
@lru_cache(maxsize=1)
def category_map() -> dict[str, dict[str, Any]]:
"""Every breadcrumb category the captured catalogue can actually serve."""
out: dict[str, dict[str, Any]] = {}
for p in products():
for b in p.get("breadcrumbs", []):
url = b.get("url") or ""
key = url.rsplit("/", 1)[-1] if url.startswith("/cat/") else slugify(b["name"])
entry = out.setdefault(key, {"slug": key, "name": b["name"], "url": url or f"/cat/{key}", "slugs": []})
if p["slug"] not in entry["slugs"]:
entry["slugs"].append(p["slug"])
return out
def category(slug: str) -> dict[str, Any] | None:
return category_map().get(slug)
def category_pool(slug: str) -> list[dict[str, Any]]:
if slug == "travel":
return list(products())
entry = category(slug)
if not entry:
return []
wanted = set(entry["slugs"])
return [p for p in products() if p["slug"] in wanted]
def brand_map() -> dict[str, dict[str, Any]]:
out: dict[str, dict[str, Any]] = {}
for p in products():
if not p.get("brand"):
continue
key = (p.get("brandUrl") or "").rsplit("/", 1)[-1] or slugify(p["brand"])
entry = out.setdefault(key, {"slug": key, "name": p["brand"], "slugs": []})
entry["slugs"].append(p["slug"])
return out
def brand_pool(slug: str) -> list[dict[str, Any]]:
entry = brand_map().get(slug)
if not entry:
return []
wanted = set(entry["slugs"])
return [p for p in products() if p["slug"] in wanted]
@lru_cache(maxsize=1)
def link_labels() -> dict[str, str]:
"""Every first-party destination the reproduced chrome links to, with the
label the source used for it. Used to serve a real page for a route the
captured data volume does not populate, instead of a dead link."""
labels: dict[str, str] = {}
def note(href: str | None, label: str | None) -> None:
if not href or not href.startswith("/") or href.startswith("//"):
return
text = (label or "").strip()
# Chrome links carry query strings and fragments; index the bare path.
path = href.split("?")[0].split("#")[0]
if path:
labels.setdefault(path, text[:90] or "Shop")
for item in nav():
note(item.get("href"), item.get("label"))
for column in item.get("columns", []):
if column.get("kind") == "promo":
note(column.get("href"), (column.get("caption") or column.get("alt") or "").split(".")[0])
continue
for block in column.get("blocks", []):
if block.get("type") == "heading":
note(block.get("href"), block.get("label"))
for link in block.get("links", []):
note(link.get("href"), link.get("label"))
footer = chrome().get("footer", {})
for column in footer.get("columns", []):
for label, href in column.get("links", []):
note(href, label)
for label, href in footer.get("legal", []):
note(href, label)
for entry in chrome().get("announcements", []) + chrome().get("utility", []):
note(entry.get("href"), entry.get("cta") or entry.get("label"))
for entry in chrome().get("campaign", []):
note(entry.get("href"), entry.get("heading"))
for name, href in chrome().get("category_subnav", {}).get("travel", []):
note(href, name)
for section in home().get("sections", []):
note(section.get("href"), section.get("heading") or section.get("alt"))
for card in section.get("cards", []):
note(card.get("href"), card.get("title") or (card.get("alt") or "").split(".")[0])
return labels
def label_for(path: str) -> str | None:
return link_labels().get(path)
def search_pool(query: str) -> list[dict[str, Any]]:
terms = [t for t in re.split(r"\s+", (query or "").strip().lower()) if t]
if not terms:
return []
out = []
for p in products():
haystack = " ".join(filter(None, [
p.get("brand"), p.get("title"), " ".join(categories_of(p)),
" ".join(c.get("name") or "" for c in p.get("colors", [])),
" ".join(f"{k} {' '.join(v)}" for k, v in (p.get("attributes") or {}).items()),
" ".join(p.get("bulletPoints") or []),
])).lower()
if all(t in haystack for t in terms):
out.append(p)
return out
|