Download tasks/llbean/environment/reference/clone/backend/repo.py from TIGER-Lab/WebsiteBench: direct link, hf CLI and curl.
- Browser
- Download file 37.9 kB
-
https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/llbean/environment/reference/clone/backend/repo.py
- Command line
-
hf download hf://datasets/TIGER-Lab/WebsiteBench/tasks/llbean/environment/reference/clone/backend/repo.py
-
curl -L -o repo.py https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/llbean/environment/reference/clone/backend/repo.py
37.9 kB
| """Query and mutation layer for the llbean clone. | |
| Every collection, facet count and total is computed from SQLite. Nothing here | |
| returns a fixed response standing in for a query. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import secrets | |
| import sqlite3 | |
| import uuid | |
| from datetime import datetime, timezone | |
| from typing import Any, Iterable, Sequence | |
| from .catalog import PERCENT_OFF_BANDS, PRICE_BANDS, SORT_FIELDS, VIEW_COUNT | |
| _CATEGORY_TREE: list[dict[str, Any]] | None = None | |
| FREE_SHIPPING_THRESHOLD = 50.0 | |
| TAX_RATE = 0.055 | |
| def _row(cursor_row: sqlite3.Row | None) -> dict[str, Any] | None: | |
| return dict(cursor_row) if cursor_row is not None else None | |
| def _rows(rows: Iterable[sqlite3.Row]) -> list[dict[str, Any]]: | |
| return [dict(r) for r in rows] | |
| def now() -> str: | |
| return datetime.now(timezone.utc).isoformat(timespec="seconds") | |
| # -------------------------------------------------------------------------- | |
| # taxonomy | |
| # -------------------------------------------------------------------------- | |
| def top_categories(db: sqlite3.Connection) -> list[dict[str, Any]]: | |
| return _rows( | |
| db.execute( | |
| "SELECT * FROM categories WHERE depth = 0 ORDER BY nav_order, cat_id" | |
| ) | |
| ) | |
| def category(db: sqlite3.Connection, cat_id: int) -> dict[str, Any] | None: | |
| return _row( | |
| db.execute("SELECT * FROM categories WHERE cat_id = ?", (cat_id,)).fetchone() | |
| ) | |
| def children(db: sqlite3.Connection, cat_id: int) -> list[dict[str, Any]]: | |
| """Child categories, each with its real product count and a tile image.""" | |
| rows = _rows( | |
| db.execute( | |
| "SELECT c.*," | |
| " (SELECT COUNT(*) FROM product_categories pc WHERE pc.cat_id = c.cat_id)" | |
| " AS product_count," | |
| " c.tile_image AS tile_image" | |
| " FROM categories c WHERE c.parent_id = ? ORDER BY c.nav_order, c.cat_id", | |
| (cat_id,), | |
| ) | |
| ) | |
| return rows | |
| def category_tree(db: sqlite3.Connection) -> list[dict[str, Any]]: | |
| """Top-level categories each carrying their observed child list. | |
| The taxonomy is seed data that never changes at runtime, and the header | |
| renders it on every route, so it is built once per process in two queries. | |
| """ | |
| global _CATEGORY_TREE | |
| if _CATEGORY_TREE is None: | |
| by_parent: dict[int, list[dict[str, Any]]] = {} | |
| for child in _rows( | |
| db.execute( | |
| "SELECT * FROM categories WHERE depth > 0 ORDER BY nav_order, cat_id" | |
| ) | |
| ): | |
| by_parent.setdefault(child["parent_id"], []).append(child) | |
| _CATEGORY_TREE = [ | |
| {**top, "children": by_parent.get(top["cat_id"], [])} | |
| for top in top_categories(db) | |
| ] | |
| return _CATEGORY_TREE | |
| _NAV_MENU: list[dict[str, Any]] | None = None | |
| def nav_menu(db: sqlite3.Connection) -> list[dict[str, Any]]: | |
| """The header mega-menu exactly as the source composes it. | |
| Two shapes exist on the source: a flat single list (Outdoor Equipment, Home | |
| Goods, Sale ...) and a grouped flyout where Women's / Men's / Kids' are | |
| column headers each carrying their own subcategories (Clothing, Outerwear, | |
| Footwear). | |
| """ | |
| global _NAV_MENU | |
| if _NAV_MENU is None: | |
| # The header shows the source's ten top-level entries in its own order. | |
| # `nav_menu` only supplies each entry's flyout, and one entry (Explore | |
| # L.L.Bean) has no flyout at all, so the menu table cannot drive the bar. | |
| # A promo collection must never become an eleventh root: that is kept | |
| # true by giving such categories a non-zero depth in the seed. | |
| tops = top_categories(db) | |
| by_label = {t["name"]: t for t in tops} | |
| rows = _rows(db.execute("SELECT * FROM nav_menu ORDER BY top_label, position")) | |
| grouped: dict[str, list[dict[str, Any]]] = {} | |
| for row in rows: | |
| grouped.setdefault(row["top_label"], []).append(row) | |
| menu = [] | |
| for top in tops: | |
| entries = grouped.get(top["name"], []) | |
| kind = entries[0]["kind"] if entries else "flat" | |
| if kind == "grouped": | |
| columns: list[dict[str, Any]] = [] | |
| for row in entries: | |
| if row["is_group"]: | |
| columns.append({"header": row, "links": []}) | |
| elif columns: | |
| columns[-1]["links"].append(row) | |
| menu.append({**top, "kind": "grouped", "columns": columns, "links": []}) | |
| else: | |
| menu.append({**top, "kind": "flat", "columns": [], "links": entries}) | |
| del by_label | |
| _NAV_MENU = menu | |
| return _NAV_MENU | |
| def home_sections(db: sqlite3.Connection) -> list[dict[str, Any]]: | |
| """The home page composition, in the order the source lays it out.""" | |
| sections = _rows(db.execute("SELECT * FROM home_sections ORDER BY position")) | |
| for section in sections: | |
| section["tiles"] = _rows( | |
| db.execute( | |
| "SELECT * FROM home_items WHERE section_id = ? ORDER BY position", | |
| (section["section_id"],), | |
| ) | |
| ) | |
| return sections | |
| def record_view(db: sqlite3.Connection, owner: str, product_id: str) -> None: | |
| """Remember that this actor opened a product, for 'Pick Up Where You Left Off'.""" | |
| db.execute( | |
| "INSERT INTO recently_viewed (owner, product_id, viewed_at) VALUES (?,?,?)" | |
| " ON CONFLICT(owner, product_id) DO UPDATE SET viewed_at = excluded.viewed_at", | |
| (owner, str(product_id), now()), | |
| ) | |
| def recently_viewed( | |
| db: sqlite3.Connection, owner: str, *, limit: int = 6 | |
| ) -> list[dict[str, Any]]: | |
| return _rows( | |
| db.execute( | |
| "SELECT p.* FROM recently_viewed rv JOIN products p" | |
| " ON p.product_id = rv.product_id WHERE rv.owner = ?" | |
| " ORDER BY rv.viewed_at DESC LIMIT ?", | |
| (owner, limit), | |
| ) | |
| ) | |
| def lander(db: sqlite3.Connection, cat_id: int) -> dict[str, Any] | None: | |
| """An editorial lander page (Outdoor Experiences, Explore L.L.Bean).""" | |
| sections = _rows( | |
| db.execute( | |
| "SELECT * FROM lander_sections WHERE cat_id = ? ORDER BY position", | |
| (int(cat_id),), | |
| ) | |
| ) | |
| if not sections: | |
| return None | |
| for section in sections: | |
| section["tiles"] = _rows( | |
| db.execute( | |
| "SELECT * FROM lander_items WHERE section_id = ? ORDER BY position", | |
| (section["section_id"],), | |
| ) | |
| ) | |
| return {"cat_id": int(cat_id), "sections": sections} | |
| def ancestors(db: sqlite3.Connection, cat_id: int) -> list[dict[str, Any]]: | |
| chain: list[dict[str, Any]] = [] | |
| current = category(db, cat_id) | |
| guard = 0 | |
| while current and guard < 10: | |
| chain.append(current) | |
| if not current.get("parent_id"): | |
| break | |
| current = category(db, current["parent_id"]) | |
| guard += 1 | |
| return list(reversed(chain)) | |
| def descendants(db: sqlite3.Connection, cat_id: int) -> list[int]: | |
| """The category itself plus every category beneath it.""" | |
| family = [int(cat_id)] | |
| frontier = [int(cat_id)] | |
| guard = 0 | |
| while frontier and guard < 8: | |
| placeholders = ",".join("?" * len(frontier)) | |
| kids = [ | |
| row[0] | |
| for row in db.execute( | |
| f"SELECT cat_id FROM categories WHERE parent_id IN ({placeholders})", | |
| frontier, | |
| ) | |
| ] | |
| kids = [k for k in kids if k not in family] | |
| family.extend(kids) | |
| frontier = kids | |
| guard += 1 | |
| return family | |
| # -------------------------------------------------------------------------- | |
| # collections: filtering, sorting, batching | |
| # -------------------------------------------------------------------------- | |
| _SORT_SQL = { | |
| "relevance": "p.position ASC", | |
| "price_low_high": "p.price_low ASC, p.name ASC", | |
| "price_high_low": "p.price_high DESC, p.name ASC", | |
| "bestselling": "p.review_count DESC, p.name ASC", | |
| "newest": "p.is_new DESC, p.position ASC", | |
| "rating": "COALESCE(p.rating, 0) DESC, p.review_count DESC", | |
| } | |
| def _filter_sql( | |
| *, | |
| cat_id: int | None, | |
| cat_ids: Sequence[int] | None = None, | |
| query: str | None, | |
| colors: Sequence[str], | |
| brands: Sequence[str], | |
| price_bands: Sequence[str], | |
| on_sale: bool, | |
| is_new: bool, | |
| genders: Sequence[str] = (), | |
| sizes: Sequence[str] = (), | |
| materials: Sequence[str] = (), | |
| percent_off: Sequence[str] = (), | |
| ) -> tuple[str, list[Any]]: | |
| joins = "" | |
| where = ["1=1"] | |
| params: list[Any] = [] | |
| if cat_id is not None: | |
| # A category page lists its own products plus everything beneath it, the | |
| # way the source counts a parent collection. | |
| joins += " JOIN product_categories pc ON pc.product_id = p.product_id" | |
| family = cat_ids or [cat_id] | |
| placeholders = ",".join("?" * len(family)) | |
| where.append(f"pc.cat_id IN ({placeholders})") | |
| params.extend(family) | |
| if query: | |
| where.append("(LOWER(p.name) LIKE ? OR LOWER(COALESCE(p.description,'')) LIKE ?)") | |
| needle = f"%{query.lower()}%" | |
| params.extend([needle, needle]) | |
| if colors: | |
| placeholders = ",".join("?" * len(colors)) | |
| where.append( | |
| "EXISTS (SELECT 1 FROM product_colors c WHERE c.product_id = p.product_id" | |
| f" AND c.bucket IN ({placeholders}))" | |
| ) | |
| params.extend(colors) | |
| if brands: | |
| placeholders = ",".join("?" * len(brands)) | |
| where.append(f"p.brand IN ({placeholders})") | |
| params.extend(brands) | |
| if price_bands: | |
| clauses = [] | |
| for band in price_bands: | |
| for label, low, high in PRICE_BANDS: | |
| if label == band: | |
| clauses.append("(p.price_low >= ? AND p.price_low < ?)") | |
| params.extend([low, high]) | |
| if clauses: | |
| where.append("(" + " OR ".join(clauses) + ")") | |
| if genders: | |
| placeholders = ",".join("?" * len(genders)) | |
| where.append(f"p.gender IN ({placeholders})") | |
| params.extend(genders) | |
| if sizes: | |
| placeholders = ",".join("?" * len(sizes)) | |
| where.append( | |
| "EXISTS (SELECT 1 FROM product_sizes z WHERE z.product_id = p.product_id" | |
| f" AND z.name IN ({placeholders}))" | |
| ) | |
| params.extend(sizes) | |
| if materials: | |
| placeholders = ",".join("?" * len(materials)) | |
| where.append(f"p.material IN ({placeholders})") | |
| params.extend(materials) | |
| if percent_off: | |
| clauses = [] | |
| for band in percent_off: | |
| for label, low, high in PERCENT_OFF_BANDS: | |
| if label == band: | |
| clauses.append("(p.percent_off >= ? AND p.percent_off < ?)") | |
| params.extend([low, high]) | |
| if clauses: | |
| where.append("(" + " OR ".join(clauses) + ")") | |
| if on_sale: | |
| where.append("p.on_sale = 1") | |
| if is_new: | |
| where.append("p.is_new = 1") | |
| return joins + " WHERE " + " AND ".join(where), params | |
| def collection( | |
| db: sqlite3.Connection, | |
| *, | |
| cat_id: int | None = None, | |
| query: str | None = None, | |
| colors: Sequence[str] = (), | |
| brands: Sequence[str] = (), | |
| price_bands: Sequence[str] = (), | |
| on_sale: bool = False, | |
| is_new: bool = False, | |
| genders: Sequence[str] = (), | |
| sizes: Sequence[str] = (), | |
| materials: Sequence[str] = (), | |
| percent_off: Sequence[str] = (), | |
| sort_field: str = "relevance", | |
| start: int = 0, | |
| view_count: int = VIEW_COUNT, | |
| ) -> dict[str, Any]: | |
| """Return one batch of a filtered collection plus its true total.""" | |
| if sort_field not in SORT_FIELDS: | |
| sort_field = "relevance" | |
| family = descendants(db, cat_id) if cat_id is not None else None | |
| tail, params = _filter_sql( | |
| cat_id=cat_id, | |
| cat_ids=family, | |
| query=query, | |
| colors=colors, | |
| brands=brands, | |
| price_bands=price_bands, | |
| on_sale=on_sale, | |
| is_new=is_new, | |
| genders=genders, | |
| sizes=sizes, | |
| materials=materials, | |
| percent_off=percent_off, | |
| ) | |
| total = db.execute( | |
| f"SELECT COUNT(DISTINCT p.product_id) FROM products p{tail}", params | |
| ).fetchone()[0] | |
| limit = max(1, min(int(view_count or VIEW_COUNT), 96)) | |
| offset = max(0, int(start or 0)) | |
| rows = _rows( | |
| db.execute( | |
| f"SELECT DISTINCT p.* FROM products p{tail}" | |
| f" ORDER BY {_SORT_SQL[sort_field]} LIMIT ? OFFSET ?", | |
| [*params, limit, offset], | |
| ) | |
| ) | |
| # One query for every card's swatches instead of one per card: a 48-item | |
| # grid otherwise costs 48 extra round trips per page render. | |
| if rows: | |
| ids = [r["product_id"] for r in rows] | |
| placeholders = ",".join("?" * len(ids)) | |
| grouped: dict[str, list[dict[str, Any]]] = {pid: [] for pid in ids} | |
| for color in _rows( | |
| db.execute( | |
| "SELECT * FROM product_colors" | |
| f" WHERE product_id IN ({placeholders}) ORDER BY product_id, idx", | |
| ids, | |
| ) | |
| ): | |
| grouped[color["product_id"]].append(color) | |
| for product in rows: | |
| product["colors"] = grouped.get(product["product_id"], []) | |
| return { | |
| "products": rows, | |
| "total": total, | |
| "start": offset, | |
| "view_count": limit, | |
| "sort_field": sort_field, | |
| "has_more": offset + len(rows) < total, | |
| "next_start": offset + limit, | |
| "remaining": max(0, total - (offset + len(rows))), | |
| } | |
| def category_facet_keys(db: sqlite3.Connection, cat_id: int | None) -> list[str]: | |
| """The facet set the source shows for this collection. | |
| Each collection has its own panel on the source: Clothing offers Gender, | |
| Footwear adds Shoe Size and Brand, Sale leads with % Off. Only the facets | |
| this clone can compute from captured data are listed, so no control is inert. | |
| """ | |
| default = ["sale", "new", "color", "price", "brand"] | |
| if cat_id is None: | |
| return ["color", "price", "sale", "brand"] | |
| rows = [ | |
| row[0] | |
| for row in db.execute( | |
| "SELECT facet FROM category_facets WHERE cat_id = ? ORDER BY position", | |
| (int(cat_id),), | |
| ) | |
| ] | |
| if rows: | |
| return rows | |
| # fall back to the nearest ancestor that declares a panel | |
| for ancestor in reversed(ancestors(db, int(cat_id))[:-1]): | |
| rows = [ | |
| row[0] | |
| for row in db.execute( | |
| "SELECT facet FROM category_facets WHERE cat_id = ? ORDER BY position", | |
| (ancestor["cat_id"],), | |
| ) | |
| ] | |
| if rows: | |
| return rows | |
| return default | |
| def facets( | |
| db: sqlite3.Connection, | |
| *, | |
| cat_id: int | None = None, | |
| query: str | None = None, | |
| keys: Sequence[str] | None = None, | |
| ) -> dict[str, Any]: | |
| """Facet values with counts computed against the current scope. | |
| Only the requested facets are built, so a collection renders the panel the | |
| source shows for it rather than one shared panel for every page. | |
| """ | |
| wanted = list(keys) if keys is not None else category_facet_keys(db, cat_id) | |
| family = descendants(db, cat_id) if cat_id is not None else None | |
| tail, params = _filter_sql( | |
| cat_id=cat_id, | |
| cat_ids=family, | |
| query=query, | |
| colors=(), | |
| brands=(), | |
| price_bands=(), | |
| on_sale=False, | |
| is_new=False, | |
| ) | |
| scope = f"(SELECT DISTINCT p.product_id FROM products p{tail})" | |
| built: dict[str, Any] = {"order": wanted, "sort_options": SORT_FIELDS} | |
| if "sale" in wanted: | |
| built["sale"] = { | |
| "name": "Sale", | |
| "count": db.execute( | |
| f"SELECT COUNT(DISTINCT p.product_id) FROM products p{tail} AND p.on_sale = 1", | |
| params, | |
| ).fetchone()[0], | |
| } | |
| if "new" in wanted: | |
| built["new"] = { | |
| "name": "New Arrivals", | |
| "count": db.execute( | |
| f"SELECT COUNT(DISTINCT p.product_id) FROM products p{tail} AND p.is_new = 1", | |
| params, | |
| ).fetchone()[0], | |
| } | |
| if "color" in wanted: | |
| built["color"] = _rows( | |
| db.execute( | |
| "SELECT bucket AS name, COUNT(DISTINCT product_id) AS count FROM product_colors" | |
| f" WHERE bucket IS NOT NULL AND product_id IN {scope}" | |
| " GROUP BY bucket ORDER BY bucket", | |
| params, | |
| ) | |
| ) | |
| if "brand" in wanted: | |
| built["brand"] = _rows( | |
| db.execute( | |
| f"SELECT p.brand AS name, COUNT(DISTINCT p.product_id) AS count FROM products p{tail}" | |
| " GROUP BY p.brand ORDER BY count DESC, p.brand ASC", | |
| params, | |
| ) | |
| ) | |
| if "gender" in wanted: | |
| built["gender"] = _rows( | |
| db.execute( | |
| f"SELECT p.gender AS name, COUNT(DISTINCT p.product_id) AS count FROM products p{tail}" | |
| " AND p.gender IS NOT NULL GROUP BY p.gender ORDER BY count DESC", | |
| params, | |
| ) | |
| ) | |
| if "size" in wanted: | |
| built["size"] = _rows( | |
| db.execute( | |
| "SELECT name, COUNT(DISTINCT product_id) AS count FROM product_sizes" | |
| f" WHERE product_id IN {scope} GROUP BY name" | |
| " ORDER BY count DESC, name LIMIT 24", | |
| params, | |
| ) | |
| ) | |
| if "material" in wanted: | |
| built["material"] = _rows( | |
| db.execute( | |
| f"SELECT p.material AS name, COUNT(*) AS count FROM products p{tail}" | |
| " AND p.material IS NOT NULL GROUP BY p.material ORDER BY count DESC LIMIT 12", | |
| params, | |
| ) | |
| ) | |
| if "price" in wanted: | |
| price = [] | |
| for label, low, high in PRICE_BANDS: | |
| count = db.execute( | |
| f"SELECT COUNT(DISTINCT p.product_id) FROM products p{tail}" | |
| " AND p.price_low >= ? AND p.price_low < ?", | |
| [*params, low, high], | |
| ).fetchone()[0] | |
| if count: | |
| price.append({"name": label, "count": count}) | |
| built["price"] = price | |
| if "percent_off" in wanted: | |
| bands = [] | |
| for label, low, high in PERCENT_OFF_BANDS: | |
| count = db.execute( | |
| f"SELECT COUNT(DISTINCT p.product_id) FROM products p{tail}" | |
| " AND p.percent_off >= ? AND p.percent_off < ?", | |
| [*params, low, high], | |
| ).fetchone()[0] | |
| if count: | |
| bands.append({"name": label, "count": count}) | |
| built["percent_off"] = bands | |
| return built | |
| # -------------------------------------------------------------------------- | |
| # products | |
| # -------------------------------------------------------------------------- | |
| def product(db: sqlite3.Connection, product_id: str) -> dict[str, Any] | None: | |
| found = _row( | |
| db.execute("SELECT * FROM products WHERE product_id = ?", (str(product_id),)).fetchone() | |
| ) | |
| if not found: | |
| return None | |
| pid = found["product_id"] | |
| found["images"] = _rows( | |
| db.execute( | |
| "SELECT * FROM product_images WHERE product_id = ? ORDER BY idx", (pid,) | |
| ) | |
| ) | |
| found["colors"] = product_colors(db, pid) | |
| found["sizes"] = _rows( | |
| db.execute( | |
| "SELECT * FROM product_sizes WHERE product_id = ? ORDER BY idx", (pid,) | |
| ) | |
| ) | |
| import json as _json | |
| found["breadcrumb_list"] = _json.loads(found.get("breadcrumb") or "[]") | |
| return found | |
| def product_colors(db: sqlite3.Connection, product_id: str) -> list[dict[str, Any]]: | |
| return _rows( | |
| db.execute( | |
| "SELECT * FROM product_colors WHERE product_id = ? ORDER BY idx", | |
| (str(product_id),), | |
| ) | |
| ) | |
| def reviews( | |
| db: sqlite3.Connection, | |
| product_id: str, | |
| *, | |
| limit: int = 10, | |
| offset: int = 0, | |
| star: int | None = None, | |
| sort: str = "recent", | |
| ) -> dict[str, Any]: | |
| where = "WHERE product_id = ?" | |
| params: list[Any] = [str(product_id)] | |
| if star: | |
| where += " AND rating = ?" | |
| params.append(int(star)) | |
| order = { | |
| "recent": "created_at DESC, review_id DESC", | |
| "helpful": "helpful DESC, review_id DESC", | |
| "high": "rating DESC, review_id DESC", | |
| "low": "rating ASC, review_id DESC", | |
| }.get(sort, "created_at DESC, review_id DESC") | |
| total = db.execute(f"SELECT COUNT(*) FROM reviews {where}", params).fetchone()[0] | |
| items = _rows( | |
| db.execute( | |
| f"SELECT * FROM reviews {where} ORDER BY {order} LIMIT ? OFFSET ?", | |
| [*params, limit, offset], | |
| ) | |
| ) | |
| histogram = [] | |
| for value in (5, 4, 3, 2, 1): | |
| count = db.execute( | |
| "SELECT COUNT(*) FROM reviews WHERE product_id = ? AND rating = ?", | |
| (str(product_id), value), | |
| ).fetchone()[0] | |
| overall = db.execute( | |
| "SELECT COUNT(*) FROM reviews WHERE product_id = ?", (str(product_id),) | |
| ).fetchone()[0] or 1 | |
| histogram.append( | |
| {"stars": value, "count": count, "percent": round(count * 100.0 / overall, 2)} | |
| ) | |
| return { | |
| "entries": items, | |
| "total": total, | |
| "histogram": histogram, | |
| "has_more": offset + len(items) < total, | |
| "next_offset": offset + limit, | |
| } | |
| # -------------------------------------------------------------------------- | |
| # cart | |
| # -------------------------------------------------------------------------- | |
| def bag_count(db: sqlite3.Connection, owner_key: str) -> int: | |
| """Units in this actor's bag, without creating one. | |
| Every page renders the header badge; opening a write transaction for a | |
| visitor who has no bag yet serialises the whole site under concurrency. | |
| """ | |
| row = db.execute( | |
| "SELECT COALESCE(SUM(ci.qty), 0) FROM cart_items ci" | |
| " JOIN carts c ON c.cart_id = ci.cart_id" | |
| " WHERE c.owner_key = ? AND ci.saved = 0", | |
| (owner_key,), | |
| ).fetchone() | |
| return int(row[0]) if row else 0 | |
| def _next_cart_id(db: sqlite3.Connection) -> str: | |
| """The identifier the next shopping bag gets. | |
| The bag page prints this value ("Shopping Bag ID: b9ce-8da6"), so a random | |
| UUID made the very same read render differently on every visit. Bags are | |
| numbered in creation order instead and the ordinal is hashed to keep the | |
| identifier's shape; the loop skips an ordinal whose id is already taken so | |
| a merged-away bag can never collide with a live one. | |
| """ | |
| ordinal = int(db.execute("SELECT COUNT(*) FROM carts").fetchone()[0]) | |
| while True: | |
| ordinal += 1 | |
| candidate = hashlib.blake2s( | |
| f"llbean:bag:{ordinal}".encode("utf-8"), digest_size=8 | |
| ).hexdigest() | |
| taken = db.execute( | |
| "SELECT 1 FROM carts WHERE cart_id = ?", (candidate,) | |
| ).fetchone() | |
| if taken is None: | |
| return candidate | |
| def get_or_create_cart(db: sqlite3.Connection, owner_key: str) -> dict[str, Any]: | |
| found = _row( | |
| db.execute("SELECT * FROM carts WHERE owner_key = ?", (owner_key,)).fetchone() | |
| ) | |
| if found: | |
| return found | |
| db.execute( | |
| "INSERT OR IGNORE INTO carts (cart_id, owner_key, created_at) VALUES (?,?,?)", | |
| (_next_cart_id(db), owner_key, now()), | |
| ) | |
| created = _row( | |
| db.execute("SELECT * FROM carts WHERE owner_key = ?", (owner_key,)).fetchone() | |
| ) | |
| if created is None: # pragma: no cover - defensive | |
| raise RuntimeError("could not open a shopping bag for this actor") | |
| return created | |
| def add_to_cart( | |
| db: sqlite3.Connection, | |
| owner_key: str, | |
| *, | |
| product_id: str, | |
| color: str | None, | |
| size: str | None, | |
| qty: int, | |
| ) -> dict[str, Any]: | |
| item = product(db, product_id) | |
| if item is None: | |
| raise LookupError("unknown product") | |
| if item["sizes"] and not size: | |
| raise ValueError("Please select a size.") | |
| if item["colors"] and not color: | |
| raise ValueError("Please select a color.") | |
| qty = max(1, min(int(qty or 1), 15)) | |
| cart = get_or_create_cart(db, owner_key) | |
| unit_price = item["sale_price"] if item["on_sale"] else item["price_high"] | |
| existing = db.execute( | |
| "SELECT item_id, qty FROM cart_items WHERE cart_id = ? AND product_id = ?" | |
| " AND COALESCE(color,'') = COALESCE(?,'') AND COALESCE(size,'') = COALESCE(?,'')" | |
| " AND saved = 0", | |
| (cart["cart_id"], str(product_id), color, size), | |
| ).fetchone() | |
| if existing: | |
| db.execute( | |
| "UPDATE cart_items SET qty = MIN(15, qty + ?) WHERE item_id = ?", | |
| (qty, existing[0]), | |
| ) | |
| else: | |
| db.execute( | |
| "INSERT INTO cart_items (cart_id, product_id, color, size, qty, unit_price," | |
| " saved, added_at) VALUES (?,?,?,?,?,?,0,?)", | |
| (cart["cart_id"], str(product_id), color, size, qty, unit_price, now()), | |
| ) | |
| return cart | |
| def cart_view(db: sqlite3.Connection, owner_key: str) -> dict[str, Any]: | |
| cart = get_or_create_cart(db, owner_key) | |
| rows = _rows( | |
| db.execute( | |
| "SELECT ci.*, p.name, p.item_number, p.slug, p.grid_image, p.grid_image_alt," | |
| " p.low_inventory, p.on_sale, p.price_high" | |
| " FROM cart_items ci JOIN products p ON p.product_id = ci.product_id" | |
| " WHERE ci.cart_id = ? ORDER BY ci.item_id", | |
| (cart["cart_id"],), | |
| ) | |
| ) | |
| active = [r for r in rows if not r["saved"]] | |
| saved = [r for r in rows if r["saved"]] | |
| subtotal = round(sum(r["unit_price"] * r["qty"] for r in active), 2) | |
| units = sum(r["qty"] for r in active) | |
| promos = _rows( | |
| db.execute( | |
| "SELECT pr.* FROM cart_promotions cp JOIN promotions pr ON pr.code = cp.code" | |
| " WHERE cp.cart_id = ?", | |
| (cart["cart_id"],), | |
| ) | |
| ) | |
| discount = 0.0 | |
| for promo in promos: | |
| if promo["kind"] == "percent": | |
| discount += subtotal * promo["amount"] / 100.0 | |
| elif promo["kind"] == "amount": | |
| discount += promo["amount"] | |
| discount = round(min(discount, subtotal), 2) | |
| payable = round(subtotal - discount, 2) | |
| free_shipping = payable >= FREE_SHIPPING_THRESHOLD or any( | |
| p["kind"] == "shipping" for p in promos | |
| ) | |
| shipping = 0.0 if free_shipping else (0.0 if not active else 6.95) | |
| return { | |
| "cart_id": cart["cart_id"], | |
| "lines": active, | |
| "saved": saved, | |
| "units": units, | |
| "subtotal": subtotal, | |
| "discount": discount, | |
| "promotions": promos, | |
| "shipping": shipping, | |
| "free_shipping": free_shipping, | |
| "threshold": FREE_SHIPPING_THRESHOLD, | |
| "progress": min(100.0, (payable / FREE_SHIPPING_THRESHOLD) * 100.0), | |
| "tax": round(payable * TAX_RATE, 2), | |
| "total": round(payable + shipping + payable * TAX_RATE, 2), | |
| "empty": not active, | |
| } | |
| def _own_item(db: sqlite3.Connection, owner_key: str, item_id: int) -> sqlite3.Row | None: | |
| return db.execute( | |
| "SELECT ci.* FROM cart_items ci JOIN carts c ON c.cart_id = ci.cart_id" | |
| " WHERE ci.item_id = ? AND c.owner_key = ?", | |
| (int(item_id), owner_key), | |
| ).fetchone() | |
| def update_qty(db: sqlite3.Connection, owner_key: str, item_id: int, qty: int) -> bool: | |
| if _own_item(db, owner_key, item_id) is None: | |
| return False | |
| qty = max(0, min(int(qty), 15)) | |
| if qty == 0: | |
| db.execute("DELETE FROM cart_items WHERE item_id = ?", (int(item_id),)) | |
| else: | |
| db.execute("UPDATE cart_items SET qty = ? WHERE item_id = ?", (qty, int(item_id))) | |
| return True | |
| def remove_item(db: sqlite3.Connection, owner_key: str, item_id: int) -> bool: | |
| if _own_item(db, owner_key, item_id) is None: | |
| return False | |
| db.execute("DELETE FROM cart_items WHERE item_id = ?", (int(item_id),)) | |
| return True | |
| def set_saved(db: sqlite3.Connection, owner_key: str, item_id: int, saved: bool) -> bool: | |
| if _own_item(db, owner_key, item_id) is None: | |
| return False | |
| db.execute( | |
| "UPDATE cart_items SET saved = ? WHERE item_id = ?", (1 if saved else 0, int(item_id)) | |
| ) | |
| return True | |
| def redeem(db: sqlite3.Connection, owner_key: str, code: str) -> tuple[bool, str]: | |
| cart = get_or_create_cart(db, owner_key) | |
| code = (code or "").strip().upper() | |
| if not code: | |
| return False, "Please enter a promo code or gift card number." | |
| promo = db.execute("SELECT * FROM promotions WHERE code = ?", (code,)).fetchone() | |
| if promo: | |
| db.execute( | |
| "INSERT OR IGNORE INTO cart_promotions (cart_id, code) VALUES (?,?)", | |
| (cart["cart_id"], code), | |
| ) | |
| return True, f"{promo['label']} applied." | |
| card = db.execute("SELECT * FROM gift_cards WHERE code = ?", (code,)).fetchone() | |
| if card: | |
| return True, f"Gift card balance: ${card['balance']:.2f}" | |
| return False, "We do not recognize that promo code or gift card number." | |
| def clear_cart(db: sqlite3.Connection, owner_key: str) -> None: | |
| cart = get_or_create_cart(db, owner_key) | |
| db.execute("DELETE FROM cart_items WHERE cart_id = ? AND saved = 0", (cart["cart_id"],)) | |
| db.execute("DELETE FROM cart_promotions WHERE cart_id = ?", (cart["cart_id"],)) | |
| # -------------------------------------------------------------------------- | |
| # orders, addresses, wishlist, stores, misc | |
| # -------------------------------------------------------------------------- | |
| def place_order( | |
| db: sqlite3.Connection, | |
| owner_key: str, | |
| *, | |
| owner: str, | |
| last_name: str, | |
| postal: str, | |
| payment_ref: str | None, | |
| ) -> dict[str, Any] | None: | |
| view = cart_view(db, owner_key) | |
| if view["empty"]: | |
| return None | |
| order_id = uuid.uuid4().hex[:12] | |
| number = f"L{secrets.randbelow(9_000_000) + 1_000_000}" | |
| db.execute( | |
| "INSERT INTO orders (order_id, owner, order_number, last_name, postal, placed_at," | |
| " status, subtotal, shipping, tax, total, payment_ref) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", | |
| ( | |
| order_id, | |
| owner, | |
| number, | |
| last_name, | |
| postal, | |
| now(), | |
| "In Process", | |
| view["subtotal"], | |
| view["shipping"], | |
| view["tax"], | |
| view["total"], | |
| payment_ref, | |
| ), | |
| ) | |
| for item in view["lines"]: | |
| db.execute( | |
| "INSERT INTO order_items (order_id, product_id, name, color, size, qty, unit_price)" | |
| " VALUES (?,?,?,?,?,?,?)", | |
| ( | |
| order_id, | |
| item["product_id"], | |
| item["name"], | |
| item["color"], | |
| item["size"], | |
| item["qty"], | |
| item["unit_price"], | |
| ), | |
| ) | |
| clear_cart(db, owner_key) | |
| return {"order_id": order_id, "order_number": number} | |
| def orders_for(db: sqlite3.Connection, owner: str) -> list[dict[str, Any]]: | |
| return _rows( | |
| db.execute( | |
| "SELECT * FROM orders WHERE owner = ? ORDER BY placed_at DESC", (owner,) | |
| ) | |
| ) | |
| def order_detail(db: sqlite3.Connection, order_id: str) -> dict[str, Any] | None: | |
| order = _row( | |
| db.execute("SELECT * FROM orders WHERE order_id = ?", (order_id,)).fetchone() | |
| ) | |
| if not order: | |
| return None | |
| order["lines"] = _rows( | |
| db.execute("SELECT * FROM order_items WHERE order_id = ?", (order_id,)) | |
| ) | |
| return order | |
| def lookup_order( | |
| db: sqlite3.Connection, *, order_number: str, last_name: str, postal: str | |
| ) -> dict[str, Any] | None: | |
| row = db.execute( | |
| "SELECT * FROM orders WHERE order_number = ? AND LOWER(last_name) = LOWER(?)" | |
| " AND postal = ?", | |
| ((order_number or "").strip(), (last_name or "").strip(), (postal or "").strip()), | |
| ).fetchone() | |
| return order_detail(db, row["order_id"]) if row else None | |
| def addresses(db: sqlite3.Connection, owner: str) -> list[dict[str, Any]]: | |
| return _rows( | |
| db.execute( | |
| "SELECT * FROM addresses WHERE owner = ? ORDER BY is_default DESC, address_id", | |
| (owner,), | |
| ) | |
| ) | |
| def add_address(db: sqlite3.Connection, owner: str, data: dict[str, str]) -> list[str]: | |
| required = ("first_name", "last_name", "street1", "city", "state", "postal") | |
| missing = [f for f in required if not (data.get(f) or "").strip()] | |
| if missing: | |
| return missing | |
| postal = (data.get("postal") or "").strip() | |
| if not postal.replace("-", "").isdigit() or len(postal.replace("-", "")) not in (5, 9): | |
| return ["postal"] | |
| db.execute( | |
| "INSERT INTO addresses (owner, label, first_name, last_name, street1, street2, city," | |
| " state, postal, country, phone, is_default) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", | |
| ( | |
| owner, | |
| data.get("label") or "Address", | |
| data["first_name"].strip(), | |
| data["last_name"].strip(), | |
| data["street1"].strip(), | |
| (data.get("street2") or "").strip(), | |
| data["city"].strip(), | |
| data["state"].strip(), | |
| postal, | |
| data.get("country") or "United States", | |
| (data.get("phone") or "").strip(), | |
| 1 if not addresses(db, owner) else 0, | |
| ), | |
| ) | |
| return [] | |
| def delete_address(db: sqlite3.Connection, owner: str, address_id: int) -> bool: | |
| row = db.execute( | |
| "SELECT address_id FROM addresses WHERE address_id = ? AND owner = ?", | |
| (int(address_id), owner), | |
| ).fetchone() | |
| if not row: | |
| return False | |
| db.execute("DELETE FROM addresses WHERE address_id = ?", (int(address_id),)) | |
| return True | |
| def wishlist(db: sqlite3.Connection, owner: str) -> list[dict[str, Any]]: | |
| return _rows( | |
| db.execute( | |
| "SELECT w.*, p.name, p.grid_image, p.grid_image_alt, p.price_low, p.price_high," | |
| " p.on_sale, p.slug FROM wishlist_items w JOIN products p" | |
| " ON p.product_id = w.product_id WHERE w.owner = ? ORDER BY w.wish_id DESC", | |
| (owner,), | |
| ) | |
| ) | |
| def toggle_wishlist(db: sqlite3.Connection, owner: str, product_id: str) -> bool: | |
| existing = db.execute( | |
| "SELECT wish_id FROM wishlist_items WHERE owner = ? AND product_id = ?", | |
| (owner, str(product_id)), | |
| ).fetchone() | |
| if existing: | |
| db.execute("DELETE FROM wishlist_items WHERE wish_id = ?", (existing[0],)) | |
| return False | |
| db.execute( | |
| "INSERT INTO wishlist_items (owner, product_id, added_at) VALUES (?,?,?)", | |
| (owner, str(product_id), now()), | |
| ) | |
| return True | |
| def find_stores(db: sqlite3.Connection, term: str) -> list[dict[str, Any]]: | |
| term = (term or "").strip() | |
| if not term: | |
| return _rows(db.execute("SELECT * FROM stores ORDER BY store_id")) | |
| like = f"%{term.lower()}%" | |
| return _rows( | |
| db.execute( | |
| "SELECT * FROM stores WHERE LOWER(city) LIKE ? OR LOWER(state) LIKE ?" | |
| " OR postal LIKE ? OR LOWER(name) LIKE ? ORDER BY store_id", | |
| (like, like, f"{term}%", like), | |
| ) | |
| ) | |
| def gift_card_balance(db: sqlite3.Connection, code: str, pin: str) -> dict[str, Any] | None: | |
| return _row( | |
| db.execute( | |
| "SELECT * FROM gift_cards WHERE code = ? AND pin = ?", | |
| ((code or "").strip(), (pin or "").strip()), | |
| ).fetchone() | |
| ) | |
| def request_catalog(db: sqlite3.Connection, data: dict[str, str]) -> list[str]: | |
| required = ("first_name", "last_name", "email", "street1", "city", "state", "postal") | |
| missing = [f for f in required if not (data.get(f) or "").strip()] | |
| email = (data.get("email") or "").strip() | |
| if email and ("@" not in email or "." not in email.split("@")[-1]): | |
| missing.append("email") | |
| if missing: | |
| return sorted(set(missing)) | |
| db.execute( | |
| "INSERT INTO catalog_requests (first_name, last_name, email, street1, city, state," | |
| " postal, created_at) VALUES (?,?,?,?,?,?,?,?)", | |
| ( | |
| data["first_name"].strip(), | |
| data["last_name"].strip(), | |
| email, | |
| data["street1"].strip(), | |
| data["city"].strip(), | |
| data["state"].strip(), | |
| data["postal"].strip(), | |
| now(), | |
| ), | |
| ) | |
| return [] | |
| def email_prefs(db: sqlite3.Connection, owner: str) -> dict[str, Any]: | |
| row = _row( | |
| db.execute("SELECT * FROM email_prefs WHERE owner = ?", (owner,)).fetchone() | |
| ) | |
| if row: | |
| return row | |
| db.execute("INSERT INTO email_prefs (owner) VALUES (?)", (owner,)) | |
| return {"owner": owner, "subscribed": 1, "frequency": "weekly", "catalog_opt": 1} | |
| def set_email_prefs( | |
| db: sqlite3.Connection, owner: str, *, subscribed: bool, frequency: str, catalog_opt: bool | |
| ) -> None: | |
| email_prefs(db, owner) | |
| db.execute( | |
| "UPDATE email_prefs SET subscribed = ?, frequency = ?, catalog_opt = ? WHERE owner = ?", | |
| (1 if subscribed else 0, frequency, 1 if catalog_opt else 0, owner), | |
| ) | |
| def content_page(db: sqlite3.Connection, cat_id: int) -> dict[str, Any] | None: | |
| return _row( | |
| db.execute("SELECT * FROM content_pages WHERE cat_id = ?", (int(cat_id),)).fetchone() | |
| ) | |
| def all_content_pages(db: sqlite3.Connection) -> list[dict[str, Any]]: | |
| return _rows(db.execute("SELECT * FROM content_pages ORDER BY name")) | |
| def content_pages(db: sqlite3.Connection, term: str | None = None) -> list[dict[str, Any]]: | |
| """Editorial results for the search page's Info & Stories tab.""" | |
| if not term: | |
| return [] | |
| like = f"%{term.lower()}%" | |
| return _rows( | |
| db.execute( | |
| "SELECT * FROM content_pages WHERE LOWER(name) LIKE ? OR LOWER(blurb) LIKE ?" | |
| " ORDER BY name LIMIT 12", | |
| (like, like), | |
| ) | |
| ) | |