AgPerry's picture
Add files using upload-large-folder tool
489b6e2 verified
Raw History Blame Contribute Delete
54.5 kB
"""Lowe's offline clone — site business schema, catalog, cart and orders.
This module owns everything Lowe's-specific that touches SQLite. The generic
account / session / mail / payment tables are owned by the vendored
``websitebench.site_backend`` and ``websitebench.local_clone_auth`` runtimes in
the *same* bound database file, opened only through
``backend/site_backend_integration.py``.
Contract wiring (``backend/runtime.json``):
* ``database.migration_hook`` -> :func:`migration_hook`
* ``database.seed_hook`` -> :func:`seed_hook`
Both hooks are idempotent and re-runnable, and :func:`ensure_ready` applies the
same work on an already-bound database so a schema addition still lands after
the lifecycle has recorded the one-shot hook.
Determinism: there is no wall clock and no randomness anywhere in this module.
Row identities come from explicit seed ids or from SQLite rowids that restart
after a reset, and every timestamp is :data:`FROZEN_CLOCK_UTC`. Two identical
operation sequences produce identical rows, which
``tests/test_backend_accounts.py::test_reset_restores_a_deterministic_snapshot``
asserts by comparing :func:`state_snapshot` output across a reset.
Payment boundary: the clone never accepts a card number, CVV, expiry, bank or
wallet credential. The only client-supplied payment input is an opaque
``scenario_id`` drawn from the frozen ``local-sandbox`` scenario list; owner,
amount, currency and fingerprint are all derived server-side from the persisted
cart.
"""
from __future__ import annotations
import hashlib
import json
import re
import sqlite3
import threading
from contextlib import closing, contextmanager
from pathlib import Path
from typing import Any, Iterable, Iterator, Mapping, Sequence
from websitebench.local_clone_auth import LocalAuthStore
from websitebench.site_backend import SiteBackend
from backend import seed_data
from backend.site_backend_integration import open_site_services
SITE_ID = "lowes"
CURRENCY = "USD"
# One frozen clock for the whole clone (the day the source observation was
# recorded, UTC). Never call a real clock here.
FROZEN_CLOCK_UTC = "2026-08-20T12:00:00Z"
PICKUP_HOLD_DAYS = 3
FREE_DELIVERY_THRESHOLD_CENTS = 4500
STANDARD_DELIVERY_CENTS = 1999
BULKY_DELIVERY_CENTS = 7999
MAX_LINE_QUANTITY = 99
PAGE_SIZE = 12
SORT_OPTIONS: tuple[tuple[str, str], ...] = (
("relevance", "Best Match"),
("top-sellers", "Top Sellers"),
("price-low", "Price: Low to High"),
("price-high", "Price: High to Low"),
("rating", "Top Rated"),
("savings", "Biggest Savings"),
)
SORT_IDS = frozenset(key for key, _ in SORT_OPTIONS)
FULFILLMENTS = ("pickup", "delivery")
# Sales-tax basis points by shipping state. A frozen local table, not a rate
# service: the clone must never call out.
TAX_BASIS_POINTS: dict[str, int] = {
"AZ": 560,
"CA": 950,
"CO": 290,
"FL": 600,
"GA": 400,
"IL": 625,
"MI": 600,
"NC": 475,
"NJ": 663,
"NV": 685,
"NY": 800,
"OH": 575,
"PA": 600,
"TN": 700,
"TX": 825,
"VA": 530,
"WA": 650,
}
DEFAULT_TAX_BASIS_POINTS = 700
US_STATES: tuple[str, ...] = (
"AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI",
"ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN",
"MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH",
"OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA",
"WV", "WI", "WY",
)
# Any key that looks like a stored payment credential is refused before it can
# reach a business table, mirroring the mandate's "never receive or store card
# number, CVV, expiry, bank or wallet credentials" rule.
_PAYMENT_KEY_RE = re.compile(
r"(?i)(card|cc[-_]?(num|number|exp)|cvv|cvc|\bpan\b|iban|routing"
r"|account[-_]?number|expir|security[-_]?code|payment[-_]?(method|token)"
r"|stripe|bank|wallet)"
)
_SERVER_PAYMENT_FACT_KEYS = frozenset(
{
"adapter",
"amountminor",
"attemptid",
"currency",
"fingerprint",
"flowid",
"owner",
"providerreference",
"providersessionid",
"subtotalcents",
"totalcents",
}
)
class PaymentFieldRejected(ValueError):
"""A card/payment-like key reached a business input path."""
class CheckoutError(ValueError):
"""Checkout input failed server-side validation."""
def __init__(self, errors: Mapping[str, str]) -> None:
super().__init__("checkout validation failed")
self.errors = dict(errors)
def reject_payment_keys(payload: Mapping[str, Any]) -> None:
for key in payload:
normalized = re.sub(r"[^a-z0-9]", "", str(key).casefold())
if _PAYMENT_KEY_RE.search(str(key)) or normalized in _SERVER_PAYMENT_FACT_KEYS:
raise PaymentFieldRejected(
f"payment-like field {key!r} is outside this clone's scope"
)
# ---------------------------------------------------------------------------
# schema
# ---------------------------------------------------------------------------
_MIGRATIONS: tuple[tuple[str, tuple[str, ...]], ...] = (
(
"0001_catalog",
(
"""
CREATE TABLE IF NOT EXISTS lowes_categories (
id TEXT PRIMARY KEY,
label TEXT NOT NULL,
position INTEGER NOT NULL,
art_light TEXT NOT NULL,
art_dark TEXT NOT NULL
)
""",
"""
CREATE TABLE IF NOT EXISTS lowes_products (
id INTEGER PRIMARY KEY,
slug TEXT NOT NULL UNIQUE,
title TEXT NOT NULL,
brand TEXT NOT NULL,
category_id TEXT NOT NULL REFERENCES lowes_categories (id),
price_cents INTEGER NOT NULL CHECK (price_cents > 0),
was_cents INTEGER CHECK (was_cents IS NULL OR was_cents > price_cents),
rating REAL NOT NULL CHECK (rating >= 0 AND rating <= 5),
review_count INTEGER NOT NULL CHECK (review_count >= 0),
badge TEXT,
model_number TEXT NOT NULL,
keywords TEXT NOT NULL,
stock INTEGER NOT NULL CHECK (stock >= 0),
pickup_today INTEGER NOT NULL CHECK (pickup_today IN (0, 1)),
free_delivery INTEGER NOT NULL CHECK (free_delivery IN (0, 1)),
delivery_days INTEGER NOT NULL CHECK (delivery_days > 0),
specs_json TEXT NOT NULL,
summary TEXT NOT NULL
)
""",
"CREATE INDEX IF NOT EXISTS idx_lowes_products_category"
" ON lowes_products (category_id)",
"""
CREATE TABLE IF NOT EXISTS lowes_stores (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
city TEXT NOT NULL,
state TEXT NOT NULL,
zip TEXT NOT NULL,
closes_at TEXT NOT NULL,
position INTEGER NOT NULL
)
""",
),
),
(
"0002_cart",
(
"""
CREATE TABLE IF NOT EXISTS lowes_cart_items (
id INTEGER PRIMARY KEY,
owner_digest TEXT NOT NULL,
product_id INTEGER NOT NULL
REFERENCES lowes_products (id) ON DELETE CASCADE,
quantity INTEGER NOT NULL CHECK (quantity BETWEEN 1 AND 99),
fulfillment TEXT NOT NULL
CHECK (fulfillment IN ('pickup', 'delivery')),
store_id TEXT REFERENCES lowes_stores (id),
unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents > 0),
unit_was_cents INTEGER,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE (owner_digest, product_id, fulfillment)
)
""",
"CREATE INDEX IF NOT EXISTS idx_lowes_cart_owner"
" ON lowes_cart_items (owner_digest)",
),
),
(
"0003_orders",
(
"""
CREATE TABLE IF NOT EXISTS lowes_orders (
id INTEGER PRIMARY KEY,
order_number TEXT NOT NULL UNIQUE,
owner_digest TEXT NOT NULL,
account_id TEXT,
email TEXT NOT NULL,
customer_name TEXT NOT NULL,
fulfillment TEXT NOT NULL
CHECK (fulfillment IN ('pickup', 'delivery')),
store_id TEXT REFERENCES lowes_stores (id),
address_json TEXT,
subtotal_cents INTEGER NOT NULL CHECK (subtotal_cents >= 0),
savings_cents INTEGER NOT NULL CHECK (savings_cents >= 0),
delivery_cents INTEGER NOT NULL CHECK (delivery_cents >= 0),
tax_cents INTEGER NOT NULL CHECK (tax_cents >= 0),
total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
currency TEXT NOT NULL,
fingerprint TEXT NOT NULL,
payment_flow_id TEXT NOT NULL UNIQUE,
payment_attempt_id TEXT NOT NULL UNIQUE,
scenario_id TEXT NOT NULL,
mail_id TEXT UNIQUE,
status TEXT NOT NULL CHECK (status IN ('placed')),
created_at TEXT NOT NULL
)
""",
"CREATE INDEX IF NOT EXISTS idx_lowes_orders_owner"
" ON lowes_orders (owner_digest)",
"""
CREATE TABLE IF NOT EXISTS lowes_order_items (
id INTEGER PRIMARY KEY,
order_id INTEGER NOT NULL
REFERENCES lowes_orders (id) ON DELETE CASCADE,
product_id INTEGER NOT NULL,
title TEXT NOT NULL,
brand TEXT NOT NULL,
slug TEXT NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents > 0),
line_total_cents INTEGER NOT NULL CHECK (line_total_cents > 0),
fulfillment TEXT NOT NULL
)
""",
"CREATE INDEX IF NOT EXISTS idx_lowes_order_items_order"
" ON lowes_order_items (order_id)",
),
),
)
def _apply_migrations(connection: sqlite3.Connection) -> list[str]:
"""Apply every pending site migration inside the caller's connection.
Uses individual ``execute`` calls rather than ``executescript`` because the
lifecycle hook runs inside an open ``BEGIN IMMEDIATE`` transaction and
``executescript`` would commit it.
"""
connection.execute(
"""
CREATE TABLE IF NOT EXISTS lowes_schema_migrations (
migration_id TEXT PRIMARY KEY,
applied_at TEXT NOT NULL
)
"""
)
applied = {
str(row[0])
for row in connection.execute(
"SELECT migration_id FROM lowes_schema_migrations"
)
}
newly: list[str] = []
for migration_id, statements in _MIGRATIONS:
if migration_id in applied:
continue
for statement in statements:
connection.execute(statement)
connection.execute(
"INSERT INTO lowes_schema_migrations (migration_id, applied_at)"
" VALUES (?, ?)",
(migration_id, FROZEN_CLOCK_UTC),
)
newly.append(migration_id)
return newly
def _seed_catalog(connection: sqlite3.Connection) -> None:
"""Insert the frozen catalog. Idempotent and order-stable."""
for category in seed_data.CATEGORIES:
connection.execute(
"INSERT OR REPLACE INTO lowes_categories"
" (id, label, position, art_light, art_dark) VALUES (?, ?, ?, ?, ?)",
(
category["id"],
category["label"],
category["position"],
category["art"][0],
category["art"][1],
),
)
for store in seed_data.STORES:
connection.execute(
"INSERT OR REPLACE INTO lowes_stores"
" (id, name, city, state, zip, closes_at, position)"
" VALUES (?, ?, ?, ?, ?, ?, ?)",
(
store["id"],
store["name"],
store["city"],
store["state"],
store["zip"],
store["closes_at"],
store["position"],
),
)
for product in seed_data.PRODUCTS:
connection.execute(
"INSERT OR REPLACE INTO lowes_products"
" (id, slug, title, brand, category_id, price_cents, was_cents,"
" rating, review_count, badge, model_number, keywords, stock,"
" pickup_today, free_delivery, delivery_days, specs_json, summary)"
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
product["id"],
product["slug"],
product["title"],
product["brand"],
product["category_id"],
product["price_cents"],
product["was_cents"],
product["rating"],
product["review_count"],
product["badge"],
product["model_number"],
product["keywords"],
product["stock"],
product["pickup_today"],
product["free_delivery"],
product["delivery_days"],
json.dumps(product["specs"], sort_keys=False, separators=(",", ":")),
product["summary"],
),
)
def migration_hook(connection: sqlite3.Connection) -> None:
"""Runtime-declared migration hook (``backend.store:migration_hook``)."""
_apply_migrations(connection)
def seed_hook(connection: sqlite3.Connection) -> None:
"""Runtime-declared seed hook (``backend.store:seed_hook``)."""
_apply_migrations(connection)
_seed_catalog(connection)
# ---------------------------------------------------------------------------
# services
# ---------------------------------------------------------------------------
_SERVICES_LOCK = threading.Lock()
_SERVICES: tuple[SiteBackend, LocalAuthStore] | None = None
def services() -> tuple[SiteBackend, LocalAuthStore]:
global _SERVICES
with _SERVICES_LOCK:
if _SERVICES is None:
backend, auth = open_site_services()
ensure_ready(backend.lifecycle.database_path)
_SERVICES = (backend, auth)
return _SERVICES
def close_services() -> None:
"""Drop the cached pair so a test can re-open against a fresh database."""
global _SERVICES
with _SERVICES_LOCK:
_SERVICES = None
def database_path() -> Path:
return services()[0].lifecycle.database_path
def _connect(path: Path) -> sqlite3.Connection:
# Autocommit at the driver level so every write path owns an explicit
# ``BEGIN IMMEDIATE``; the vendored payment/mail APIs require a caller
# transaction that is genuinely open.
connection = sqlite3.connect(str(path), timeout=30, isolation_level=None)
connection.row_factory = sqlite3.Row
connection.execute("PRAGMA foreign_keys = ON")
connection.execute("PRAGMA busy_timeout = 30000")
return connection
def connect() -> sqlite3.Connection:
return _connect(database_path())
@contextmanager
def transaction(connection: sqlite3.Connection) -> Iterator[sqlite3.Connection]:
connection.execute("BEGIN IMMEDIATE")
try:
yield connection
except BaseException:
if connection.in_transaction:
connection.execute("ROLLBACK")
raise
else:
if connection.in_transaction:
connection.execute("COMMIT")
def ensure_ready(path: Path) -> None:
"""Apply pending migrations and seed rows on an already-bound database."""
with closing(_connect(path)) as connection, transaction(connection):
_apply_migrations(connection)
empty = (
connection.execute("SELECT COUNT(*) FROM lowes_products").fetchone()[0] == 0
)
if empty:
_seed_catalog(connection)
def reset() -> dict[str, Any]:
"""Deterministically restore the seeded state in one transaction."""
backend, auth = services()
def _site_reset(connection: sqlite3.Connection) -> None:
for table in (
"lowes_order_items",
"lowes_orders",
"lowes_cart_items",
"lowes_products",
"lowes_stores",
"lowes_categories",
):
connection.execute(f"DELETE FROM {table}")
# No site table uses AUTOINCREMENT, so clearing the rows also restarts
# the implicit rowid counters and order numbers stay reproducible.
_apply_migrations(connection)
_seed_catalog(connection)
backend.lifecycle.reset_embedded(connection, confirm_site_id=SITE_ID)
auth.reset_site_state(site_reset=_site_reset, seed_accounts=[])
return {"reset": True, "site_id": SITE_ID, "seed_id": seed_data.SEED_ID}
def state_snapshot() -> dict[str, Any]:
"""A stable, comparable projection of every site-owned table."""
with closing(connect()) as connection:
snapshot: dict[str, Any] = {}
for table, order in (
("lowes_categories", "position, id"),
("lowes_stores", "position, id"),
("lowes_products", "id"),
("lowes_cart_items", "owner_digest, product_id, fulfillment"),
("lowes_orders", "id"),
("lowes_order_items", "id"),
):
rows = connection.execute(
f"SELECT * FROM {table} ORDER BY {order}"
).fetchall()
snapshot[table] = [dict(row) for row in rows]
return snapshot
# ---------------------------------------------------------------------------
# catalog reads
# ---------------------------------------------------------------------------
def _product_public(row: sqlite3.Row) -> dict[str, Any]:
return {
"id": int(row["id"]),
"slug": str(row["slug"]),
"title": str(row["title"]),
"brand": str(row["brand"]),
"category_id": str(row["category_id"]),
"price_cents": int(row["price_cents"]),
"was_cents": int(row["was_cents"]) if row["was_cents"] is not None else None,
"rating": float(row["rating"]),
"review_count": int(row["review_count"]),
"badge": row["badge"],
"model_number": str(row["model_number"]),
"keywords": str(row["keywords"]),
"stock": int(row["stock"]),
"pickup_today": bool(row["pickup_today"]),
"free_delivery": bool(row["free_delivery"]),
"delivery_days": int(row["delivery_days"]),
"specs": json.loads(row["specs_json"]),
"summary": str(row["summary"]),
"url": f"/pd/{row['slug']}/{int(row['id'])}",
}
def categories() -> list[dict[str, Any]]:
with closing(connect()) as connection:
return [
dict(row)
for row in connection.execute(
"SELECT * FROM lowes_categories ORDER BY position, id"
)
]
def stores() -> list[dict[str, Any]]:
with closing(connect()) as connection:
return [
dict(row)
for row in connection.execute(
"SELECT * FROM lowes_stores ORDER BY position, id"
)
]
def get_store(store_id: str | None) -> dict[str, Any] | None:
if not store_id:
return None
with closing(connect()) as connection:
row = connection.execute(
"SELECT * FROM lowes_stores WHERE id = ?", (store_id,)
).fetchone()
return dict(row) if row is not None else None
def all_products() -> list[dict[str, Any]]:
with closing(connect()) as connection:
return [
_product_public(row)
for row in connection.execute("SELECT * FROM lowes_products ORDER BY id")
]
def get_product(product_id: int) -> dict[str, Any] | None:
with closing(connect()) as connection:
row = connection.execute(
"SELECT * FROM lowes_products WHERE id = ?", (product_id,)
).fetchone()
return _product_public(row) if row is not None else None
def products_by_ids(product_ids: Sequence[int]) -> list[dict[str, Any]]:
if not product_ids:
return []
placeholders = ",".join("?" for _ in product_ids)
with closing(connect()) as connection:
rows = connection.execute(
f"SELECT * FROM lowes_products WHERE id IN ({placeholders})",
tuple(product_ids),
).fetchall()
by_id = {int(row["id"]): _product_public(row) for row in rows}
return [by_id[pid] for pid in product_ids if pid in by_id]
def brands() -> list[str]:
with closing(connect()) as connection:
return [
str(row[0])
for row in connection.execute(
"SELECT DISTINCT brand FROM lowes_products ORDER BY brand"
)
]
# ---------------------------------------------------------------------------
# search
# ---------------------------------------------------------------------------
_TOKEN_RE = re.compile(r"[a-z0-9]+")
def _tokens(text: str) -> list[str]:
return _TOKEN_RE.findall(text.casefold())
def _relevance(product: Mapping[str, Any], category_label: str, tokens: Sequence[str]) -> int:
if not tokens:
return 0
title = product["title"].casefold()
brand = product["brand"].casefold()
keywords = product["keywords"].casefold()
category = category_label.casefold()
score = 0
for token in tokens:
hit = 0
if token in title:
hit += 6
if title.startswith(token):
hit += 3
if token in brand:
hit += 4
if token in keywords:
hit += 3
if token in category:
hit += 2
if token in product["model_number"].casefold():
hit += 2
if hit == 0:
return 0 # every token must match somewhere
score += hit
return score
def search(
*,
query: str = "",
category_ids: Sequence[str] = (),
brand_names: Sequence[str] = (),
min_price_cents: int | None = None,
max_price_cents: int | None = None,
min_rating: float | None = None,
pickup_today: bool = False,
free_delivery: bool = False,
sort: str = "relevance",
page: int = 1,
page_size: int = PAGE_SIZE,
) -> dict[str, Any]:
"""Server-side search: token filter, facet filters, sort, then paginate.
The catalog is small and frozen, so ranking runs in Python over the rows
SQLite already narrowed. Ordering is fully deterministic: every comparison
ends with the product id so ties never depend on row order.
"""
if sort not in SORT_IDS:
sort = "relevance"
page_size = max(1, min(48, int(page_size)))
clauses: list[str] = []
parameters: list[Any] = []
if category_ids:
clauses.append(
"category_id IN (" + ",".join("?" for _ in category_ids) + ")"
)
parameters.extend(category_ids)
if brand_names:
clauses.append("brand IN (" + ",".join("?" for _ in brand_names) + ")")
parameters.extend(brand_names)
if min_price_cents is not None:
clauses.append("price_cents >= ?")
parameters.append(int(min_price_cents))
if max_price_cents is not None:
clauses.append("price_cents <= ?")
parameters.append(int(max_price_cents))
if min_rating is not None:
clauses.append("rating >= ?")
parameters.append(float(min_rating))
if pickup_today:
clauses.append("pickup_today = 1")
if free_delivery:
clauses.append("free_delivery = 1")
where = (" WHERE " + " AND ".join(clauses)) if clauses else ""
with closing(connect()) as connection:
rows = connection.execute(
f"SELECT * FROM lowes_products{where} ORDER BY id", tuple(parameters)
).fetchall()
labels = {
str(row["id"]): str(row["label"])
for row in connection.execute("SELECT id, label FROM lowes_categories")
}
tokens = _tokens(query)
scored: list[tuple[int, dict[str, Any]]] = []
for row in rows:
product = _product_public(row)
score = _relevance(product, labels.get(product["category_id"], ""), tokens)
if tokens and score == 0:
continue
scored.append((score, product))
if sort == "price-low":
scored.sort(key=lambda item: (item[1]["price_cents"], item[1]["id"]))
elif sort == "price-high":
scored.sort(key=lambda item: (-item[1]["price_cents"], item[1]["id"]))
elif sort == "rating":
scored.sort(
key=lambda item: (-item[1]["rating"], -item[1]["review_count"], item[1]["id"])
)
elif sort == "top-sellers":
scored.sort(key=lambda item: (-item[1]["review_count"], item[1]["id"]))
elif sort == "savings":
scored.sort(
key=lambda item: (
-((item[1]["was_cents"] or item[1]["price_cents"]) - item[1]["price_cents"]),
item[1]["id"],
)
)
else:
scored.sort(key=lambda item: (-item[0], -item[1]["review_count"], item[1]["id"]))
total = len(scored)
page_count = max(1, (total + page_size - 1) // page_size)
page = max(1, min(int(page), page_count))
start = (page - 1) * page_size
window = [product for _, product in scored[start : start + page_size]]
facet_categories: dict[str, int] = {}
facet_brands: dict[str, int] = {}
for _, product in scored:
facet_categories[product["category_id"]] = (
facet_categories.get(product["category_id"], 0) + 1
)
facet_brands[product["brand"]] = facet_brands.get(product["brand"], 0) + 1
return {
"query": query,
"total": total,
"page": page,
"page_size": page_size,
"page_count": page_count,
"first_index": start + 1 if total else 0,
"last_index": min(start + page_size, total),
"sort": sort,
"products": window,
"facet_categories": facet_categories,
"facet_brands": facet_brands,
}
def suggest(query: str, *, limit: int = 8) -> dict[str, Any]:
"""Autocomplete groups: matching products, then matching categories."""
text = query.strip()
if len(text) < 2:
return {"query": text, "groups": []}
tokens = _tokens(text)
with closing(connect()) as connection:
rows = connection.execute("SELECT * FROM lowes_products ORDER BY id").fetchall()
category_rows = connection.execute(
"SELECT * FROM lowes_categories ORDER BY position, id"
).fetchall()
labels = {str(row["id"]): str(row["label"]) for row in category_rows}
ranked: list[tuple[int, dict[str, Any]]] = []
for row in rows:
product = _product_public(row)
score = _relevance(product, labels.get(product["category_id"], ""), tokens)
if score:
ranked.append((score, product))
ranked.sort(key=lambda item: (-item[0], -item[1]["review_count"], item[1]["id"]))
product_items = [
{
"label": product["title"],
"href": product["url"],
"kind": "product",
"price_cents": product["price_cents"],
}
for _, product in ranked[:limit]
]
category_items = [
{
"label": str(row["label"]),
"href": f"/search?category={row['id']}",
"kind": "category",
}
for row in category_rows
if any(token in str(row["label"]).casefold() for token in tokens)
][:4]
keyword_items = [
{"label": term, "href": f"/search?q={term.replace(' ', '+')}", "kind": "keyword"}
for term in seed_data.RECOMMENDED_SEARCHES
if any(token in term.casefold() for token in tokens)
][:4]
groups = []
if keyword_items:
groups.append({"label": "Suggested searches", "items": keyword_items})
if product_items:
groups.append({"label": "Products", "items": product_items})
if category_items:
groups.append({"label": "Departments", "items": category_items})
return {"query": text, "groups": groups}
# ---------------------------------------------------------------------------
# cart
# ---------------------------------------------------------------------------
def owner_token(session_digest: str) -> str:
"""Payment owner identity derived from the server-side session digest."""
return f"session:{session_digest}"
def _cart_rows(connection: sqlite3.Connection, owner_digest: str) -> list[sqlite3.Row]:
return connection.execute(
"SELECT c.*, p.slug, p.title, p.brand, p.category_id, p.rating,"
" p.review_count, p.free_delivery, p.delivery_days, p.stock,"
" p.pickup_today AS product_pickup_today"
" FROM lowes_cart_items AS c"
" JOIN lowes_products AS p ON p.id = c.product_id"
" WHERE c.owner_digest = ?"
" ORDER BY c.id",
(owner_digest,),
).fetchall()
def _cart_public(rows: Iterable[sqlite3.Row]) -> dict[str, Any]:
items: list[dict[str, Any]] = []
subtotal = 0
savings = 0
units = 0
needs_delivery = False
all_free_delivery = True
for row in rows:
quantity = int(row["quantity"])
unit = int(row["unit_price_cents"])
line_total = unit * quantity
was = int(row["unit_was_cents"]) if row["unit_was_cents"] is not None else None
subtotal += line_total
units += quantity
if was is not None:
savings += (was - unit) * quantity
if str(row["fulfillment"]) == "delivery":
needs_delivery = True
if not int(row["free_delivery"]):
all_free_delivery = False
items.append(
{
"item_id": int(row["id"]),
"product_id": int(row["product_id"]),
"slug": str(row["slug"]),
"title": str(row["title"]),
"brand": str(row["brand"]),
"quantity": quantity,
"fulfillment": str(row["fulfillment"]),
"store_id": row["store_id"],
"unit_price_cents": unit,
"unit_was_cents": was,
"line_total_cents": line_total,
"delivery_days": int(row["delivery_days"]),
"free_delivery": bool(row["free_delivery"]),
"url": f"/pd/{row['slug']}/{int(row['product_id'])}",
}
)
return {
"items": items,
"count": len(items),
"units": units,
"subtotal_cents": subtotal,
"savings_cents": savings,
"needs_delivery": needs_delivery,
"all_free_delivery": all_free_delivery,
}
def get_cart(owner_digest: str) -> dict[str, Any]:
with closing(connect()) as connection:
return _cart_public(_cart_rows(connection, owner_digest))
def cart_units(owner_digest: str) -> int:
with closing(connect()) as connection:
row = connection.execute(
"SELECT COALESCE(SUM(quantity), 0) FROM lowes_cart_items"
" WHERE owner_digest = ?",
(owner_digest,),
).fetchone()
return int(row[0])
def add_to_cart(
owner_digest: str,
*,
product_id: int,
quantity: int = 1,
fulfillment: str = "pickup",
store_id: str | None = None,
) -> dict[str, Any]:
if fulfillment not in FULFILLMENTS:
raise CheckoutError({"fulfillment": "Choose store pickup or delivery."})
quantity = max(1, min(MAX_LINE_QUANTITY, int(quantity)))
with closing(connect()) as connection, transaction(connection):
product = connection.execute(
"SELECT * FROM lowes_products WHERE id = ?", (product_id,)
).fetchone()
if product is None:
raise CheckoutError({"product": "That product is not in this catalog."})
if fulfillment == "pickup" and not int(product["pickup_today"]):
raise CheckoutError(
{"fulfillment": "This item is not available for store pickup."}
)
resolved_store = store_id if fulfillment == "pickup" else None
if resolved_store is None and fulfillment == "pickup":
resolved_store = seed_data.DEFAULT_STORE_ID
existing = connection.execute(
"SELECT id, quantity FROM lowes_cart_items"
" WHERE owner_digest = ? AND product_id = ? AND fulfillment = ?",
(owner_digest, product_id, fulfillment),
).fetchone()
if existing is None:
connection.execute(
"INSERT INTO lowes_cart_items"
" (owner_digest, product_id, quantity, fulfillment, store_id,"
" unit_price_cents, unit_was_cents, created_at, updated_at)"
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
owner_digest,
product_id,
quantity,
fulfillment,
resolved_store,
int(product["price_cents"]),
product["was_cents"],
FROZEN_CLOCK_UTC,
FROZEN_CLOCK_UTC,
),
)
else:
merged = min(MAX_LINE_QUANTITY, int(existing["quantity"]) + quantity)
connection.execute(
"UPDATE lowes_cart_items SET quantity = ?, updated_at = ?"
" WHERE id = ?",
(merged, FROZEN_CLOCK_UTC, int(existing["id"])),
)
rows = _cart_rows(connection, owner_digest)
return _cart_public(rows)
def update_cart_item(
owner_digest: str, *, item_id: int, quantity: int
) -> dict[str, Any]:
quantity = int(quantity)
with closing(connect()) as connection, transaction(connection):
owned = connection.execute(
"SELECT id FROM lowes_cart_items WHERE id = ? AND owner_digest = ?",
(item_id, owner_digest),
).fetchone()
if owned is None:
raise CheckoutError({"item": "That cart line is not yours."})
if quantity <= 0:
connection.execute("DELETE FROM lowes_cart_items WHERE id = ?", (item_id,))
else:
connection.execute(
"UPDATE lowes_cart_items SET quantity = ?, updated_at = ? WHERE id = ?",
(min(MAX_LINE_QUANTITY, quantity), FROZEN_CLOCK_UTC, item_id),
)
rows = _cart_rows(connection, owner_digest)
return _cart_public(rows)
def set_cart_item_fulfillment(
owner_digest: str, *, item_id: int, fulfillment: str, store_id: str | None = None
) -> dict[str, Any]:
if fulfillment not in FULFILLMENTS:
raise CheckoutError({"fulfillment": "Choose store pickup or delivery."})
with closing(connect()) as connection, transaction(connection):
line = connection.execute(
"SELECT c.*, p.pickup_today FROM lowes_cart_items AS c"
" JOIN lowes_products AS p ON p.id = c.product_id"
" WHERE c.id = ? AND c.owner_digest = ?",
(item_id, owner_digest),
).fetchone()
if line is None:
raise CheckoutError({"item": "That cart line is not yours."})
if fulfillment == "pickup" and not int(line["pickup_today"]):
raise CheckoutError(
{"fulfillment": "This item is not available for store pickup."}
)
duplicate = connection.execute(
"SELECT id, quantity FROM lowes_cart_items"
" WHERE owner_digest = ? AND product_id = ? AND fulfillment = ? AND id <> ?",
(owner_digest, int(line["product_id"]), fulfillment, item_id),
).fetchone()
resolved_store = (
(store_id or str(line["store_id"] or seed_data.DEFAULT_STORE_ID))
if fulfillment == "pickup"
else None
)
if duplicate is not None:
merged = min(
MAX_LINE_QUANTITY, int(duplicate["quantity"]) + int(line["quantity"])
)
connection.execute(
"UPDATE lowes_cart_items SET quantity = ?, updated_at = ? WHERE id = ?",
(merged, FROZEN_CLOCK_UTC, int(duplicate["id"])),
)
connection.execute("DELETE FROM lowes_cart_items WHERE id = ?", (item_id,))
else:
connection.execute(
"UPDATE lowes_cart_items SET fulfillment = ?, store_id = ?,"
" updated_at = ? WHERE id = ?",
(fulfillment, resolved_store, FROZEN_CLOCK_UTC, item_id),
)
rows = _cart_rows(connection, owner_digest)
return _cart_public(rows)
def remove_cart_item(owner_digest: str, *, item_id: int) -> dict[str, Any]:
return update_cart_item(owner_digest, item_id=item_id, quantity=0)
def clear_cart(owner_digest: str) -> None:
with closing(connect()) as connection, transaction(connection):
connection.execute(
"DELETE FROM lowes_cart_items WHERE owner_digest = ?", (owner_digest,)
)
def migrate_owner(
connection: sqlite3.Connection, old_digest: str, new_digest: str
) -> None:
"""Move an anonymous cart onto the rotated authenticated session.
Registered as ``session_rotation_callback`` so the move happens inside the
same auth transaction that revokes the old session and creates the new one.
"""
if old_digest == new_digest:
return
for row in connection.execute(
"SELECT id, product_id, quantity, fulfillment FROM lowes_cart_items"
" WHERE owner_digest = ? ORDER BY id",
(old_digest,),
).fetchall():
duplicate = connection.execute(
"SELECT id, quantity FROM lowes_cart_items"
" WHERE owner_digest = ? AND product_id = ? AND fulfillment = ?",
(new_digest, int(row["product_id"]), str(row["fulfillment"])),
).fetchone()
if duplicate is None:
connection.execute(
"UPDATE lowes_cart_items SET owner_digest = ?, updated_at = ?"
" WHERE id = ?",
(new_digest, FROZEN_CLOCK_UTC, int(row["id"])),
)
else:
merged = min(
MAX_LINE_QUANTITY, int(duplicate["quantity"]) + int(row["quantity"])
)
connection.execute(
"UPDATE lowes_cart_items SET quantity = ?, updated_at = ? WHERE id = ?",
(merged, FROZEN_CLOCK_UTC, int(duplicate["id"])),
)
connection.execute(
"DELETE FROM lowes_cart_items WHERE id = ?", (int(row["id"]),)
)
# ---------------------------------------------------------------------------
# pricing
# ---------------------------------------------------------------------------
def _round_half_up(value: float) -> int:
return int(value + 0.5)
def price_cart(
cart: Mapping[str, Any], *, fulfillment: str, state: str | None
) -> dict[str, Any]:
subtotal = int(cart["subtotal_cents"])
if fulfillment == "pickup":
delivery = 0
elif subtotal >= FREE_DELIVERY_THRESHOLD_CENTS and cart["all_free_delivery"]:
delivery = 0
elif cart["all_free_delivery"]:
delivery = STANDARD_DELIVERY_CENTS
else:
delivery = BULKY_DELIVERY_CENTS
basis = TAX_BASIS_POINTS.get((state or "").upper(), DEFAULT_TAX_BASIS_POINTS)
tax = _round_half_up((subtotal + delivery) * basis / 10000)
return {
"subtotal_cents": subtotal,
"savings_cents": int(cart["savings_cents"]),
"delivery_cents": delivery,
"tax_cents": tax,
"tax_basis_points": basis,
"total_cents": subtotal + delivery + tax,
"currency": CURRENCY,
}
def _fingerprint(payload: Mapping[str, Any]) -> str:
canonical = json.dumps(
payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")
)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def _order_number(row_id: int) -> str:
return f"LWS-{700000 + row_id}"
# ---------------------------------------------------------------------------
# checkout validation
# ---------------------------------------------------------------------------
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$")
_ZIP_RE = re.compile(r"^\d{5}$")
_NAME_RE = re.compile(r"^[A-Za-z][A-Za-z .'-]{0,59}$")
def _clean(value: Any, limit: int = 120) -> str:
return " ".join(str(value).split())[:limit] if isinstance(value, str) else ""
def validate_checkout(
form: Mapping[str, Any], *, cart: Mapping[str, Any], scenario_ids: Sequence[str]
) -> dict[str, Any]:
reject_payment_keys(form)
errors: dict[str, str] = {}
fulfillment = _clean(form.get("fulfillment"), 20) or "pickup"
if fulfillment not in FULFILLMENTS:
errors["fulfillment"] = "Choose store pickup or delivery."
fulfillment = "pickup"
first_name = _clean(form.get("first_name"), 60)
last_name = _clean(form.get("last_name"), 60)
email = _clean(form.get("email"), 200).casefold()
if not _NAME_RE.match(first_name):
errors["first_name"] = "Enter a first name."
if not _NAME_RE.match(last_name):
errors["last_name"] = "Enter a last name."
if not _EMAIL_RE.match(email):
errors["email"] = "Enter a valid email address."
address: dict[str, str] | None = None
store_id: str | None = None
state: str | None = None
if fulfillment == "delivery":
address_1 = _clean(form.get("address_1"), 120)
address_2 = _clean(form.get("address_2"), 120)
city = _clean(form.get("city"), 80)
state = _clean(form.get("state"), 2).upper()
postal = _clean(form.get("zip"), 10)
if len(address_1) < 4:
errors["address_1"] = "Enter a street address."
if len(city) < 2:
errors["city"] = "Enter a city."
if state not in US_STATES:
errors["state"] = "Enter a two-letter US state code."
if not _ZIP_RE.match(postal):
errors["zip"] = "Enter a five-digit ZIP code."
address = {
"address_1": address_1,
"address_2": address_2,
"city": city,
"state": state,
"zip": postal,
}
else:
store_id = _clean(form.get("store_id"), 40) or seed_data.DEFAULT_STORE_ID
known = {store["id"] for store in stores()}
if store_id not in known:
errors["store_id"] = "Choose a store for pickup."
state = next(
(store["state"] for store in stores() if store["id"] == store_id), None
)
scenario_id = _clean(form.get("scenario_id"), 80)
if scenario_id not in set(scenario_ids):
errors["scenario_id"] = "Choose a local sandbox payment scenario."
if not cart["items"]:
errors["cart"] = "Your cart is empty."
if fulfillment == "delivery" and not cart["items"]:
errors.setdefault("cart", "Your cart is empty.")
if errors:
raise CheckoutError(errors)
return {
"fulfillment": fulfillment,
"first_name": first_name,
"last_name": last_name,
"customer_name": f"{first_name} {last_name}",
"email": email,
"address": address,
"store_id": store_id,
"state": state,
"scenario_id": scenario_id,
}
# ---------------------------------------------------------------------------
# checkout
# ---------------------------------------------------------------------------
def place_order(
owner_digest: str,
checkout: Mapping[str, Any],
*,
account_id: str | None = None,
) -> dict[str, Any]:
"""Run one payment attempt and, on approval, persist the order atomically.
The payment approval is consumed inside the same SQLite transaction that
writes the order snapshot and empties the cart, so no approval can be
replayed against a second order and no order can exist without a consumed
approval.
"""
backend, _auth = services()
cart = get_cart(owner_digest)
if not cart["items"]:
raise CheckoutError({"cart": "Your cart is empty."})
fulfillment = str(checkout["fulfillment"])
totals = price_cart(cart, fulfillment=fulfillment, state=checkout.get("state"))
owner = owner_token(owner_digest)
snapshot = {
"site_id": SITE_ID,
"fulfillment": fulfillment,
"store_id": checkout.get("store_id"),
"state": checkout.get("state"),
"email": checkout["email"],
"lines": [
{
"product_id": item["product_id"],
"quantity": item["quantity"],
"unit_price_cents": item["unit_price_cents"],
"fulfillment": item["fulfillment"],
}
for item in cart["items"]
],
"subtotal_cents": totals["subtotal_cents"],
"delivery_cents": totals["delivery_cents"],
"tax_cents": totals["tax_cents"],
"total_cents": totals["total_cents"],
"currency": CURRENCY,
}
fingerprint = _fingerprint(snapshot)
scenario_id = str(checkout["scenario_id"])
with closing(connect()) as connection:
connection.execute("BEGIN IMMEDIATE")
try:
existing = connection.execute(
"SELECT * FROM lowes_orders WHERE owner_digest = ? AND fingerprint = ?",
(owner_digest, fingerprint),
).fetchone()
if existing is not None:
connection.execute("COMMIT")
return {
"placed": True,
"already": True,
"order": get_order(str(existing["order_number"])),
}
flow = backend.payments.create_intent(
owner=owner,
amount_minor=totals["total_cents"],
currency=CURRENCY,
fingerprint=fingerprint,
idempotency_key=f"lowes.flow:{fingerprint[:40]}",
connection=connection,
)
attempt = backend.payments.attempt(
flow_id=flow["flow_id"],
owner=owner,
amount_minor=totals["total_cents"],
currency=CURRENCY,
fingerprint=fingerprint,
scenario_id=scenario_id,
idempotency_key=f"lowes.attempt:{fingerprint[:32]}:{scenario_id}",
connection=connection,
)
if attempt["status"] != "APPROVED":
connection.execute("COMMIT")
return {
"placed": False,
"already": False,
"payment": _payment_public(flow, attempt),
"totals": totals,
}
consumed = backend.payments.consume_approval(
connection,
flow_id=flow["flow_id"],
owner=owner,
amount_minor=totals["total_cents"],
currency=CURRENCY,
fingerprint=fingerprint,
)
cursor = connection.execute(
"INSERT INTO lowes_orders"
" (order_number, owner_digest, account_id, email, customer_name,"
" fulfillment, store_id, address_json, subtotal_cents,"
" savings_cents, delivery_cents, tax_cents, total_cents, currency,"
" fingerprint, payment_flow_id, payment_attempt_id, scenario_id,"
" status, created_at)"
" VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,"
" 'placed', ?)",
(
owner_digest,
account_id,
checkout["email"],
checkout["customer_name"],
fulfillment,
checkout.get("store_id"),
json.dumps(checkout.get("address"), sort_keys=True)
if checkout.get("address")
else None,
totals["subtotal_cents"],
totals["savings_cents"],
totals["delivery_cents"],
totals["tax_cents"],
totals["total_cents"],
CURRENCY,
fingerprint,
flow["flow_id"],
consumed["attempt_id"],
scenario_id,
FROZEN_CLOCK_UTC,
),
)
order_id = int(cursor.lastrowid)
order_number = _order_number(order_id)
connection.execute(
"UPDATE lowes_orders SET order_number = ? WHERE id = ?",
(order_number, order_id),
)
for item in cart["items"]:
connection.execute(
"INSERT INTO lowes_order_items"
" (order_id, product_id, title, brand, slug, quantity,"
" unit_price_cents, line_total_cents, fulfillment)"
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
order_id,
item["product_id"],
item["title"],
item["brand"],
item["slug"],
item["quantity"],
item["unit_price_cents"],
item["line_total_cents"],
item["fulfillment"],
),
)
connection.execute(
"DELETE FROM lowes_cart_items WHERE owner_digest = ?", (owner_digest,)
)
mail = backend.mail.enqueue(
"order-confirmation",
checkout["email"],
{
"order_number": order_number,
"customer_name": checkout["customer_name"],
"total_display": money(totals["total_cents"]),
"currency": CURRENCY,
"fulfillment_summary": _fulfillment_summary(checkout),
"hold_days": str(PICKUP_HOLD_DAYS),
},
idempotency_key=f"lowes.mail:{order_number}",
simulation=True,
connection=connection,
)
connection.execute(
"UPDATE lowes_orders SET mail_id = ? WHERE id = ?",
(mail["mail_id"], order_id),
)
connection.execute("COMMIT")
except Exception:
if connection.in_transaction:
connection.execute("ROLLBACK")
raise
return {"placed": True, "already": False, "order": get_order(order_number)}
def _fulfillment_summary(checkout: Mapping[str, Any]) -> str:
if checkout["fulfillment"] == "pickup":
store = get_store(checkout.get("store_id"))
return f"store pickup at {store['name']}" if store else "store pickup"
address = checkout.get("address") or {}
return f"delivery to {address.get('city', '')} {address.get('state', '')}".strip()
def _payment_public(flow: Mapping[str, Any], attempt: Mapping[str, Any]) -> dict[str, Any]:
return {
"flow_id": flow["flow_id"],
"attempt_id": attempt["attempt_id"],
"status": attempt["status"],
"scenario_id": attempt["scenario_id"],
"amount_minor": int(attempt["amount_minor"]),
"currency": attempt["currency"],
"is_simulation": True,
}
def get_order(order_number: str) -> dict[str, Any] | None:
with closing(connect()) as connection:
row = connection.execute(
"SELECT * FROM lowes_orders WHERE order_number = ?", (order_number,)
).fetchone()
if row is None:
return None
items = connection.execute(
"SELECT * FROM lowes_order_items WHERE order_id = ? ORDER BY id",
(int(row["id"]),),
).fetchall()
mail = None
if row["mail_id"]:
mail_row = connection.execute(
"SELECT mail_id, purpose, status, is_simulation"
" FROM websitebench_mail_jobs WHERE mail_id = ?",
(row["mail_id"],),
).fetchone()
mail = dict(mail_row) if mail_row is not None else None
flow = connection.execute(
"SELECT status FROM websitebench_payment_flows WHERE flow_id = ?",
(row["payment_flow_id"],),
).fetchone()
order = dict(row)
order["address"] = json.loads(order["address_json"]) if order["address_json"] else None
order["items"] = [dict(item) for item in items]
order["mail"] = mail
order["payment_status"] = str(flow["status"]) if flow is not None else None
order["store"] = get_store(order["store_id"])
return order
def orders_for_owner(owner_digest: str, account_id: str | None = None) -> list[dict[str, Any]]:
with closing(connect()) as connection:
if account_id:
rows = connection.execute(
"SELECT order_number FROM lowes_orders"
" WHERE owner_digest = ? OR account_id = ? ORDER BY id DESC",
(owner_digest, account_id),
).fetchall()
else:
rows = connection.execute(
"SELECT order_number FROM lowes_orders"
" WHERE owner_digest = ? ORDER BY id DESC",
(owner_digest,),
).fetchall()
return [order for order in (get_order(str(row[0])) for row in rows) if order]
def payment_scenarios() -> list[dict[str, str]]:
backend, _auth = services()
return [dict(item) for item in backend.config.payments["local_sandbox"]["scenarios"]]
# ---------------------------------------------------------------------------
# formatting helpers shared with the view layer
# ---------------------------------------------------------------------------
def money(cents: int) -> str:
return f"{cents // 100:,}.{cents % 100:02d}"
def money_parts(cents: int) -> tuple[str, str]:
return f"{cents // 100:,}", f"{cents % 100:02d}"