"""Source-grounded Lowe's offline clone frontend shell. The visual states and local image assets are derived from the Playwright evidence pack in materials/lowes/source-current and source-assets. """ from __future__ import annotations import json from html import escape from pathlib import Path from typing import Any, Mapping, Sequence from urllib.parse import parse_qs, quote_plus, urlencode from fastapi import FastAPI, Request, Response from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse from fastapi.staticfiles import StaticFiles import commerce import landing from backend import accounts as account_backend from backend import store as site_store from ui.artwork import VIEWS, product_svg SITE_ID = "lowes" DISPLAY_NAME = "Lowe's" ROOT = Path(__file__).resolve().parent MATERIAL_ROOT = ROOT.parent STATIC_ROOT = ROOT / "static" ASSET_ROOT = MATERIAL_ROOT / "source-assets" / "playwright-20260821" MULTIPAGE_ASSET_ROOT = STATIC_ROOT / "assets" / "playwright-multipage-20260821" app = FastAPI(title=DISPLAY_NAME) app.mount("/static", StaticFiles(directory=STATIC_ROOT), name="static") app.mount("/source-assets", StaticFiles(directory=ASSET_ROOT), name="source-assets") app.mount( "/multipage-assets", StaticFiles(directory=MULTIPAGE_ASSET_ROOT), name="multipage-assets", ) PRODUCTS = [ { "backend_id": 1001, "slug": "frigidaire-professional-french-door-refrigerator", "brand": "Frigidaire Professional", "title": "21.4-cu ft Counter-Depth French Door Refrigerator with Dual Ice Maker", "price": 2999.00, "was": 3999.00, "rating": "4.6", "reviews": 812, "image": "005-753ec6507385a84d.avif", "category": "Appliances", }, { "backend_id": 1002, "slug": "frigidaire-professional-convection-range", "brand": "Frigidaire Professional", "title": "30-in 6-Burner Convection Range with Air Fry", "price": 1699.00, "was": 2999.00, "rating": "4.7", "reviews": 441, "image": "005-289c2ff5d6cb25ae.avif", "category": "Appliances", }, { "backend_id": 1005, "slug": "frigidaire-gallery-french-door-refrigerator", "brand": "Frigidaire Gallery", "title": "French Door Refrigerator with Custom-Flex Temp Drawer", "price": 1999.00, "was": 2799.00, "rating": "4.5", "reviews": 668, "image": "005-dfaf191432b00001.avif", "category": "Appliances", }, { "backend_id": 1006, "slug": "frigidaire-energy-star-refrigerator", "brand": "Frigidaire", "title": "ENERGY STAR French Door Refrigerator with Ice Maker", "price": 1599.00, "was": 2399.00, "rating": "4.4", "reviews": 503, "image": "009-82acfde0786311c2.avif", "category": "Appliances", }, { "backend_id": 1003, "slug": "frigidaire-dishwasher", "brand": "Frigidaire", "title": "Top Control 24-in Built-In Dishwasher", "price": 499.00, "was": 649.00, "rating": "4.3", "reviews": 1159, "image": "011-c6564a958b49fc75.avif", "category": "Appliances", }, { "backend_id": 1004, "slug": "electrolux-front-load-laundry-pair", "brand": "Electrolux", "title": "Front-Load Washer and Electric Dryer Laundry Pair", "price": 1599.00, "was": 2199.00, "rating": "4.6", "reviews": 924, "image": "011-baeb3a51751a722c.avif", "category": "Appliances", }, ] BEST_SELLER_DEPARTMENTS = [ ("Accessible Home", "6af8471da47c294fdc6c.webp"), ("Animal & Pet Care", "41a8e365a49148ee412e.webp"), ("Appliances", "ba41fa97d7383500c4b6.webp"), ("Automotive", "6c36e70a664e0848d90d.avif"), ("Bathroom", "dda585b6cae61ddd07ea.webp"), ("Building Supplies", "dd7f3b1d215945e9f098.avif"), ("Cleaning Supplies", "d2732d99a54a164ff9fe.webp"), ("Clothing & Work Apparel", "eed3b304716ed0e28843.webp"), ("Dining & Entertaining", "1c049e30d66740306d57.avif"), ("Drinks & Snacks", "a1a0b97fcf109d04fd4a.webp"), ("Electrical", "1e30e7d63a3040a0bf02.webp"), ("Flooring", "3f72678a92b47aca55df.webp"), ] STATES = { "A": ["Alabama", "Alaska", "Arizona", "Arkansas"], "C": ["California", "Colorado", "Connecticut"], "D": ["Delaware", "District Of Columbia"], "F": ["Florida"], "G": ["Georgia"], "H": ["Hawaii"], "I": ["Idaho", "Illinois", "Indiana", "Iowa"], "K": ["Kansas", "Kentucky"], "L": ["Louisiana"], "M": ["Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana"], "N": ["Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota"], "O": ["Ohio", "Oklahoma", "Oregon"], "P": ["Pennsylvania"], "R": ["Rhode Island"], "S": ["South Carolina", "South Dakota"], "T": ["Tennessee", "Texas"], "U": ["Utah"], "V": ["Vermont", "Virginia"], "W": ["Washington", "West Virginia", "Wisconsin", "Wyoming"], } # Routes that predate the source-path inventory and are still reachable from # bookmarks. Each one now names the source-compatible path it belongs to, so the # clone has a single canonical URL per surface instead of two parallel ones. LEGACY_REDIRECTS = { "credit": "/l/Credit", "pro": "/l/Pro", "ai-assist": "/ai", "installations": "/l/install", "ideas": "/diy-projects-and-ideas", "maintenance": "/l/shop/home-maintenance", "terms": "/l/about/terms-and-conditions-of-use", "privacy": "/l/about/privacy-and-security-statement", "info": "/l/help", } # The Playwright probe recorded Access Denied for most source paths, so pages # reconstructed from a URL alone say so in one consistent sentence rather than # implying a verified reproduction. SOURCE_RESTRICTED_NOTE = landing.SOURCE_RESTRICTED_NOTE SYNTHETIC_COMMERCE_NOTE = ( "Prices, ratings, reviews, specifications and artwork on this page come " "from this clone's frozen synthetic catalog, not from Lowe's. The source " "page answered Access Denied to the recorded Playwright session, so no " "source layout or product data was observed for it." ) EMPTY_CART: dict[str, Any] = { "items": [], "count": 0, "units": 0, "subtotal_cents": 0, "savings_cents": 0, "needs_delivery": False, "all_free_delivery": True, } def money(value: float) -> str: return f"${value:,.2f}" def cents(value: int) -> str: return f"${site_store.money(int(value))}" def product_by_slug(slug: str) -> dict[str, object] | None: return next((product for product in PRODUCTS if product["slug"] == slug), None) CAPTURED_BY_BACKEND_ID = {int(item["backend_id"]): item for item in PRODUCTS} def captured_product(product_id: int) -> dict[str, object] | None: """The captured-asset display record for a backend id, when there is one.""" return CAPTURED_BY_BACKEND_ID.get(int(product_id)) def catalog_art(product_id: int, view: str = "front") -> str: """Locally generated artwork URL for any catalog product.""" return f"/img/p/{int(product_id)}/{view}.svg" # --------------------------------------------------------------------------- # shared page furniture # --------------------------------------------------------------------------- def breadcrumb_bar(trail: Sequence[tuple[str, str | None]]) -> str: parts = [] for label, href in trail: if href: parts.append(f'{escape(label)}') else: parts.append(f"{escape(label)}") return ( '" ) def sandbox_notice(text: str) -> str: return f'

{escape(text)}

' def action_row(actions: Sequence[tuple[str, str]]) -> str: if not actions: return "" links = "".join( f'{escape(label)}' for label, href in actions ) return f'' def highlight_grid(highlights: Sequence[tuple[str, str]]) -> str: if not highlights: return "" cards = "".join( f"

{escape(title)}

{escape(copy)}

" for title, copy in highlights ) return f'
{cards}
' def fact_table(facts: Sequence[tuple[str, str]]) -> str: if not facts: return "" rows = "".join( f'{escape(term)}{escape(value)}' for term, value in facts ) return f'{rows}
' def rating_line(product: Mapping[str, Any]) -> str: filled = int(float(product["rating"]) + 0.5) stars = "★" * filled + "☆" * (5 - filled) return ( f'
{stars} ' f'{float(product["rating"]):.1f} ({int(product["review_count"]):,})
' ) def price_line(product: Mapping[str, Any]) -> str: price = int(product["price_cents"]) was = product.get("was_cents") extra = "" if was: extra = ( f'Was {cents(int(was))}' f'Save {cents(int(was) - price)}' ) return f'
{cents(price)}{extra}
' def catalog_card(product: Mapping[str, Any]) -> str: """A product tile for the synthetic catalog, using locally drawn artwork.""" flag = "" if product.get("badge"): flag = ( '' f'{escape(str(product["badge"]))}' ) url = escape(str(product["url"]), quote=True) return f"""
{flag} {escape(str(product['title']), quote=True)}
{escape(str(product['brand']))} {escape(str(product['title']))} {rating_line(product)}{price_line(product)}
""" def catalog_grid(products: Sequence[Mapping[str, Any]]) -> str: if not products: return ( '

No matching items

' "

Clear a filter or widen the price range to see this clone's " "catalog again.

" ) return '
' + "".join(catalog_card(row) for row in products) + "
" def auth_services(): return site_store.services()[1] def site_backend(): return site_store.services()[0] # The session cookie is not named here: ``backend/runtime.json`` derives it from # the site id and the vendored runtime returns the mandated Host-only options # (``__Host-`` prefix, Secure, HttpOnly, SameSite, Path=/, never a Domain). def session_cookie_spec() -> dict[str, Any]: return dict(site_backend().session_cookie) def session_cookie_name() -> str: return str(session_cookie_spec()["name"]) def read_session_token(request: Request) -> str | None: return request.cookies.get(session_cookie_name()) def set_session_cookie(response: Response, token: str) -> Response: options = session_cookie_spec() name = str(options.pop("name")) response.set_cookie(name, token, **options) return response def clear_session_cookie(response: Response) -> Response: options = session_cookie_spec() name = str(options.pop("name")) response.delete_cookie(name, path=str(options.get("path", "/"))) return response def existing_owner(request: Request) -> str | None: token = read_session_token(request) if not token: return None try: return auth_services().session_owner_digest(token) except Exception: return None def ensured_owner(request: Request) -> tuple[str, str]: token, _session = auth_services().ensure_session(read_session_token(request)) return token, auth_services().session_owner_digest(token) def current_session(request: Request) -> dict[str, Any] | None: try: return auth_services().resolve_session(read_session_token(request)) except Exception: return None def current_account(request: Request) -> dict[str, Any] | None: return account_backend.public_account(current_session(request)) def current_account_id(request: Request) -> str | None: session = current_session(request) if not session or not session.get("authenticated"): return None return str(session["account"]["account_id"]) def cart_units_for_token(token: str) -> int: """Cart size for an explicit token, used after a session rotation. The request cookie still holds the revoked token on the response that performs the rotation, so the shell has to be counted from the new one. """ try: owner = auth_services().session_owner_digest(token) except Exception: return 0 return int(site_store.cart_units(owner)) def cart_for(request: Request) -> tuple[str | None, dict[str, Any]]: """The session's cart exactly as the backend holds it. The shell reads this on every render, so it has to cover the whole catalog rather than only the six captured-asset products: a line added from a ``/pd/`` page must count in the masthead and appear on ``/cart``. """ owner = existing_owner(request) if owner is None: return None, dict(EMPTY_CART) return owner, site_store.get_cart(owner) def icon(name: str) -> str: icons = { "search": "⌕", "store": "▣", "account": "◉", "cart": "🛒", "ai": "✦", "close": "×", "menu": "☰", } return f'' def account_utility(account: dict[str, Any] | None) -> str: """The masthead account control, truthful about the current session.""" if not account: label = "Sign In" else: first = str(account.get("display_name", "")).split(" ")[0] or "Account" label = f"Hi, {first[:14]}" return ( f'" ) CATNAV_ITEMS = ( ("▦ Shop All", "/c/Departments", (("Appliances", "/c/Appliances"), ("Bathroom", "/c/Bathroom"), ("Building Supplies", "/c/Building-supplies"), ("Doors & Windows", "/c/Windows-doors"))), ("♙ Installations", "/l/install", (("Installation Services", "/l/install"), ("Store Services", "/l/about/store-services"), ("Bathroom Installation", "/c/Bathroom"), ("Appliance Installation", "/c/Appliances"))), ("◇ Deals", "/l/savings", (("Daily Deals", "/l/savings/daily-deals"), ("Coupons", "/l/savings/coupons"), ("All Deals", "/pl/Deals/1611079983848"), ("Rebate Center", "/l/help/rebate-center"))), ("♧ Design & Ideas", "/diy-projects-and-ideas", (("DIY Projects & Ideas", "/diy-projects-and-ideas"), ("Workshops", "/diy-projects-and-ideas/workshops"), ("Fresh Inspiration", "/l/fresh-projects-and-inspiration"), ("Paint Ideas", "/c/Paint"))), ("$99 Maintenance", "/l/shop/home-maintenance", (("Home Maintenance", "/l/shop/home-maintenance"), ("Seasonal Projects", "/diy-projects-and-ideas"), ("Services", "/l/about/store-services"))), ("Appliances", "/c/Appliances", (("Refrigerators", "/c/Refrigerators"), ("Ranges", "/c/Ranges"), ("Dishwashers", "/c/Dishwashers"), ("Washers & Dryers", "/c/Washers-dryers"))), ("Bathroom", "/c/Bathroom", (("Bathroom Vanities", "/c/Bathroom-vanities"), ("Toilets", "/c/Toilets"), ("Showers", "/c/Showers"), ("Bathroom Faucets", "/c/Bathroom-faucets"))), ("Building Supplies", "/c/Building-supplies", (("Lumber", "/c/Lumber"), ("Decking", "/c/Decking"), ("Concrete & Masonry", "/c/Concrete-masonry"), ("Roofing", "/c/Roofing"), ("Insulation", "/c/Insulation"), ("Drywall", "/c/Drywall"))), ("Doors & Windows", "/c/Windows-doors", (("Exterior Doors", "/c/Exterior-doors"), ("Interior Doors", "/c/Interior-doors"), ("Windows", "/c/Windows"), ("Garage Doors", "/c/Garage-doors"))), ) def catnav() -> str: items = [] for index, (label, href, children) in enumerate(CATNAV_ITEMS): strong = " catnav__link--strong" if index < 4 else "" badge = ' New' if label == "$99 Maintenance" else "" child_links = "".join( f'{escape(child_label)}' for child_label, child_href in children ) items.append( '
  • ' f'{escape(label)}{badge}' f'
    {escape(label.lstrip("▦♙◇♧ "))}' f'{child_links}View all →
    ' "
  • " ) return '" def header( cart_count: int = 0, query: str = "", account: dict[str, Any] | None = None ) -> str: q = escape(query, quote=True) return f"""
    Shop this week’s top deals now. >
    {catnav()}
    """ DRAWER_BENEFITS = ( '' ) def drawer(opened: bool = False, account: dict[str, Any] | None = None) -> str: hidden = "hidden" if not opened else "" state = "open" if opened else "closed" if account: title = "Your Account" contents = f"""

    Signed in as {escape(str(account.get('contact_display', '')))} in this offline clone. Nothing here exists at Lowe's.

    {DRAWER_BENEFITS}""" else: title = "Sign In or Create Account" contents = f"""

    Enter your email or phone number to get started. We'll check if you have an account.

    {DRAWER_BENEFITS}""" return f"""
    """ # Every footer destination is a source-compatible path this clone serves, so no # footer control leaves the origin or lands on a shared filler page. FOOTER_GROUPS: dict[str, tuple[tuple[str, str], ...]] = { "Customer Service": ( ("Customer Service", "/l/help"), ("Order Status", "/mylowes/orders/checkorderstatus"), ("Returns Policy", "/l/help/returns-policy"), ("Shipping & Delivery", "/l/help/shipping-delivery"), ("Special Orders", "/l/help/special-orders"), ), "Resources": ( ("Weekly Ad", "/weekly-ad"), ("Store Directory", "/Lowes-Stores"), ("DIY Projects & Ideas", "/diy-projects-and-ideas"), ("Lowe's Gift Cards", "/l/shop/gift-cards"), ("Subscriptions", "/subscriptions"), ), "About Lowe's": ( ("How We Help", "/l/about/how-we-help"), ("MyLowe's Rewards", "/l/about/mylowes-rewards"), ("Lowe's Marketplace", "/l/about/lowes-marketplace"), ("Suppliers", "/l/about/suppliers"), ("Privacy & Security", "/l/about/privacy-and-security-statement"), ("Terms & Conditions of Use", "/l/about/terms-and-conditions-of-use"), ), "For Pros": ( ("Lowe's for Pros", "/l/Pro"), ("Pro Benefits", "/l/Pro/pro-benefits"), ("Resources for Pros", "/l/Pro/resources-for-pros"), ("Pro Credit", "/l/Credit"), ("Tool Rental", "/l/shop/rental"), ), } def footer() -> str: columns = "".join( f"

    {escape(title)}

    " for title, items in FOOTER_GROUPS.items() ) return f'' def product_card(product: dict[str, object]) -> str: price = float(product["price"]) was = float(product["was"]) return f"""
    SALE {escape(str(product['title']), quote=True)}
    {escape(str(product['brand']))} {escape(str(product['title']))}
    ★★★★★ {product['rating']} ({product['reviews']})
    {money(price)}Was {money(was)}Save {money(was-price)}
    """ def document(title: str, body: str, cart_count: int = 0, query: str = "", account_open: bool = False, account: dict[str, Any] | None = None) -> str: return f"""{escape(title)}{header(cart_count, query, account)}{body}{footer()}{drawer(account_open, account)}""" def render( request: Request, title: str, body: str, *, query: str = "", account_open: bool = False, status_code: int = 200, ) -> HTMLResponse: """Render one page with the session-derived cart count and account state.""" _owner, cart = cart_for(request) return HTMLResponse( document( title, body, int(cart["units"]), query, account_open, current_account(request), ), status_code=status_code, ) @app.get("/healthz") def healthz() -> dict[str, object]: return {"ok": True, "site_id": SITE_ID} @app.get("/", response_class=HTMLResponse) def home(request: Request, account: str = "") -> HTMLResponse: cards = "".join(product_card(product) for product in PRODUCTS[:4]) body = f"""

    Recommended searches

    Electrolux End-of-Summer Sale

    ELECTROLUX · FRIGIDAIRE · FRIGIDAIRE GALLERY · FRIGIDAIRE PROFESSIONAL
    Save up to $300 when you bundle select Frigidaire major appliances
    myLowe's Rewards — Members Get MoreFREE Delivery and Haul AwayFREE Basic Installation and Installation Parts2-Year Lowe's Protection Plan

    Featured appliance deals

    Shop all deals
    {cards}

    Services for every project

    Find a Store

    Select a synthetic store for pickup and local availability.

    Choose a store
    """ return render(request, "Lowe’s Home Improvement", body, account_open=account == "open") @app.get("/best-sellers", response_class=HTMLResponse) def best_sellers(request: Request) -> HTMLResponse: sidebar = "".join(f'
  • {escape(label)}
  • ' for label, _image in BEST_SELLER_DEPARTMENTS) cards = "".join( f'{escape(label)}' for label, image in BEST_SELLER_DEPARTMENTS ) body = f"""

    Lowe’s Best Sellers

    {cards}See All Departments
    """ return render(request, "Lowe's Best Sellers - The Most Popular Items on Lowes.com", body) @app.get("/diy-projects-and-ideas/workshops", response_class=HTMLResponse) def workshops(request: Request) -> HTMLResponse: body = """

    Welcome to MyLowe’s Rewards™ Kids Club!

    Kids Club — your next family adventure starts here Create your Kids Profile and sign up for workshops Build, laugh and learn at a free workshop

    Free workshops and family fun

    MyLowe’s Rewards members can create a kids profile, collect digital badges and register for hands-on family workshops in this local demo.

    Get Started
    """ return render(request, "Lowe’s Kids Club: Free Workshops & Family Fun", body) @app.get("/Lowes-Stores", response_class=HTMLResponse) @app.get("/stores", response_class=HTMLResponse) def stores_directory(request: Request) -> HTMLResponse: groups = "".join( f'

    {letter}

    {"".join(f"{escape(state)}" for state in states)}
    ' for letter, states in STATES.items() ) body = f"""

    State Directory

    Lowe's Stores in the U.S.

    {groups}
    """ return render(request, "Lowe's Store Directory - Find Locations by State and City", body) @app.get("/stores/{state}", response_class=HTMLResponse) def stores_in_state(request: Request, state: str) -> HTMLResponse: label = state.replace("-", " ").title() body = f'

    Lowe\'s Stores in {escape(label)}

    {escape(label)} Lowe\'s

    Select a location in the header to see local pickup availability.

    ' return render(request, f"Lowe's Stores in {label}", body) @app.get("/mylowes/orders", response_class=HTMLResponse) def order_search(request: Request, result: str = "") -> HTMLResponse: result_box = '
    No matching local order was found. This form never contacts Lowe\'s.
    ' if result else "" body = f"""

    Check Order Status

    {result_box}

    Already have a MyLowe's account? Sign In

    """ return render(request, "Check Order Status", body) @app.get("/subscriptions", response_class=HTMLResponse) def subscriptions(request: Request) -> HTMLResponse: categories = [ ("Air Filters", "b1b525b77407e16c4857.avif"), ("Cleaning Supplies", "f3a5af534697d6b76954.webp"), ("Hardware", "7679add5dce57126b778.webp"), ("Lawn Care", "dec89f8f5b922b47de43.webp"), ] tiles = "".join(f'{escape(label)}' for label, image in categories) body = f"""
    Woman changing an air filter

    SUBSCRIPTIONS
    MADE SIMPLE

    • Free Standard Shipping
    • 5% Off Select Items
    • Automatic Repeat Deliveries
    • Cancel Anytime
    Learn MoreTerms & Conditions

    How does it work?

    1

    Find eligible products

    Shop items available for repeat delivery.

    2

    Choose your schedule

    Select a delivery frequency that works for you.

    3

    Save automatically

    Manage or cancel your local demo subscription anytime.

    Popular subscription categories

    {tiles}
    """ return render(request, "Subscriptions | Lowe's", body) @app.get("/c/{category_slug}", response_class=HTMLResponse) def category_page(request: Request, category_slug: str) -> HTMLResponse: label = category_slug.replace("-", " ").title() cards = "".join(product_card(product) for product in PRODUCTS) child_map = { "appliances": ("Refrigerators", "Ranges", "Dishwashers", "Washers-dryers"), "bathroom": ("Bathroom-vanities", "Toilets", "Showers", "Bathroom-faucets"), "building-supplies": ("Lumber", "Decking", "Concrete-masonry", "Roofing", "Insulation", "Drywall"), "windows-doors": ("Exterior-doors", "Interior-doors", "Windows", "Garage-doors"), } children = child_map.get(category_slug.lower(), ()) category_links = "".join( f'{escape(child.replace("-", " ").title())}' for child in children ) if not category_links: category_links = f'Best SellersShop All {escape(label)}Subscriptions' body = f'

    {escape(label)}

    Featured {escape(label)}

    {cards}
    ' return render(request, f"Shop {label} at Lowes.com", body) @app.get("/api/suggest") def suggest(q: str = "") -> JSONResponse: needle = q.strip().lower() labels = ["cordless drill", "refrigerator", "refrigerator water filter", "Frigidaire appliances", "dishwasher", "range", "washer and dryer"] matched = [label for label in labels if needle in label.lower()][:6] products = [{"label": p["title"], "href": f"/product/{p['slug']}"} for p in PRODUCTS if needle in str(p["title"]).lower()][:3] return JSONResponse({"groups": [{"label": "Search suggestions", "items": [{"label": label, "href": f"/search?q={quote_plus(label)}"} for label in matched]}, {"label": "Products", "items": products}]}) @app.get("/search", response_class=HTMLResponse) def search(request: Request, q: str = "") -> HTMLResponse: needle = q.strip().lower() matches = PRODUCTS if not needle or needle in {"deals", "appliances"} else [p for p in PRODUCTS if needle in json.dumps(p).lower()] cards = "".join(product_card(product) for product in matches) body = f'

    {escape(q) if q else "Shop All"}

    {len(matches)} results
    {f"
    {cards}
    " if cards else "

    No exact results

    Try appliances, refrigerator, dishwasher, or range.

    "}
    ' return render(request, f"{q or 'Shop All'} | Lowe's", body, query=q) @app.get("/product/{slug}", response_class=HTMLResponse) def product(request: Request, slug: str) -> HTMLResponse: product = product_by_slug(slug) if not product: return render(request, "Product not found", '

    Product not found

    Continue shopping
    ', status_code=404) body = f"""
    {escape(str(product['title']), quote=True)}
    {escape(str(product['brand']))}

    {escape(str(product['title']))}

    ★★★★★ {product['rating']} ({product['reviews']})
    {money(float(product['price']))}Was {money(float(product['was']))}

    How do you want to get your item?

    Local demo only. No real inventory, fulfillment, or charge.

    Product details

    Brand{escape(str(product['brand']))}
    Category{escape(str(product['category']))}
    ModelWB-{str(product['slug'])[:12].upper()}
    """ return render(request, f"{product['title']} | Lowe's", body) def resolve_cart_products(values: Mapping[str, list[str]]) -> list[int]: """Backend product ids for an add-to-cart post. ``slug`` is the captured-asset form used by the home, search and ``/product/`` tiles; ``product_id`` is the catalog form used by every ``/pd/``, ``/pl/``, ``/collections/`` and ``/configure/`` control, and a package page posts it once per suite member. """ ids = [ int(raw.strip()) for raw in values.get("product_id", []) if raw.strip().isdigit() ] if ids: return ids captured = product_by_slug(values.get("slug", [""])[0]) return [int(captured["backend_id"])] if captured else [] def resolve_cart_product(values: Mapping[str, list[str]]) -> int | None: ids = resolve_cart_products(values) return ids[0] if ids else None def local_next(values: Mapping[str, list[str]], fallback: str = "/cart") -> str: """A redirect target restricted to this origin's own absolute paths.""" target = values.get("next", [""])[0] if target.startswith("/") and not target.startswith("//"): return target return fallback @app.post("/cart/add") async def add_to_cart(request: Request) -> RedirectResponse: values = parse_qs((await request.body()).decode("utf-8", "replace")) token, owner = ensured_owner(request) raw_quantity = values.get("quantity", ["1"])[0] quantity = int(raw_quantity) if raw_quantity.isdigit() else 1 requested = values.get("fulfillment", ["pickup"])[0] fulfillment = requested if requested in site_store.FULFILLMENTS else "pickup" for product_id in resolve_cart_products(values): try: site_store.add_to_cart( owner, product_id=product_id, quantity=quantity, fulfillment=fulfillment, ) except site_store.CheckoutError: # A pickup-ineligible item is the only expected rejection here; the # delivery line is still a real add rather than a silent no-op. site_store.add_to_cart( owner, product_id=product_id, quantity=quantity, fulfillment="delivery", ) return set_session_cookie( RedirectResponse(local_next(values), status_code=303), token ) @app.post("/cart/update") async def update_cart(request: Request) -> RedirectResponse: values = parse_qs((await request.body()).decode("utf-8", "replace")) action = values.get("action", [""])[0] token, owner = ensured_owner(request) backend_cart = site_store.get_cart(owner) raw_item = values.get("item_id", [""])[0].strip() if raw_item.isdigit(): item = next( (row for row in backend_cart["items"] if int(row["item_id"]) == int(raw_item)), None, ) else: product_id = resolve_cart_product(values) item = next( ( row for row in backend_cart["items"] if product_id is not None and int(row["product_id"]) == product_id ), None, ) if item: quantity = int(item["quantity"]) if action == "remove": site_store.remove_cart_item(owner, item_id=int(item["item_id"])) elif action == "minus": site_store.update_cart_item( owner, item_id=int(item["item_id"]), quantity=quantity - 1 ) elif action == "plus": site_store.update_cart_item( owner, item_id=int(item["item_id"]), quantity=quantity + 1 ) return set_session_cookie(RedirectResponse("/cart", status_code=303), token) def cart_line(item: Mapping[str, Any]) -> str: """One cart row, linking back to whichever page owns the item's display.""" product_id = int(item["product_id"]) captured = captured_product(product_id) if captured: href = f"/product/{captured['slug']}" art = f"/static/assets/playwright-20260821/{captured['image']}" else: href = str(item["url"]) art = catalog_art(product_id) fulfillment = ( "Store pickup" if item["fulfillment"] == "pickup" else "Delivery" ) return ( '
    ' f'' f'
    ' f'{escape(str(item["brand"]))}' f'{escape(str(item["title"]))}' f"

    {fulfillment} in this local demo.

    " '
    ' f'' '' f'{int(item["quantity"])}' '' '' "
    " f'{cents(int(item["line_total_cents"]))}
    ' ) @app.get("/cart", response_class=HTMLResponse) def cart_page(request: Request) -> HTMLResponse: _owner, cart = cart_for(request) if not cart["items"]: body = '

    Your cart is empty

    Find everything you need for your next project.

    Start shopping
    ' return render(request, "Cart | Lowe's", body) lines = "".join(cart_line(item) for item in cart["items"]) savings = int(cart["savings_cents"]) savings_row = ( f'
    Savings-{cents(savings)}
    ' if savings else "" ) body = ( '
    ' f'

    Cart ({int(cart["units"])} items)

    ' f'
    {lines}
    ' '
    " ) return render(request, "Cart | Lowe's", body) @app.get("/checkout", response_class=HTMLResponse) def checkout(request: Request) -> HTMLResponse: owner = existing_owner(request) backend_cart = site_store.get_cart(owner) if owner else {"items": [], "subtotal_cents": 0, "savings_cents": 0, "all_free_delivery": True} totals = site_store.price_cart(backend_cart, fulfillment="pickup", state="NC") scenarios = site_store.payment_scenarios() options = "".join(f'' for item in scenarios) button_disabled = "disabled" if not backend_cart["items"] else "" body = f'

    Checkout

    WebsiteBench local sandbox
    No real Lowe\'s order or payment will be created.

    Contact information

    Fulfillment

    Sandbox payment outcome

    ' return render(request, "Checkout | Lowe's", body) async def form_values(request: Request) -> dict[str, str]: body = (await request.body()).decode("utf-8", "replace") return {key: entries[0] for key, entries in parse_qs(body).items()} @app.post("/account/start") async def account_start(request: Request) -> HTMLResponse: values = parse_qs((await request.body()).decode("utf-8", "replace")) identifier_raw = values.get("identifier", [""])[0] token, _owner = ensured_owner(request) try: identified = account_backend.identify(auth_services(), identifier_raw) except Exception as exc: _field, message = account_backend.friendly_error(exc) return set_session_cookie( render(request, "Account | Lowe's", f'

    Check your entry

    {escape(message)}

    Try again
    ', account_open=True), token, ) identity = identified["identity"] if identified["account_exists"]: body = f'

    Welcome back

    Forgot your password?

    ' else: phone_note = '

    Phone registration uses reserved test numbers only: 555-0100 through 555-0199, such as (213) 555-0142.

    ' if identity["kind"] == "phone" else '' body = f'

    Create your local account

    {phone_note}

    Verification will go only to the local WebsiteBench outbox for {escape(identity["display"])}.

    ' return set_session_cookie(render(request, "Account | Lowe's", body), token) @app.post("/account/create") async def account_create(request: Request) -> HTMLResponse: values = parse_qs((await request.body()).decode("utf-8", "replace")) token, _owner = ensured_owner(request) try: result = account_backend.start_registration(auth_services(), token, identifier=values.get("identifier", [""])[0], first_name=values.get("first_name", [""])[0], last_name=values.get("last_name", [""])[0], password=values.get("password", [""])[0]) code = account_backend.sandbox_code(auth_services(), token) help_box = f'
    Local sandbox code: {escape(code or "unavailable")}
    This value comes from the repository-approved local outbox and was not sent externally.
    ' body = f'

    Verify your contact

    Enter the local code for {escape(result["identity"]["display"])}.

    {help_box}
    ' except Exception as exc: _field, message = account_backend.friendly_error(exc) body = f'

    Could not start registration

    {escape(message)}

    Start again
    ' return set_session_cookie(render(request, "Verify account | Lowe's", body), token) @app.post("/account/verify") async def account_verify(request: Request) -> HTMLResponse: values = parse_qs((await request.body()).decode("utf-8", "replace")) token, _owner = ensured_owner(request) try: completed = account_backend.verify_and_complete(auth_services(), token, values.get("code", [""])[0]) new_token = str(completed["session_token"]) name = escape(str(completed["account"]["display_name"])) body = f'

    Account created

    Welcome, {name}. Your account and contact verification exist only in this offline clone.

    Continue shopping
    ' # The account page must reflect the rotated session, not the anonymous # one the request arrived with, so the shell is rendered from the new # token rather than from ``request.cookies``. account = account_backend.public_account(auth_services().resolve_session(new_token)) page = HTMLResponse( document( "Account created | Lowe's", body, cart_units_for_token(new_token), account=account, ) ) return set_session_cookie(page, new_token) except Exception as exc: _field, message = account_backend.friendly_error(exc) body = f'

    Verification failed

    {escape(message)}

    Start again
    ' return set_session_cookie( render(request, "Verification failed | Lowe's", body), token ) @app.post("/account/signin") async def account_signin(request: Request) -> HTMLResponse: values = parse_qs((await request.body()).decode("utf-8", "replace")) token, _owner = ensured_owner(request) try: signed = account_backend.sign_in(auth_services(), token, identifier=values.get("identifier", [""])[0], password=values.get("password", [""])[0]) return set_session_cookie( RedirectResponse("/", status_code=303), str(signed["session_token"]) ) except Exception as exc: _field, message = account_backend.friendly_error(exc) return set_session_cookie( render(request, "Sign in | Lowe's", f'

    Sign in failed

    {escape(message)}

    Try again
    '), token, ) @app.post("/account/signout") async def account_signout(request: Request) -> RedirectResponse: """Revoke the server-side session first, then drop the cookie. The anonymous cart is deliberately not migrated: the revoked session's owner digest keeps its rows, and the next request starts a fresh anonymous session, which is what a real sign-out looks like from the browser. """ account_backend.sign_out(auth_services(), read_session_token(request)) return clear_session_cookie(RedirectResponse("/", status_code=303)) # --------------------------------------------------------------------------- # password recovery # --------------------------------------------------------------------------- RESET_STEP_INTRO = ( "

    Enter the email or reserved test phone number on your local account. " "This clone answers the same way whether or not an account exists.

    " ) def reset_request_form(identifier: str = "", notice: str = "") -> str: return ( '

    Reset your password

    ' f"{notice}{RESET_STEP_INTRO}" '
    ' '' '' "
    " ) @app.get("/account/reset", response_class=HTMLResponse) def account_reset(request: Request, identifier: str = "") -> HTMLResponse: return render(request, "Reset your password | Lowe's", reset_request_form(identifier)) @app.post("/account/reset/start") async def account_reset_start(request: Request) -> HTMLResponse: values = await form_values(request) identifier_raw = values.get("identifier", "") token, _owner = ensured_owner(request) try: result = account_backend.start_password_reset( auth_services(), token, identifier=identifier_raw ) except Exception as exc: _field, message = account_backend.friendly_error(exc) notice = f'

    {escape(message)}

    ' return set_session_cookie( render( request, "Reset your password | Lowe's", reset_request_form(identifier_raw, notice), status_code=400, ), token, ) # The store's public message is identical for a known and an unknown # identity. The sandbox block below is the one place they differ, and only # while the local development helper is on: with # ``LOWES_LOCAL_SANDBOX_HELP=0`` ``sandbox_code`` returns None for both and # the two responses become byte-identical. code = account_backend.sandbox_code( auth_services(), token, purpose=account_backend.PURPOSE_PASSWORD_RESET ) help_box = ( '
    Local sandbox code: ' f'{escape(code)}
    This value comes from the local outbox ' "and was not sent externally.
    " if code else '
    No local sandbox code is ' "available to display. Nothing was sent to any external service.
    " ) body = ( '

    Check your local outbox

    ' f'

    {escape(str(result["flow"]["message"]))}

    {help_box}' '
    ' '" "
    " ) return set_session_cookie( render(request, "Reset your password | Lowe's", body), token ) @app.post("/account/reset/verify") async def account_reset_verify(request: Request) -> HTMLResponse: values = await form_values(request) token, _owner = ensured_owner(request) try: account_backend.verify_password_reset( auth_services(), token, values.get("code", "") ) except Exception as exc: _field, message = account_backend.friendly_error(exc) body = ( '
    ' f"

    Verification failed

    {escape(message)}

    " 'Start again' "
    " ) return set_session_cookie( render(request, "Reset your password | Lowe's", body, status_code=400), token, ) body = ( '

    Choose a new password

    ' '
    ' '' '' "
    " ) return set_session_cookie( render(request, "Reset your password | Lowe's", body), token ) @app.post("/account/reset/complete") async def account_reset_complete(request: Request) -> HTMLResponse: values = await form_values(request) token, _owner = ensured_owner(request) try: new_token = account_backend.complete_password_reset( auth_services(), token, new_password=values.get("password", "") ) except Exception as exc: _field, message = account_backend.friendly_error(exc) body = ( '
    ' f"

    Password was not changed

    {escape(message)}

    " 'Start again' "
    " ) return set_session_cookie( render(request, "Reset your password | Lowe's", body, status_code=400), token, ) body = ( '

    Password updated

    ' "

    Every earlier local session for this account was revoked and you are " "signed in on this device only.

    " 'Continue shopping
    ' ) account = account_backend.public_account(auth_services().resolve_session(new_token)) page = HTMLResponse( document( "Password updated | Lowe's", body, cart_units_for_token(new_token), account=account, ) ) return set_session_cookie(page, new_token) @app.post("/checkout/place") async def checkout_place(request: Request) -> HTMLResponse: values = await form_values(request) token, owner = ensured_owner(request) cart = site_store.get_cart(owner) try: checkout_data = site_store.validate_checkout(values, cart=cart, scenario_ids=[item["id"] for item in site_store.payment_scenarios()]) # Binding the order to the account as well as to the session digest is # what keeps it visible after a sign-out/sign-in rotates the session. result = site_store.place_order( owner, checkout_data, account_id=current_account_id(request) ) if result["placed"]: order = result["order"] body = f'
    Approved local simulation

    Thanks, your offline order is recorded

    Order {escape(order["order_number"])} totals ${site_store.money(order["total_cents"])}.

    A simulated confirmation was queued in the local outbox; nothing was sent to Lowe\'s or an external provider.

    View orders
    ' else: payment = result["payment"] body = f'
    {escape(payment["status"])}

    Sandbox payment was not approved

    Your cart is unchanged. Choose the approved scenario to continue.

    Try another scenario
    ' response = render(request, "Order result | Lowe's", body) except Exception as exc: if isinstance(exc, site_store.CheckoutError): message = " ".join(exc.errors.values()) else: message = "The local checkout could not be completed." response = render(request, "Checkout error | Lowe's", f'

    Check your checkout details

    {escape(message)}

    Return to checkout
    ', status_code=400) return set_session_cookie(response, token) @app.get("/orders", response_class=HTMLResponse) def orders(request: Request) -> HTMLResponse: owner = existing_owner(request) rows = site_store.orders_for_owner(owner, current_account_id(request)) if owner else [] if not rows: body = '

    Order Status

    No offline orders are associated with this browser session.

    Start shopping
    ' else: cards = "".join(f'
    {escape(str(order["status"]))}

    {escape(str(order["order_number"]))}

    {escape(str(order["customer_name"]))} · ${site_store.money(int(order["total_cents"]))} · {escape(str(order["fulfillment"]))}

    {len(order["items"])} line item(s), payment {escape(str(order["payment_status"]))}

    ' for order in rows) body = f'

    Order Status

    {cards}
    ' return render(request, "Order Status | Lowe's", body) # --------------------------------------------------------------------------- # locally generated product artwork # --------------------------------------------------------------------------- @app.get("/img/p/{product_id}/{view}.svg") def product_artwork(product_id: int, view: str) -> Response: """Deterministic SVG for a catalog product. The clone ships no source photography for the synthetic catalog, so the ``/pd/``, ``/pl/``, ``/collections/`` and ``/configure/`` families draw their own artwork from the product's category palette and id. """ product = site_store.get_product(product_id) if product is None: return Response(status_code=404) category = commerce.category_index().get(str(product["category_id"]), {}) svg = product_svg(product, category, view if view in VIEWS else "front") return Response(svg, media_type="image/svg+xml") # --------------------------------------------------------------------------- # /l/... landing families # --------------------------------------------------------------------------- def landing_catalog(page: landing.Landing) -> str: if not page.catalog: return "" query, category_id, sort = page.catalog result = site_store.search( query=query, category_ids=[category_id] if category_id else (), sort=sort, page_size=8, ) heading = page.catalog_heading or "From this clone's catalog" return ( '
    ' f'

    {escape(heading)}

    ' 'Browse best sellers
    ' f'{catalog_grid(result["products"])}
    ' ) def landing_body(page: landing.Landing) -> str: trail = list(page.trail) if not trail or trail[-1][0] != page.heading: trail.append((page.heading, None)) return ( '
    ' + breadcrumb_bar(trail) + f'

    {escape(page.family)}

    ' + f'

    {escape(page.heading)}

    ' + f'

    {escape(page.intro)}

    ' + sandbox_notice(SOURCE_RESTRICTED_NOTE) + action_row(page.actions) + ( '
    ' '

    On this page

    ' + highlight_grid(page.highlights) + "
    " if page.highlights else "" ) + ( '

    ' "What this clone actually does

    " + fact_table(page.facts) + "
    " if page.facts else "" ) + landing_catalog(page) + "
    " ) @app.get("/l/{path:path}", response_class=HTMLResponse) def landing_route(request: Request, path: str) -> HTMLResponse: page = landing.LANDING_PAGES.get("/l/" + path.rstrip("/")) if page is None: return not_found(request, "/l/" + path) return render(request, page.title, landing_body(page)) # --------------------------------------------------------------------------- # /ai — local shopping assistant # --------------------------------------------------------------------------- AI_STARTERS = ( "refrigerator", "cordless drill", "interior paint", "ceiling fan", "water heater", "lawn mower", ) @app.get("/ai", response_class=HTMLResponse) def ai_assistant(request: Request, q: str = "") -> HTMLResponse: question = q.strip() starters = "".join( f'{escape(term)}' for term in AI_STARTERS ) if question: result = site_store.search(query=question, sort="relevance", page_size=6) if result["products"]: answer = ( f'

    {int(result["total"])} item(s) in this ' f"clone's catalog match “{escape(question)}”. The ranking is the " "same deterministic relevance score the search page uses.

    " + catalog_grid(result["products"]) ) else: answer = ( '

    Nothing in this catalog matches that

    ' f"

    “{escape(question)}” returned no rows. This assistant can only " "answer from the frozen local catalog — it never calls a model, a " "search service or any other network endpoint.

    " ) else: answer = ( '

    Ask about something in this catalog

    ' "

    Pick a starter above or type a product, brand or category.

    " ) body = ( '
    ' + breadcrumb_bar([("Home", "/"), ("AI Assist", None)]) + '

    AI Assist

    ' + '

    Lowe\'s AI Assist

    ' + '

    A local, deterministic shopping assistant. It ' "answers only from this clone's frozen catalog, so the same question " "always returns the same items.

    " + sandbox_notice( "No model, inference endpoint or third-party service is contacted. " "The source /ai page answered Access Denied to the recorded " "Playwright session, so this is not a reproduction of it." ) + '
    ' '' '
    ' f'
    {starters}
    ' + answer + "
    " ) title = ( f"AI Assist: {question} | Lowe's" if question else "Lowe's AI Assist | Lowe's" ) return render(request, title, body, query=question) # --------------------------------------------------------------------------- # /b/lowesbrands — brand directory # --------------------------------------------------------------------------- @app.get("/b/lowesbrands", response_class=HTMLResponse) def brand_directory(request: Request, brand: str = "") -> HTMLResponse: all_brands = site_store.brands() counts = site_store.search(page_size=1)["facet_brands"] selected = brand if brand in all_brands else "" tiles = "".join( f'' f"{escape(name)}" f'{int(counts.get(name, 0))} items' for name in all_brands ) if selected: result = site_store.search(brand_names=[selected], sort="top-sellers", page_size=12) listing = ( '
    ' f'

    {escape(selected)} in this catalog

    ' 'Show every brand
    ' f'{catalog_grid(result["products"])}
    ' ) else: listing = ( '

    Choose a brand to see ' "everything this clone's catalog carries under it.

    " ) body = ( '
    ' + breadcrumb_bar([("Home", "/"), ("Brands", None)]) + '

    Brand Directory

    ' + "

    Lowe's Brands

    " + '

    Every brand below is invented for this offline ' "clone and deliberately names no real Lowe's vendor, so a brand page here " "can never be mistaken for a captured one.

    " + sandbox_notice(SOURCE_RESTRICTED_NOTE) + f'
    {tiles}
    ' + listing + "
    " ) title = ( f"{selected} | Lowe's Brands" if selected else "Lowe's Brands Directory | Lowe's" ) return render(request, title, body) # --------------------------------------------------------------------------- # /diy-projects-and-ideas and /n/how-to/... # --------------------------------------------------------------------------- DIY_THEMES = ( ( "Outdoor cooking", "Clean, season and store a grill so it lights first time next season.", "/n/how-to/clean-and-maintain-your-grill-ht", "Read the how-to", ), ( "Family workshops", "Free hands-on builds for the MyLowe's Rewards Kids Club.", "/diy-projects-and-ideas/workshops", "See workshops", ), ( "Seasonal refresh", "Room-by-room ideas that need paint, lighting and hardware only.", "/l/fresh-projects-and-inspiration", "Get inspired", ), ( "Home maintenance", "The seasonal checklist behind this clone's repeat-delivery categories.", "/l/shop/home-maintenance", "See the checklist", ), ( "Window treatments", "Measure an opening and configure a blind to it, priced server-side.", "/configure/blinds/allen-roth-Cordless-Cellular-Shade/5015737843", "Open the configurator", ), ( "Paint projects", "Sheens, primers and coverage for interior and exterior work.", "/l/shop/online-paint-store", "Visit the paint store", ), ) @app.get("/diy-projects-and-ideas", response_class=HTMLResponse) def diy_projects(request: Request) -> HTMLResponse: cards = "".join( '
    ' f"

    {escape(title)}

    {escape(copy)}

    " f'{escape(cta)}' "
    " for title, copy, href, cta in DIY_THEMES ) body = ( '
    ' + breadcrumb_bar([("Home", "/"), ("DIY Projects & Ideas", None)]) + '

    Ideas & Inspiration

    ' + '

    DIY Projects & Ideas

    ' + '

    The project hub that sits above this clone\'s ' "how-to article, its family workshops page and its configurable window " "treatments. Every card below opens a page this clone serves itself.

    " + sandbox_notice(SOURCE_RESTRICTED_NOTE) + f'
    {cards}
    ' + "
    " ) return render(request, "DIY Projects & Ideas | Lowe's", body) GRILL_HOW_TO = { "intro": ( "A grill that is cleaned after the season lights faster, cooks more " "evenly and lasts longer. This is the full sequence, from a burnt-on " "grate to a covered grill ready for storage." ), "time": "About 60 minutes, plus drying time", "difficulty": "Beginner", "steps": ( ( "Burn off the residue", "Run the grill on high with the lid closed for 15 minutes so food " "residue turns to ash, then turn it off and let it cool enough to " "handle.", ), ( "Brush the grates", "Work along the bars, not across them, with a stiff grate brush. " "Replace a brush as soon as bristles start to shed.", ), ( "Empty the grease tray", "Pull the tray and the catch cup, scrape them out and wash them. A " "full tray is the most common cause of a flare-up.", ), ( "Clean the burner tubes", "Brush along the tubes so every port is open, and check that the " "flame is blue and even when you relight.", ), ( "Wash the exterior", "Warm water and dish soap on the lid and cart, rinsed and dried. " "Wipe stainless steel along the grain.", ), ( "Season and cover", "Coat the grates with a thin film of high-smoke-point oil, run the " "grill for 15 minutes, let it cool and fit the cover.", ), ), "supplies": ( "Grate brush or scraper", "Bucket, warm water and dish soap", "Non-abrasive cloths", "High-smoke-point cooking oil", "Replacement grease cups", "A fitted grill cover", ), } @app.get("/n/how-to/{article}", response_class=HTMLResponse) def how_to_article(request: Request, article: str) -> HTMLResponse: slug = article.rstrip("/") if not slug: return not_found(request, "/n/how-to/") # The captured inventory carries exactly one how-to path; anything else that # matches the pattern gets the same structure with its own URL-derived title # rather than a shared filler body. is_grill = slug.startswith("clean-and-maintain-your-grill") display = commerce.humanize(slug.removesuffix("-ht")) heading = "How to Clean and Maintain Your Grill" if is_grill else f"How to {display}" intro = GRILL_HOW_TO["intro"] if is_grill else ( f"A step-by-step local article for {display.lower()}. This clone ships " "one fully written how-to; every other path in the family renders this " "same structure from its own URL." ) steps = "".join( f"
  • {escape(title)}

    {escape(copy)}

  • " for title, copy in ( GRILL_HOW_TO["steps"] if is_grill else (("Plan the work", intro),) ) ) supplies = "".join( f"
  • {escape(item)}
  • " for item in (GRILL_HOW_TO["supplies"] if is_grill else ("Project-specific supplies",)) ) related = site_store.search( query="grill" if is_grill else "", category_ids=("outdoor-living",), page_size=4 ) body = ( '
    ' + breadcrumb_bar( [ ("Home", "/"), ("DIY Projects & Ideas", "/diy-projects-and-ideas"), (heading, None), ] ) + '

    How-To

    ' + f'

    {escape(heading)}

    ' + f'

    {escape(intro)}

    ' + sandbox_notice(SOURCE_RESTRICTED_NOTE) + fact_table( ( ("Time", str(GRILL_HOW_TO["time"]) if is_grill else "Varies"), ("Difficulty", str(GRILL_HOW_TO["difficulty"]) if is_grill else "Varies"), ("Steps", str(len(GRILL_HOW_TO["steps"]) if is_grill else 1)), ) ) + f'

    Steps

      {steps}
    ' + f'

    What you need

    ' + ( '
    ' '

    Shop this project

    ' 'Shop outdoors
    ' + catalog_grid(related["products"]) + "
    " if related["products"] else "" ) + "
    " ) return render(request, f"{heading} | Lowe's", body) # --------------------------------------------------------------------------- # /store/ — store finder # --------------------------------------------------------------------------- @app.get("/store/", response_class=HTMLResponse) def store_finder(request: Request, q: str = "") -> HTMLResponse: needle = q.strip().casefold() rows = site_store.stores() matches = [ row for row in rows if not needle or needle in " ".join( str(row[key]).casefold() for key in ("name", "city", "state", "zip") ) ] cards = "".join( '
    ' f'

    {escape(str(row["name"]))}

    ' f'

    {escape(str(row["city"]))}, {escape(str(row["state"]))} {escape(str(row["zip"]))}
    ' f'Closes at {escape(str(row["closes_at"]))}

    ' f'' f'Stores in {escape(str(row["state"]))}' "
    " for row in matches ) if not matches: cards = ( '

    No store matches that search

    ' "

    This clone carries four synthetic stores. Clear the search to see " "them all.

    " ) body = ( '
    ' + breadcrumb_bar([("Home", "/"), ("Find a Store", None)]) + '

    Store Finder

    ' + "

    Find a Lowe's Store

    " + '

    These four stores are the ones the local pickup ' "selector and the sandbox checkout actually use. Searching filters them " "on the server.

    " + sandbox_notice(SOURCE_RESTRICTED_NOTE) + '' f'

    {len(matches)} of {len(rows)} stores

    ' f'
    {cards}
    ' + action_row( ( ("Full store directory", "/Lowes-Stores"), ("In-store services", "/l/about/store-services"), ) ) + "
    " ) return render(request, "Find a Lowe's Store Near You | Lowe's", body) # --------------------------------------------------------------------------- # /weekly-ad # --------------------------------------------------------------------------- WEEKLY_AD_EVIDENCE_NOTE = ( "Evidence gap: the recorded Playwright replay of the source Weekly Ad only " "ever captured a loading skeleton, so no source layout was observed for this " "route at all. The circular below is built entirely from this clone's own " "catalog savings." ) @app.get("/weekly-ad", response_class=HTMLResponse) def weekly_ad(request: Request, store: str = "") -> HTMLResponse: stores = site_store.stores() selected = next( (row for row in stores if str(row["id"]) == store), stores[0] if stores else None ) options = "".join( f'' for row in stores ) front = site_store.search(sort="savings", page_size=4) inside = site_store.search(sort="savings", page_size=8, page=2) body = ( '
    ' + breadcrumb_bar([("Home", "/"), ("Weekly Ad", None)]) + '

    Weekly Ad

    ' + '

    This Week\'s Ad

    ' + '

    Every offer below is computed from the local ' "catalog's own was-and-now prices, so the ad, the product card and the " "cart all quote the same number.

    " + sandbox_notice(WEEKLY_AD_EVIDENCE_NOTE) + '
    ' '' '
    ' + ( f'

    Showing the ad for {escape(str(selected["name"]))},' f' {escape(str(selected["city"]))}, {escape(str(selected["state"]))}.

    ' if selected else "" ) + '
    ' '

    Front page

    ' + catalog_grid(front["products"]) + "
    " '
    ' '

    Inside the ad

    ' 'All savings
    ' + catalog_grid(inside["products"]) + "
    " + action_row( ( ("Coupons", "/l/savings/coupons"), ("Daily deals", "/l/savings/daily-deals"), ("Find a store", "/store/"), ) ) + "
    " ) return render(request, "Weekly Ad | Lowe's", body) # --------------------------------------------------------------------------- # /mylowes/orders/checkorderstatus — guest order lookup # --------------------------------------------------------------------------- @app.get("/mylowes/orders/checkorderstatus", response_class=HTMLResponse) def check_order_status( request: Request, email: str = "", order_number: str = "" ) -> HTMLResponse: result = "" if email.strip() and order_number.strip(): order = site_store.get_order(order_number.strip().upper()) # The same wording covers "no such order" and "wrong email", so the form # cannot be used to discover which order numbers exist. if order and str(order["email"]).casefold() == email.strip().casefold(): items = "".join( f'{escape(str(item["title"]))}' f'{int(item["quantity"])}' f'{cents(int(item["line_total_cents"]))}' for item in order["items"] ) result = ( '
    ' f'{escape(str(order["status"]))}' f'

    {escape(str(order["order_number"]))}

    ' f'

    {escape(str(order["customer_name"]))} · ' f'{escape(str(order["fulfillment"]))} · ' f'{cents(int(order["total_cents"]))}

    ' '' f"{items}
    ItemQtyLine total
    " "

    This is a local sandbox order. No Lowe's order exists.

    " ) else: result = ( '
    No local order matches that ' "order number and email address. This lookup only reads orders " "placed inside this clone.
    " ) body = ( '
    ' + breadcrumb_bar( [ ("Home", "/"), ("Orders Search", "/mylowes/orders"), ("Check Order Status", None), ] ) + '
    ' "

    Look Up an Order

    " '

    Enter the order number from a local sandbox confirmation together with ' "the email address it was placed under. The lookup runs against this " "clone's own database.

    " '
    ' '" '" '' "
    " + result + '' '

    Back to Orders Search

    ' "
    " ) return render(request, "Look Up an Order — Check Order Status | Lowe's", body) # --------------------------------------------------------------------------- # /lists # --------------------------------------------------------------------------- @app.get("/lists", response_class=HTMLResponse) def lists_page(request: Request) -> HTMLResponse: body = ( '
    ' + breadcrumb_bar([("Home", "/"), ("Lists", None)]) + '

    Lists

    ' + '

    Saved lists are an account feature. This clone ' "keeps a real per-session cart instead, and does not persist a separate " "list.

    " + '

    No saved lists

    ' '

    Go to your cart

    ' + "
    " ) return render(request, "Lists | Lowe's", body) # --------------------------------------------------------------------------- # /pd/{source-slug}/{item-id} — product detail # --------------------------------------------------------------------------- @app.get("/pd/{slug}/{item_id}", response_class=HTMLResponse) def product_detail_route(request: Request, slug: str, item_id: str) -> HTMLResponse: detail = commerce.product_detail(slug, item_id) product = detail["product"] thumbs = "".join( f'" for index, view in enumerate(VIEWS) ) specs = "".join( f'{escape(str(name))}{escape(str(value))}' for name, value in product["specs"] ) specs += ( f'Model{escape(str(product["model_number"]))}' f'Item{escape(item_id)}' f'Category{escape(detail["category_label"])}' ) pickup_note = ( "Free pickup today at your selected store" if product["pickup_today"] else "Not available for store pickup" ) body = ( '
    ' + breadcrumb_bar( [ ("Home", "/"), (detail["category_label"], f'/c/{quote_plus(detail["category_label"])}'), (detail["display_title"], None), ] ) + '
    ' f'
    {thumbs}
    ' f'
    ' '
    ' f'{escape(str(product["brand"]))}' f'

    {escape(detail["display_title"])}

    ' f'

    Item # {escape(item_id)} · ' f'Model # {escape(str(product["model_number"]))}

    ' + rating_line(product) + price_line(product) + f'

    {escape(str(product["summary"]))}

    ' '
    ' f'' '

    How do you want to get your item?

    ' '" '
    ' '
    ' '' '' '' '
    ' '' "
    " f'

    {int(product["stock"])} in stock in this ' "clone's synthetic inventory.

    " + sandbox_notice(SYNTHETIC_COMMERCE_NOTE) + "
    " f'

    Product details

    ' f'{specs}
    ' + ( '
    ' '

    Customers also viewed

    ' + catalog_grid(detail["related"]) + "
    " if detail["related"] else "" ) + "
    " ) return render(request, f"{detail['display_title']} | Lowe's", body) # --------------------------------------------------------------------------- # /pl/... — product list # --------------------------------------------------------------------------- def query_string(request: Request, **overrides: Any) -> str: pairs: list[tuple[str, str]] = [ (key, value) for key, value in request.query_params.multi_items() if key not in overrides ] for key, value in overrides.items(): if value in (None, "", False): continue if isinstance(value, (list, tuple)): pairs.extend((key, str(item)) for item in value) else: pairs.append((key, str(value))) return urlencode(pairs) def list_filters_form( action: str, request: Request, result: Mapping[str, Any] ) -> str: selected_brands = set(request.query_params.getlist("brand")) facet_brands = result["facet_brands"] brand_options = "".join( '' for name, count in sorted(facet_brands.items()) ) rating = request.query_params.get("rating", "") rating_options = "".join( '" for value in ("4.5", "4", "3") ) return ( f'
    ' '
    ' 'Brand' + (brand_options or '

    No brands in scope

    ') + "
    " '
    ' 'Price' '
    ' '' '' '' '' "
    " '
    ' 'Customer Rating' + rating_options + "
    " '
    ' 'Availability' '" '" "
    " f'' '' f'Clear all filters' "
    " ) def pagination_bar(path: str, request: Request, result: Mapping[str, Any]) -> str: if int(result["page_count"]) <= 1: return "" links = "".join( '{number}' for number in range(1, int(result["page_count"]) + 1) ) return f'' @app.get("/pl/{path:path}", response_class=HTMLResponse) def product_list_route(request: Request, path: str) -> HTMLResponse: segments = [segment for segment in path.split("/") if segment] if len(segments) < 2: return not_found(request, "/pl/" + path) collection_id = segments[-1] title_segments = segments[:-1] params = request.query_params page = params.get("page", "1") listing = commerce.list_page( title_segments, collection_id, brands=params.getlist("brand"), min_price=params.get("min_price", ""), max_price=params.get("max_price", ""), rating=params.get("rating", ""), pickup=bool(params.get("pickup")), free_delivery=bool(params.get("free_delivery")), sort=params.get("sort", "relevance"), page=int(page) if page.isdigit() else 1, ) result = listing["result"] action = "/pl/" + path sort_options = "".join( f'" for key, label in site_store.SORT_OPTIONS ) refinement_chips = "".join( f'{escape(label)}' for label in listing["refinements"] ) body = ( '
    ' + breadcrumb_bar( [("Home", "/"), ("Shop", "/c/Departments"), (listing["heading"], None)] ) + '

    Collection ' + escape(collection_id) + "

    " + f'

    {escape(listing["heading"])}

    ' + (f'
    {refinement_chips}
    ' if refinement_chips else "") + sandbox_notice(SYNTHETIC_COMMERCE_NOTE) + '
    ' + list_filters_form(action, request, result) + "
    " + '
    ' + ( f'

    Showing {int(result["first_index"])}–' f'{int(result["last_index"])} of {int(result["total"])} results in ' f'{escape(listing["scope"]["label"])}

    ' if int(result["total"]) else '

    0 results

    ' ) + f'
    ' + "".join( f'' for name in params.getlist("brand") ) + '' f'' '
    ' "
    " + catalog_grid(result["products"]) + pagination_bar(action, request, result) + "
    " ) return render(request, f"{listing['heading']} at Lowes.com", body) # --------------------------------------------------------------------------- # /collections/{source-slug}/{collection-id} — appliance suites # --------------------------------------------------------------------------- @app.get("/collections/{slug}/{collection_id}", response_class=HTMLResponse) def collection_route(request: Request, slug: str, collection_id: str) -> HTMLResponse: package = commerce.collection_package(slug, collection_id) rows = "".join( '
    ' f'' f'' f'
    {escape(role)}' f'{escape(str(product["brand"]))}' f'' f'{escape(str(product["title"]))}{rating_line(product)}
    ' f'{cents(int(product["price_cents"]))}
    ' for role, product in package["members"] ) hidden_ids = "".join( f'' for product_id in package["product_ids"] ) body = ( '
    ' + breadcrumb_bar( [ ("Home", "/"), ("Appliances", "/c/Appliances"), (package["display_title"], None), ] ) + '

    Appliance Suite ' + escape(collection_id) + "

    " + f'

    {escape(package["display_title"])}

    ' + '

    A four-piece suite assembled from this clone\'s ' "catalog. Adding the suite adds every member as a real cart line, priced " "at each member's own catalog price.

    " + sandbox_notice(SYNTHETIC_COMMERCE_NOTE) + '
    ' + rows + "
    " '
    " + action_row( ( ("Shop appliances", "/c/Appliances"), ("Installation services", "/l/install"), ("Delivery details", "/l/help/shipping-delivery"), ) ) + "
    " ) return render(request, f"{package['display_title']} | Lowe's", body) # --------------------------------------------------------------------------- # /configure/blinds/{source-slug}/{item-id} — made-to-measure configurator # --------------------------------------------------------------------------- def option_select( name: str, label: str, options: Sequence[tuple[str, str]], selected: str ) -> str: choices = "".join( f'" for value, text in options ) return ( f'' ) @app.get("/configure/blinds/{slug}/{item_id}", response_class=HTMLResponse) def blinds_configurator( request: Request, slug: str, item_id: str ) -> HTMLResponse: quote = commerce.blind_configuration(slug, item_id, dict(request.query_params)) product = quote["product"] action = f"/configure/blinds/{slug}/{item_id}" body = ( '
    ' + breadcrumb_bar( [ ("Home", "/"), ("Window Treatments", "/c/Window-treatments-Home-decor"), (quote["display_title"], None), ] ) + '

    Made to Measure · Item # ' + escape(item_id) + "

    " + f'

    Configure: {escape(quote["display_title"])}

    ' + '

    Choose a size and the lift, opacity and colour ' "options. The quote is recalculated on the server from a frozen option " "table, so a hand-edited query string cannot produce an unpriced " "configuration.

    " + sandbox_notice(SYNTHETIC_COMMERCE_NOTE) + '
    ' f'
    ' + option_select( "width", "Width (inches)", tuple((str(value), f"{value} in") for value in commerce.BLIND_WIDTHS), str(quote["width"]), ) + option_select( "height", "Height (inches)", tuple((str(value), f"{value} in") for value in commerce.BLIND_HEIGHTS), str(quote["height"]), ) + option_select("mount", "Mount", commerce.BLIND_MOUNTS, quote["mount"]) + option_select( "control", "Lift control", tuple((value, label) for value, label, _extra in commerce.BLIND_CONTROLS), quote["control"], ) + option_select("opacity", "Opacity", commerce.BLIND_ROOMS, quote["opacity"]) + option_select("color", "Colour", commerce.BLIND_COLORS, quote["color"]) + '' "
    " f'
    {escape(quote[
    ' "
    " '
    " + action_row( ( ("Special orders", "/l/help/special-orders"), ("Installation services", "/l/install"), ("Shop window treatments", "/c/Window-treatments-Home-decor"), ) ) + "
    " ) return render( request, f"Configure {quote['display_title']} | Lowe's", body ) # --------------------------------------------------------------------------- # not found # --------------------------------------------------------------------------- def not_found(request: Request, path: str) -> HTMLResponse: body = ( '

    Page not found

    ' f"

    Nothing is served at {escape(path)} in this offline " "clone.

    " '

    Back to home ' 'Shop all departments

    ' "
    " ) return render(request, "Page not found | Lowe's", body, status_code=404) @app.get("/{path:path}") def informational(request: Request, path: str) -> Response: target = LEGACY_REDIRECTS.get(path.strip("/")) if target: # A pre-inventory alias keeps working, but the source-compatible path is # the one canonical URL from here on. return RedirectResponse(target, status_code=308) return not_found(request, "/" + path)