"""Catalog fixture access and cart/favorite persistence for the Article clone. The catalog is a read-only fixture derived from source-observed evidence. Mutable state (cart, favorites, orders) lives in this site's bound SQLite database, opened only through the generated backend integration seam. """ from __future__ import annotations import json import pathlib import time from typing import Any from backend.site_backend_integration import open_site_services DATA = pathlib.Path(__file__).resolve().parent / "data" _catalog: dict[str, Any] | None = None _services: tuple[Any, Any] | None = None def catalog() -> dict[str, Any]: global _catalog if _catalog is None: _catalog = json.loads((DATA / "catalog.json").read_text(encoding="utf-8")) _catalog["by_id"] = {p["product_id"]: p for p in _catalog["products"]} _catalog["by_slug"] = {p["slug"]: p for p in _catalog["products"]} return _catalog def services() -> tuple[Any, Any]: """Open the bound backend once and make the synthetic demo account usable. Seeding is idempotent, so a reset database always comes back with the same deterministic reviewer credentials. """ global _services if _services is None: _services = open_site_services() from site_schema import SYNTHETIC_ACCOUNTS for account in SYNTHETIC_ACCOUNTS: try: _services[1].seed_account(**account) except Exception: # a pre-seeded database is not an error pass return _services def backend(): return services()[0] def auth(): return services()[1] def connect(): return auth().connect() def product(product_id: str) -> dict[str, Any] | None: return catalog()["by_id"].get(product_id) def collection(collection_id: str) -> list[dict[str, Any]]: ids = catalog()["collections"].get(collection_id, []) return [catalog()["by_id"][i] for i in ids if i in catalog()["by_id"]] _subcategories: dict[str, Any] | None = None def subcategories(browse_id: str) -> list[dict[str, Any]]: """Source-observed subcategory tiles, narrowed to products this clone holds.""" global _subcategories if _subcategories is None: path = DATA / "subcategories.json" _subcategories = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} entries = [] for entry in _subcategories.get(browse_id, []): local = [pid for pid in entry["member_product_ids"] if pid in catalog()["by_id"]] if not local: continue # never render a tile that would open an empty result entries.append({**entry, "local_product_ids": local}) return entries _content: dict[str, Any] | None = None def _content_pages() -> dict[str, Any]: global _content if _content is None: path = DATA / "content.json" _content = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} return _content def content_routes() -> list[str]: return sorted(_content_pages()) def content_page(route: str) -> dict[str, Any] | None: return _content_pages().get(route) def cart_recommendations(limit: int = 6) -> list[dict[str, Any]]: """The order the source's empty cart renders under Browse popular products.""" path = DATA / "cart-recommendations.json" ids = json.loads(path.read_text(encoding="utf-8"))["product_ids"] if path.exists() else [] picked = [product(i) for i in ids] picked = [p for p in picked if p] if len(picked) < limit: for extra in collection("living-furniture"): if extra not in picked: picked.append(extra) if len(picked) >= limit: break return picked[:limit] _menu_routes: dict[str, Any] | None = None def menu_routes() -> dict[str, Any]: global _menu_routes if _menu_routes is None: path = DATA / "menu-routes.json" _menu_routes = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} return _menu_routes def menu_route(path: str) -> dict[str, Any] | None: """A mega-menu destination with its source-observed membership narrowed to the products this clone holds.""" entry = menu_routes().get(path) if entry is None: return None products = [catalog()["by_id"][i] for i in entry["product_ids"] if i in catalog()["by_id"]] return {**entry, "products": products} _megamenu: dict[str, Any] | None = None def mega_menu(label: str) -> dict[str, Any] | None: """The captured dropdown for one nav item, narrowed to destinations this clone serves so a menu control never opens a dead route.""" global _megamenu if _megamenu is None: path = DATA / "megamenu.json" _megamenu = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} return _megamenu.get(label) _facets: dict[str, Any] | None = None def facet_groups(browse_id: str) -> list[dict[str, Any]]: """Source-observed filter groups for a collection, with each option's count recomputed against the products this clone actually holds.""" global _facets if _facets is None: path = DATA / "facets.json" _facets = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} entry = _facets.get(browse_id) return entry["groups"] if entry else [] def facet_local_count(products: list[dict[str, Any]], label: str) -> int: """How many of these products the option's label matches by name.""" needle = label.lower() return sum(1 for p in products if needle in p["name"].lower()) _room_tiles: list[dict[str, Any]] | None = None # Display titles as the source renders them beneath each All Rooms tile; the CMS # alt text ("Shop By Bedroom") differs from the visible label. ROOM_TITLES = { "/browse/224/living-furniture": "Living Room", "/browse/222/dining-furniture": "Dining Room & Kitchen", "/browse/225/bedroom-furniture": "Bedroom", "/browse/223/home-office-furniture": "Home Office", "/browse/58/outdoor": "Outdoor", "/browse/345/entryway-furniture": "Entryway", } def room_tiles() -> list[dict[str, Any]]: """Only tiles whose destination this clone actually serves are rendered.""" global _room_tiles if _room_tiles is None: path = DATA / "room-tiles.json" raw = json.loads(path.read_text(encoding="utf-8")) if path.exists() else [] _room_tiles = [ {**t, "title": ROOM_TITLES[t["href"]]} for t in raw if t.get("href") in ROOM_TITLES and t.get("image") ] return _room_tiles def subcategory_by_tc(browse_id: str, tc: str) -> dict[str, Any] | None: for entry in subcategories(browse_id): if entry["tc"] == tc: return entry return None def variants_for(prod: dict[str, Any]) -> list[dict[str, Any]]: """Colour siblings this clone actually serves; a dropped product must never remain linked from a swatch.""" return [v for v in (prod.get("variants") or []) if v["product_id"] in catalog()["by_id"]] def all_products() -> list[dict[str, Any]]: return catalog()["products"] COLLECTION_ROUTES = { "living-furniture": ("/browse/224/living-furniture", "Living Room"), "dining-furniture": ("/browse/222/dining-furniture", "Dining & Kitchen"), "bedroom-furniture": ("/browse/225/bedroom-furniture", "All Bedroom"), "outdoor": ("/browse/58/outdoor", "Outdoor"), "decor": ("/browse/48/decor", "Accessories & Decor"), "home-office": ("/browse/223/home-office-furniture", "Home Office"), "entryway": ("/browse/345/entryway-furniture", "Entryway"), "new-arrivals": ("/browse/100/new", "New Arrivals"), "all-rooms": ("/c/all-rooms", "All Rooms"), } def primary_collection(product_id: str) -> tuple[str, str]: """The collection whose breadcrumb the source shows for this product.""" for name in COLLECTION_ROUTES: if product_id in catalog()["collections"].get(name, []): return name, COLLECTION_ROUTES[name][1] return "all-rooms", COLLECTION_ROUTES["all-rooms"][1] def collection_href(name: str) -> str: return COLLECTION_ROUTES.get(name, COLLECTION_ROUTES["all-rooms"])[0] def search(query: str) -> list[dict[str, Any]]: q = query.strip().lower() if not q: return [] return [p for p in all_products() if q in p["name"].lower()] # --- mutable state ------------------------------------------------------- def owner_key(session_token: str, session: dict[str, Any]) -> str: """Scope cart state to the account when signed in, else to the session.""" account = session.get("account") if session else None if account: return f"account:{account['account_id']}" return f"session:{auth().session_owner_digest(session_token)}" def cart_items(owner: str) -> list[dict[str, Any]]: with connect() as connection: rows = connection.execute( "SELECT product_id, quantity FROM article_cart_items" " WHERE owner_key=? ORDER BY cart_item_id", (owner,), ).fetchall() items = [] for row in rows: prod = product(str(row["product_id"])) if prod is None: continue items.append({ "product": prod, "quantity": int(row["quantity"]), "line_cents": prod["price_cents"] * int(row["quantity"]), }) return items def cart_count(owner: str) -> int: with connect() as connection: row = connection.execute( "SELECT COALESCE(SUM(quantity), 0) AS n FROM article_cart_items WHERE owner_key=?", (owner,), ).fetchone() return int(row["n"]) if row else 0 def cart_subtotal(owner: str) -> int: return sum(i["line_cents"] for i in cart_items(owner)) # Deterministic local checkout arithmetic. The source's USD shipping and tax # figures were not captured (the checkout capture ran on a CAD-region egress), # so these are this clone's own fixed sandbox rules, not source-observed values. SHIPPING_FLAT_CENTS = 4900 FREE_SHIPPING_THRESHOLD_CENTS = 99900 TAX_RATE_BASIS_POINTS = 875 # 8.75% def shipping_cents(subtotal: int) -> int: if subtotal == 0 or subtotal >= FREE_SHIPPING_THRESHOLD_CENTS: return 0 return SHIPPING_FLAT_CENTS def tax_cents(subtotal: int) -> int: return (subtotal * TAX_RATE_BASIS_POINTS + 5000) // 10000 def add_to_cart(owner: str, product_id: str, quantity: int = 1) -> None: if product(product_id) is None: raise KeyError(product_id) now = int(time.time()) with connect() as connection: connection.execute( "INSERT INTO article_cart_items(owner_key, product_id, quantity, created_at)" " VALUES (?,?,?,?)" " ON CONFLICT(owner_key, product_id)" " DO UPDATE SET quantity = quantity + excluded.quantity", (owner, product_id, quantity, now), ) connection.commit() def set_quantity(owner: str, product_id: str, quantity: int) -> None: with connect() as connection: if quantity <= 0: connection.execute( "DELETE FROM article_cart_items WHERE owner_key=? AND product_id=?", (owner, product_id), ) else: connection.execute( "UPDATE article_cart_items SET quantity=? WHERE owner_key=? AND product_id=?", (quantity, owner, product_id), ) connection.commit() def remove_from_cart(owner: str, product_id: str) -> None: set_quantity(owner, product_id, 0) def favorites(owner: str) -> list[dict[str, Any]]: with connect() as connection: rows = connection.execute( "SELECT product_id FROM article_favorites WHERE owner_key=? ORDER BY favorite_id", (owner,), ).fetchall() return [p for p in (product(str(r["product_id"])) for r in rows) if p] def toggle_favorite(owner: str, product_id: str) -> bool: """Return True when the product ends up favorited.""" now = int(time.time()) with connect() as connection: existing = connection.execute( "SELECT 1 FROM article_favorites WHERE owner_key=? AND product_id=?", (owner, product_id), ).fetchone() if existing: connection.execute( "DELETE FROM article_favorites WHERE owner_key=? AND product_id=?", (owner, product_id), ) connection.commit() return False connection.execute( "INSERT INTO article_favorites(owner_key, product_id, created_at) VALUES (?,?,?)", (owner, product_id, now), ) connection.commit() return True def migrate_owner(old_owner: str, new_owner: str) -> None: """Carry an anonymous cart across a sign-in session rotation.""" if old_owner == new_owner: return with connect() as connection: connection.execute( "UPDATE OR IGNORE article_cart_items SET owner_key=? WHERE owner_key=?", (new_owner, old_owner), ) connection.execute("DELETE FROM article_cart_items WHERE owner_key=?", (old_owner,)) connection.commit()