File size: 15,279 Bytes
187ef74 | 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 442 443 444 445 | """Deterministic local commerce models for the source product route families.
Provenance boundary — read before treating anything here as source evidence:
``source-current/playwright-route-inventory-20260821/all-links-probe.json``
records ``Access Denied`` for every one of the 32 ``/pd/`` and 12 ``/pl/``
source URLs, and for both ``/collections/`` and both ``/configure/blinds/``
URLs. No source layout, image, price, rating, review count or specification was
ever observed for those pages, so nothing this module produces may be presented
as source-visually accepted.
* Source-derived: the pathname text only, which the immutable route inventory
already stores.
* Clone-authored: every price, rating, review count, option, specification and
image, drawn from the frozen synthetic catalog seeded by
``backend/seed_data.py``.
Determinism: the only inputs are the URL and the frozen catalog, so the same
URL always renders the same page. No clock and no randomness anywhere.
"""
from __future__ import annotations
import re
import zlib
from typing import Any, Mapping, Sequence
from backend import store as site_store
_WORD_RE = re.compile(r"[A-Za-z0-9]+")
# URL words that carry no catalog meaning and would only add noise to a scope
# lookup.
_STOPWORDS = frozenset(
{
"a", "all", "an", "and", "at", "best", "by", "deal", "deals", "for",
"from", "in", "lowes", "more", "new", "of", "on", "our", "pd", "pl",
"shop", "the", "to", "top", "with", "your",
}
)
# ---------------------------------------------------------------------------
# URL text helpers
# ---------------------------------------------------------------------------
def words(value: str) -> list[str]:
"""Lowercase alphanumeric words from a URL segment."""
return [word.casefold() for word in _WORD_RE.findall(value.replace("-", " "))]
def meaningful_words(value: str) -> list[str]:
seen: list[str] = []
for word in words(value):
if word in _STOPWORDS or word.isdigit() or word in seen:
continue
seen.append(word)
return seen
def humanize(segment: str) -> str:
"""Readable heading text from one URL segment.
Words that are already upper case or that carry a digit keep their captured
spelling, so ``Frigidaire-30-in-Electric-Range`` reads as
``Frigidaire 30 in Electric Range`` rather than being re-cased.
"""
text = re.sub(r"\s+", " ", segment.replace("-", " ").replace("_", " ")).strip()
if not text:
return ""
parts = []
for word in text.split(" "):
if word.isupper() or any(character.isdigit() for character in word):
parts.append(word)
else:
parts.append(word[:1].upper() + word[1:])
return " ".join(parts)
def stable_index(value: str, span: int) -> int:
"""Deterministic index in ``0..span-1`` derived from a URL fragment.
Numeric source ids drive the index directly so neighbouring item ids do not
collapse onto one catalog row; anything else falls back to CRC32, which —
unlike ``hash()`` — is stable across processes.
"""
if span <= 0:
return 0
digits = "".join(character for character in value if character.isdigit())
if digits:
return int(digits[-12:]) % span
return zlib.crc32(value.encode("utf-8")) % span
# ---------------------------------------------------------------------------
# catalog lookups
# ---------------------------------------------------------------------------
def category_index() -> dict[str, dict[str, Any]]:
return {str(row["id"]): dict(row) for row in site_store.categories()}
def category_label(category_id: str) -> str:
row = category_index().get(category_id)
return str(row["label"]) if row else humanize(category_id)
def product_for_item(item_id: str) -> dict[str, Any]:
"""Resolve a source item id onto exactly one local catalog product.
An id that happens to name a local product returns it; every other id maps
through :func:`stable_index`, which is what keeps a source PDP URL rendering
the same synthetic item on every run.
"""
products = site_store.all_products()
if item_id.isdigit():
exact = next((row for row in products if int(row["id"]) == int(item_id)), None)
if exact is not None:
return exact
return products[stable_index(item_id, len(products))]
def related_products(
product: Mapping[str, Any], *, limit: int = 4
) -> list[dict[str, Any]]:
"""Same-category neighbours, ordered by id, wrapping around the category."""
siblings = [
row
for row in site_store.all_products()
if row["category_id"] == product["category_id"] and row["id"] != product["id"]
]
if len(siblings) <= limit:
return siblings
start = stable_index(str(product["id"]), len(siblings))
doubled = siblings + siblings
return doubled[start : start + limit]
# ---------------------------------------------------------------------------
# /pd/{source-slug}/{item-id}
# ---------------------------------------------------------------------------
def product_detail(slug: str, item_id: str) -> dict[str, Any]:
product = product_for_item(item_id)
display_title = humanize(slug) or str(product["title"])
return {
"source_slug": slug,
"source_item_id": item_id,
"display_title": display_title,
"product": product,
"category_label": category_label(str(product["category_id"])),
"related": related_products(product),
"exact_local_item": item_id.isdigit() and int(item_id) == int(product["id"]),
}
# ---------------------------------------------------------------------------
# /pl/{title}/{collection-id} (and the deeper refinement form)
# ---------------------------------------------------------------------------
def list_scope(segments: Sequence[str], collection_id: str) -> dict[str, Any]:
"""Pick the catalog slice a source collection URL maps onto.
Order of preference: a category whose label shares a word with the URL, then
a single URL word the catalog can actually search on, then a category chosen
by :func:`stable_index`. Every branch is a pure function of the URL, so the
same collection id always lands on the same slice.
"""
url_words = []
for segment in segments:
url_words.extend(meaningful_words(segment))
categories = site_store.categories()
for row in categories:
label_words = set(words(str(row["label"])))
if label_words & set(url_words):
return {
"category_id": str(row["id"]),
"label": str(row["label"]),
"query": "",
"basis": "category-word-match",
}
for word in sorted(set(url_words), key=len, reverse=True):
if len(word) < 4:
continue
probe = site_store.search(query=word, page_size=1)
if int(probe["total"]) >= 3:
return {
"category_id": "",
"label": humanize(word),
"query": word,
"basis": "catalog-keyword-match",
}
row = categories[stable_index(collection_id, len(categories))]
return {
"category_id": str(row["id"]),
"label": str(row["label"]),
"query": "",
"basis": "collection-id-mapping",
}
def list_page(
segments: Sequence[str],
collection_id: str,
*,
brands: Sequence[str] = (),
min_price: str = "",
max_price: str = "",
rating: str = "",
pickup: bool = False,
free_delivery: bool = False,
sort: str = "relevance",
page: int = 1,
) -> dict[str, Any]:
"""Run one product-list request against the local catalog."""
scope = list_scope(segments, collection_id)
result = site_store.search(
query=scope["query"],
category_ids=[scope["category_id"]] if scope["category_id"] else (),
brand_names=[name for name in brands if name],
min_price_cents=_cents(min_price),
max_price_cents=_cents(max_price),
min_rating=_number(rating),
pickup_today=pickup,
free_delivery=free_delivery,
sort=sort,
page=page,
)
trail = [humanize(segment) for segment in segments if segment]
return {
"scope": scope,
"result": result,
"trail": trail,
"heading": trail[0] if trail else scope["label"],
"refinements": trail[1:],
"collection_id": collection_id,
}
def _cents(value: str) -> int | None:
text = str(value).strip()
if not text:
return None
try:
return max(0, int(round(float(text) * 100)))
except ValueError:
return None
def _number(value: str) -> float | None:
text = str(value).strip()
if not text:
return None
try:
return float(text)
except ValueError:
return None
# ---------------------------------------------------------------------------
# /collections/{source-slug}/{collection-id}
# ---------------------------------------------------------------------------
PACKAGE_ROLES = (
"Refrigeration",
"Cooking",
"Cleanup",
"Laundry",
)
# Suite discount in basis points, applied to the sum of the member prices. A
# fixed local rule, not an observed Lowe's promotion.
PACKAGE_DISCOUNT_BASIS_POINTS = 1200
def collection_package(slug: str, collection_id: str) -> dict[str, Any]:
"""A four-piece appliance suite assembled from the local catalog."""
appliances = [
row for row in site_store.all_products() if row["category_id"] == "appliances"
]
if not appliances:
appliances = site_store.all_products()
start = stable_index(collection_id, len(appliances))
doubled = appliances + appliances
members = doubled[start : start + len(PACKAGE_ROLES)]
list_total = sum(int(row["price_cents"]) for row in members)
discount = (list_total * PACKAGE_DISCOUNT_BASIS_POINTS) // 10000
return {
"source_slug": slug,
"collection_id": collection_id,
"display_title": humanize(slug),
"members": list(zip(PACKAGE_ROLES, members)),
"product_ids": [int(row["id"]) for row in members],
"list_total_cents": list_total,
"discount_cents": discount,
"package_total_cents": list_total - discount,
}
# ---------------------------------------------------------------------------
# /configure/blinds/{source-slug}/{item-id}
# ---------------------------------------------------------------------------
BLIND_WIDTHS: tuple[int, ...] = tuple(range(18, 73, 2))
BLIND_HEIGHTS: tuple[int, ...] = tuple(range(24, 85, 6))
BLIND_MOUNTS: tuple[tuple[str, str], ...] = (
("inside", "Inside mount"),
("outside", "Outside mount"),
)
# (id, label, surcharge in cents)
BLIND_CONTROLS: tuple[tuple[str, str, int], ...] = (
("cordless", "Cordless lift", 0),
("cord-loop", "Continuous cord loop", 1500),
("motorized", "Motorized lift", 12900),
)
BLIND_COLORS: tuple[tuple[str, str], ...] = (
("smooth-white", "Smooth White"),
("antique-white", "Antique White"),
("driftwood", "Driftwood"),
("espresso", "Espresso"),
)
BLIND_ROOMS: tuple[tuple[str, str], ...] = (
("room-darkening", "Room darkening"),
("light-filtering", "Light filtering"),
("blackout", "Blackout"),
)
# Local pricing rule: the catalog price covers the first five square feet and
# every additional square foot adds this much. Clone-authored, not observed.
BLIND_INCLUDED_SQFT = 5
BLIND_SQFT_CENTS = 320
def blind_defaults(slug: str, item_id: str) -> dict[str, str]:
"""Deterministic starting configuration derived from the source URL."""
return {
"width": str(BLIND_WIDTHS[stable_index(item_id, len(BLIND_WIDTHS))]),
"height": str(BLIND_HEIGHTS[stable_index(item_id + "h", len(BLIND_HEIGHTS))]),
"mount": BLIND_MOUNTS[stable_index(slug, len(BLIND_MOUNTS))][0],
"control": _default_control(slug),
"color": _default_color(slug),
"opacity": BLIND_ROOMS[stable_index(slug + "o", len(BLIND_ROOMS))][0],
}
def _default_control(slug: str) -> str:
lowered = slug.casefold()
for control_id, _label, _extra in BLIND_CONTROLS:
if control_id.replace("-", "") in lowered.replace("-", ""):
return control_id
return BLIND_CONTROLS[stable_index(slug + "c", len(BLIND_CONTROLS))][0]
def _default_color(slug: str) -> str:
lowered = slug.casefold()
for color_id, label in BLIND_COLORS:
if all(word in lowered for word in words(label)):
return color_id
return BLIND_COLORS[stable_index(slug + "k", len(BLIND_COLORS))][0]
def _choice(options: Sequence[tuple[str, ...]], value: str, fallback: str) -> str:
identifiers = [str(option[0]) for option in options]
return value if value in identifiers else fallback
def blind_configuration(
slug: str, item_id: str, selection: Mapping[str, str]
) -> dict[str, Any]:
"""Server-side quote for one blind configuration.
Every field is validated against the frozen option lists, so a hand-edited
query string cannot push an unpriced value into the quote.
"""
product = product_for_item(item_id)
defaults = blind_defaults(slug, item_id)
width = _snap(selection.get("width", defaults["width"]), BLIND_WIDTHS, defaults["width"])
height = _snap(
selection.get("height", defaults["height"]), BLIND_HEIGHTS, defaults["height"]
)
mount = _choice(BLIND_MOUNTS, selection.get("mount", ""), defaults["mount"])
control = _choice(BLIND_CONTROLS, selection.get("control", ""), defaults["control"])
color = _choice(BLIND_COLORS, selection.get("color", ""), defaults["color"])
opacity = _choice(BLIND_ROOMS, selection.get("opacity", ""), defaults["opacity"])
square_feet = (width * height) / 144
oversize = max(0.0, square_feet - BLIND_INCLUDED_SQFT)
size_cents = int(oversize * BLIND_SQFT_CENTS + 0.5)
control_cents = next(
extra for control_id, _label, extra in BLIND_CONTROLS if control_id == control
)
base_cents = int(product["price_cents"])
return {
"source_slug": slug,
"source_item_id": item_id,
"display_title": humanize(slug),
"product": product,
"width": width,
"height": height,
"mount": mount,
"control": control,
"color": color,
"opacity": opacity,
"square_feet": round(square_feet, 2),
"base_cents": base_cents,
"size_cents": size_cents,
"control_cents": control_cents,
"unit_cents": base_cents + size_cents + control_cents,
"labels": {
"mount": dict(BLIND_MOUNTS)[mount],
"control": {
control_id: label for control_id, label, _extra in BLIND_CONTROLS
}[control],
"color": dict(BLIND_COLORS)[color],
"opacity": dict(BLIND_ROOMS)[opacity],
},
}
def _snap(value: str, options: Sequence[int], fallback: str) -> int:
try:
number = int(float(str(value)))
except (TypeError, ValueError):
return int(fallback)
return number if number in options else int(fallback)
|