AgPerry's picture
Add files using upload-large-folder tool
489b6e2 verified
Raw History Blame Contribute Delete
15.3 kB
"""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)