Download tasks/backcountry/environment/reference/clone/store.py from TIGER-Lab/WebsiteBench: direct link, hf CLI and curl.
- Browser
- Download file 16.8 kB
-
https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/backcountry/environment/reference/clone/store.py
- Command line
-
hf download hf://datasets/TIGER-Lab/WebsiteBench/tasks/backcountry/environment/reference/clone/store.py
-
curl -L -o store.py https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/backcountry/environment/reference/clone/store.py
16.8 kB
| """Deterministic local business store for the Backcountry offline clone. | |
| Persistence goes through the generated ``site_backend_integration`` seam so the | |
| site keeps its own bound SQLite database, session cookie and mail outbox. This | |
| module owns only the site's business tables: carts, cart lines, wish lists, | |
| orders and addresses. Authentication, sessions and mail stay with | |
| ``LocalAuthStore``; nothing here reimplements them. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import sqlite3 | |
| import threading | |
| from dataclasses import dataclass | |
| from typing import Any | |
| from backend.site_backend_integration import open_site_services | |
| SCHEMA = """ | |
| CREATE TABLE IF NOT EXISTS clone_cart ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| actor TEXT NOT NULL UNIQUE, | |
| created_at TEXT NOT NULL DEFAULT (datetime('now')) | |
| ); | |
| CREATE TABLE IF NOT EXISTS clone_cart_line ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| cart_id INTEGER NOT NULL REFERENCES clone_cart(id) ON DELETE CASCADE, | |
| sku_id TEXT NOT NULL, | |
| product_slug TEXT NOT NULL, | |
| color TEXT, | |
| size TEXT, | |
| quantity INTEGER NOT NULL CHECK (quantity > 0), | |
| unit_price REAL NOT NULL, | |
| list_price REAL NOT NULL, | |
| added_at TEXT NOT NULL DEFAULT (datetime('now')), | |
| UNIQUE (cart_id, sku_id) | |
| ); | |
| CREATE TABLE IF NOT EXISTS clone_wishlist ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| actor TEXT NOT NULL, | |
| product_slug TEXT NOT NULL, | |
| color TEXT, | |
| added_at TEXT NOT NULL DEFAULT (datetime('now')), | |
| UNIQUE (actor, product_slug, color) | |
| ); | |
| CREATE TABLE IF NOT EXISTS clone_order ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| order_number TEXT NOT NULL UNIQUE, | |
| actor TEXT NOT NULL, | |
| placed_on TEXT NOT NULL, | |
| status TEXT NOT NULL, | |
| ship_to TEXT NOT NULL, | |
| subtotal REAL NOT NULL, | |
| shipping REAL NOT NULL, | |
| tax REAL NOT NULL, | |
| total REAL NOT NULL, | |
| lines TEXT NOT NULL | |
| ); | |
| CREATE TABLE IF NOT EXISTS clone_address ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| actor TEXT NOT NULL, | |
| label TEXT NOT NULL, | |
| recipient TEXT NOT NULL, | |
| line1 TEXT NOT NULL, | |
| line2 TEXT, | |
| city TEXT NOT NULL, | |
| region TEXT NOT NULL, | |
| postal_code TEXT NOT NULL, | |
| country TEXT NOT NULL, | |
| is_default INTEGER NOT NULL DEFAULT 0 | |
| ); | |
| CREATE TABLE IF NOT EXISTS clone_outbox ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| channel TEXT NOT NULL, | |
| recipient TEXT NOT NULL, | |
| purpose TEXT NOT NULL, | |
| created_at TEXT NOT NULL DEFAULT (datetime('now')) | |
| ); | |
| """ | |
| # The one synthetic member the clone ships with. No source credential is used | |
| # or stored; this account exists only inside the local database. | |
| MEMBER = { | |
| "email": "gearhead.demo@backcountry.offline.invalid", | |
| "password": "GearheadDemo!2026", | |
| "first_name": "Alex", | |
| "last_name": "Rivera", | |
| "tier": "Summit Club Member", | |
| } | |
| SEED_ADDRESSES = [ | |
| {"label": "Home", "recipient": "Alex Rivera", "line1": "1284 Wasatch Loop", "line2": "Apt 4", | |
| "city": "Salt Lake City", "region": "UT", "postal_code": "84109", "country": "United States", | |
| "is_default": 1}, | |
| {"label": "Work", "recipient": "Alex Rivera", "line1": "2607 South 3200 West", "line2": None, | |
| "city": "West Valley City", "region": "UT", "postal_code": "84119", "country": "United States", | |
| "is_default": 0}, | |
| ] | |
| SEED_ORDERS = [ | |
| {"order_number": "BC-4820117", "placed_on": "2026-07-18", "status": "Delivered", | |
| "ship_to": "Home", "shipping": 0.0, | |
| "lines": [{"product_slug": "/patagonia-black-hole-40l-duffel-bag", "sku_id": "PATZAKX-BERFIG-ONESIZ", | |
| "color": "Berry Fig", "size": "One Size", "quantity": 1, "unit_price": 165.0}]}, | |
| {"order_number": "BC-4791560", "placed_on": "2026-06-02", "status": "Delivered", | |
| "ship_to": "Home", "shipping": 0.0, | |
| "lines": [{"product_slug": "/osprey-packs-daylite-13l-backpack", "sku_id": "OSPZ19S-BLA-ONESIZ", | |
| "color": "Black", "size": "One Size", "quantity": 2, "unit_price": 52.50}, | |
| {"product_slug": "/patagonia-black-hole-3l-cube", "sku_id": "PATZAKW-BLABLA-ONESIZ", | |
| "color": "Black/Black", "size": "One Size", "quantity": 1, "unit_price": 45.0}]}, | |
| {"order_number": "BC-4756903", "placed_on": "2026-04-11", "status": "Cancelled", | |
| "ship_to": "Work", "shipping": 6.95, | |
| "lines": [{"product_slug": "/cotopaxi-allpa-del-dia-35l-travel-pack", "sku_id": "CTXB0IE-DELDIA-ONESIZ", | |
| "color": "Del Dia", "size": "One Size", "quantity": 1, "unit_price": 230.0}]}, | |
| ] | |
| TAX_RATE = 0.0725 | |
| FREE_SHIPPING_THRESHOLD = 69.0 | |
| STANDARD_SHIPPING = 6.95 | |
| _lock = threading.Lock() | |
| class Services: | |
| backend: Any | |
| auth: Any | |
| _services: Services | None = None | |
| def services() -> Services: | |
| global _services | |
| if _services is None: | |
| backend, auth = open_site_services() | |
| _services = Services(backend=backend, auth=auth) | |
| _bootstrap(_services) | |
| return _services | |
| def _connect() -> sqlite3.Connection: | |
| conn = services().auth.connect() | |
| conn.row_factory = sqlite3.Row | |
| return conn | |
| def _bootstrap(svc: Services) -> None: | |
| svc.auth.ensure_schema() | |
| conn = svc.auth.connect() | |
| try: | |
| conn.executescript(SCHEMA) | |
| conn.commit() | |
| finally: | |
| conn.close() | |
| if not svc.auth.account_exists(MEMBER["email"]): | |
| svc.auth.seed_account( | |
| subject_id="backcountry-member-demo", | |
| email=MEMBER["email"], | |
| display_name=f'{MEMBER["first_name"]} {MEMBER["last_name"]}', | |
| password=MEMBER["password"], | |
| ) | |
| seed_member_data() | |
| def seed_member_data() -> None: | |
| """Seed the member's deterministic fixture rows. | |
| Idempotent by row identity, not by actor: `clone_order.order_number` is | |
| globally unique, so guarding on "this actor has no orders yet" would crash | |
| against a row left by an earlier fixture identity. | |
| Every statement is a true no-op once the fixture rows are already correct. | |
| An `INSERT ... ON CONFLICT DO UPDATE` would not be: SQLite allocates the | |
| AUTOINCREMENT rowid before it detects the conflict, so `sqlite_sequence` | |
| advanced on every boot and consecutive restarts left different durable | |
| state. Repair first, then insert only what is genuinely absent. | |
| """ | |
| actor = MEMBER["email"] | |
| conn = _connect() | |
| try: | |
| for a in SEED_ADDRESSES: | |
| conn.execute( | |
| "INSERT INTO clone_address (actor,label,recipient,line1,line2,city,region," | |
| "postal_code,country,is_default) SELECT ?,?,?,?,?,?,?,?,?,? WHERE NOT EXISTS " | |
| "(SELECT 1 FROM clone_address WHERE actor = ? AND label = ?)", | |
| (actor, a["label"], a["recipient"], a["line1"], a["line2"], a["city"], | |
| a["region"], a["postal_code"], a["country"], a["is_default"], | |
| actor, a["label"])) | |
| for o in SEED_ORDERS: | |
| subtotal = round(sum(x["unit_price"] * x["quantity"] for x in o["lines"]), 2) | |
| tax = round(subtotal * TAX_RATE, 2) | |
| total = round(subtotal + o["shipping"] + tax, 2) | |
| conn.execute( | |
| "UPDATE clone_order SET actor = ?, placed_on = ?, status = ?, " | |
| "ship_to = ?, subtotal = ?, shipping = ?, tax = ?, total = ?, lines = ? " | |
| "WHERE order_number = ?", | |
| (actor, o["placed_on"], o["status"], o["ship_to"], subtotal, | |
| o["shipping"], tax, total, json.dumps(o["lines"]), o["order_number"])) | |
| conn.execute( | |
| "INSERT INTO clone_order (order_number,actor,placed_on,status,ship_to," | |
| "subtotal,shipping,tax,total,lines) SELECT ?,?,?,?,?,?,?,?,?,? " | |
| "WHERE NOT EXISTS (SELECT 1 FROM clone_order WHERE order_number = ?)", | |
| (o["order_number"], actor, o["placed_on"], o["status"], o["ship_to"], | |
| subtotal, o["shipping"], tax, total, json.dumps(o["lines"]), | |
| o["order_number"])) | |
| conn.commit() | |
| finally: | |
| conn.close() | |
| # -------------------------------------------------------------------------- | |
| # cart | |
| # -------------------------------------------------------------------------- | |
| def _cart_id(conn: sqlite3.Connection, actor: str) -> int: | |
| row = conn.execute("SELECT id FROM clone_cart WHERE actor = ?", (actor,)).fetchone() | |
| if row: | |
| return int(row["id"]) | |
| cur = conn.execute("INSERT INTO clone_cart (actor) VALUES (?)", (actor,)) | |
| return int(cur.lastrowid) | |
| def cart_lines(actor: str) -> list[dict[str, Any]]: | |
| conn = _connect() | |
| try: | |
| rows = conn.execute( | |
| "SELECT l.* FROM clone_cart_line l JOIN clone_cart c ON c.id = l.cart_id" | |
| " WHERE c.actor = ? ORDER BY l.added_at, l.id", (actor,)).fetchall() | |
| return [dict(r) for r in rows] | |
| finally: | |
| conn.close() | |
| def cart_count(actor: str) -> int: | |
| conn = _connect() | |
| try: | |
| row = conn.execute( | |
| "SELECT COALESCE(SUM(l.quantity), 0) AS n FROM clone_cart_line l" | |
| " JOIN clone_cart c ON c.id = l.cart_id WHERE c.actor = ?", (actor,)).fetchone() | |
| return int(row["n"]) | |
| finally: | |
| conn.close() | |
| def add_to_cart(actor: str, *, sku_id: str, product_slug: str, color: str | None, | |
| size: str | None, unit_price: float, list_price: float, quantity: int = 1) -> None: | |
| if quantity < 1: | |
| raise ValueError("quantity must be positive") | |
| with _lock: | |
| conn = _connect() | |
| try: | |
| cart_id = _cart_id(conn, actor) | |
| # Idempotent per SKU: re-adding the same variant increments quantity, | |
| # which is how the source cart behaves. | |
| conn.execute( | |
| "INSERT INTO clone_cart_line (cart_id, sku_id, product_slug, color, size, quantity, unit_price, list_price)" | |
| " VALUES (?,?,?,?,?,?,?,?)" | |
| " ON CONFLICT(cart_id, sku_id) DO UPDATE SET quantity = quantity + excluded.quantity", | |
| (cart_id, sku_id, product_slug, color, size, quantity, unit_price, list_price)) | |
| conn.commit() | |
| finally: | |
| conn.close() | |
| def set_line_quantity(actor: str, sku_id: str, quantity: int) -> None: | |
| with _lock: | |
| conn = _connect() | |
| try: | |
| cart_id = _cart_id(conn, actor) | |
| if quantity <= 0: | |
| conn.execute("DELETE FROM clone_cart_line WHERE cart_id = ? AND sku_id = ?", (cart_id, sku_id)) | |
| else: | |
| conn.execute("UPDATE clone_cart_line SET quantity = ? WHERE cart_id = ? AND sku_id = ?", | |
| (quantity, cart_id, sku_id)) | |
| conn.commit() | |
| finally: | |
| conn.close() | |
| def remove_line(actor: str, sku_id: str) -> None: | |
| set_line_quantity(actor, sku_id, 0) | |
| def clear_cart(actor: str) -> None: | |
| with _lock: | |
| conn = _connect() | |
| try: | |
| conn.execute("DELETE FROM clone_cart_line WHERE cart_id IN (SELECT id FROM clone_cart WHERE actor = ?)", | |
| (actor,)) | |
| conn.commit() | |
| finally: | |
| conn.close() | |
| def merge_cart(source_actor: str, target_actor: str) -> None: | |
| """Carry an anonymous cart into the member cart on sign-in.""" | |
| if source_actor == target_actor: | |
| return | |
| with _lock: | |
| conn = _connect() | |
| try: | |
| src = conn.execute("SELECT id FROM clone_cart WHERE actor = ?", (source_actor,)).fetchone() | |
| if not src: | |
| return | |
| target_id = _cart_id(conn, target_actor) | |
| for row in conn.execute("SELECT * FROM clone_cart_line WHERE cart_id = ?", (src["id"],)).fetchall(): | |
| conn.execute( | |
| "INSERT INTO clone_cart_line (cart_id, sku_id, product_slug, color, size, quantity, unit_price, list_price)" | |
| " VALUES (?,?,?,?,?,?,?,?)" | |
| " ON CONFLICT(cart_id, sku_id) DO UPDATE SET quantity = quantity + excluded.quantity", | |
| (target_id, row["sku_id"], row["product_slug"], row["color"], row["size"], | |
| row["quantity"], row["unit_price"], row["list_price"])) | |
| conn.execute("DELETE FROM clone_cart WHERE id = ?", (src["id"],)) | |
| conn.commit() | |
| finally: | |
| conn.close() | |
| def cart_totals(lines: list[dict[str, Any]]) -> dict[str, float]: | |
| subtotal = round(sum(x["unit_price"] * x["quantity"] for x in lines), 2) | |
| savings = round(sum((x["list_price"] - x["unit_price"]) * x["quantity"] for x in lines), 2) | |
| shipping = 0.0 if (subtotal >= FREE_SHIPPING_THRESHOLD or not lines) else STANDARD_SHIPPING | |
| tax = round(subtotal * TAX_RATE, 2) | |
| return {"subtotal": subtotal, "savings": savings, "shipping": shipping, | |
| "tax": tax, "total": round(subtotal + shipping + tax, 2)} | |
| # -------------------------------------------------------------------------- | |
| # wish list | |
| # -------------------------------------------------------------------------- | |
| def wishlist(actor: str) -> list[dict[str, Any]]: | |
| conn = _connect() | |
| try: | |
| rows = conn.execute("SELECT * FROM clone_wishlist WHERE actor = ? ORDER BY added_at DESC, id DESC", | |
| (actor,)).fetchall() | |
| return [dict(r) for r in rows] | |
| finally: | |
| conn.close() | |
| def toggle_wishlist(actor: str, product_slug: str, color: str | None) -> bool: | |
| with _lock: | |
| conn = _connect() | |
| try: | |
| row = conn.execute( | |
| "SELECT id FROM clone_wishlist WHERE actor = ? AND product_slug = ? AND IFNULL(color,'') = IFNULL(?,'')", | |
| (actor, product_slug, color)).fetchone() | |
| if row: | |
| conn.execute("DELETE FROM clone_wishlist WHERE id = ?", (row["id"],)) | |
| conn.commit() | |
| return False | |
| conn.execute("INSERT INTO clone_wishlist (actor, product_slug, color) VALUES (?,?,?)", | |
| (actor, product_slug, color)) | |
| conn.commit() | |
| return True | |
| finally: | |
| conn.close() | |
| # -------------------------------------------------------------------------- | |
| # orders and addresses | |
| # -------------------------------------------------------------------------- | |
| def orders(actor: str) -> list[dict[str, Any]]: | |
| conn = _connect() | |
| try: | |
| rows = conn.execute("SELECT * FROM clone_order WHERE actor = ? ORDER BY placed_on DESC", (actor,)).fetchall() | |
| out = [] | |
| for r in rows: | |
| rec = dict(r) | |
| rec["lines"] = json.loads(rec["lines"]) | |
| out.append(rec) | |
| return out | |
| finally: | |
| conn.close() | |
| def order(actor: str, order_number: str) -> dict[str, Any] | None: | |
| for o in orders(actor): | |
| if o["order_number"] == order_number: | |
| return o | |
| return None | |
| def addresses(actor: str) -> list[dict[str, Any]]: | |
| conn = _connect() | |
| try: | |
| rows = conn.execute("SELECT * FROM clone_address WHERE actor = ? ORDER BY is_default DESC, id", (actor,)).fetchall() | |
| return [dict(r) for r in rows] | |
| finally: | |
| conn.close() | |
| def record_outbox(channel: str, recipient: str, purpose: str) -> None: | |
| """Marketing sign-ups land in a local outbox; nothing leaves the machine.""" | |
| with _lock: | |
| conn = _connect() | |
| try: | |
| conn.execute("INSERT INTO clone_outbox (channel, recipient, purpose) VALUES (?,?,?)", | |
| (channel, recipient, purpose)) | |
| conn.commit() | |
| finally: | |
| conn.close() | |
| def outbox() -> list[dict[str, Any]]: | |
| conn = _connect() | |
| try: | |
| return [dict(r) for r in conn.execute("SELECT * FROM clone_outbox ORDER BY id DESC").fetchall()] | |
| finally: | |
| conn.close() | |
| SEED_ACCOUNTS = [{ | |
| "subject_id": "backcountry-member-demo", | |
| "email": MEMBER["email"], | |
| "display_name": f'{MEMBER["first_name"]} {MEMBER["last_name"]}', | |
| "password": MEMBER["password"], | |
| }] | |
| SITE_TABLES = ("clone_cart_line", "clone_cart", "clone_wishlist", | |
| "clone_order", "clone_address", "clone_outbox") | |
| def _site_reset(connection: sqlite3.Connection) -> None: | |
| for table in SITE_TABLES: | |
| connection.execute(f"DELETE FROM {table}") | |
| # DELETE leaves the AUTOINCREMENT high-water mark behind, so row ids would | |
| # creep on every reset and two resets would not produce identical state. | |
| connection.execute( | |
| "DELETE FROM sqlite_sequence WHERE name IN ({})".format( | |
| ",".join("?" for _ in SITE_TABLES)), | |
| SITE_TABLES) | |
| def reset_state() -> None: | |
| """Deterministic reset: auth rows, mail flows and this site's business | |
| tables are cleared and reseeded in one transaction through the shared | |
| auth store, so a reset also clears mail rate limits and restores the | |
| seeded member's password.""" | |
| with _lock: | |
| services().auth.reset_site_state(site_reset=_site_reset, seed_accounts=SEED_ACCOUNTS) | |
| seed_member_data() | |