AgPerry's picture
Add files using upload-large-folder tool
187ef74 verified
Raw History Blame Contribute Delete
116 kB
"""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'<a href="{escape(href, quote=True)}">{escape(label)}</a>')
else:
parts.append(f"<span>{escape(label)}</span>")
return (
'<nav class="breadcrumbs" aria-label="Breadcrumb">'
+ " / ".join(parts)
+ "</nav>"
)
def sandbox_notice(text: str) -> str:
return f'<p class="notice notice--sandbox">{escape(text)}</p>'
def action_row(actions: Sequence[tuple[str, str]]) -> str:
if not actions:
return ""
links = "".join(
f'<a href="{escape(href, quote=True)}">{escape(label)}</a>'
for label, href in actions
)
return f'<div class="category-links">{links}</div>'
def highlight_grid(highlights: Sequence[tuple[str, str]]) -> str:
if not highlights:
return ""
cards = "".join(
f"<article class=\"service-card\"><h3>{escape(title)}</h3><p>{escape(copy)}</p></article>"
for title, copy in highlights
)
return f'<div class="service-grid">{cards}</div>'
def fact_table(facts: Sequence[tuple[str, str]]) -> str:
if not facts:
return ""
rows = "".join(
f'<tr><th scope="row">{escape(term)}</th><td>{escape(value)}</td></tr>'
for term, value in facts
)
return f'<table class="spec-table"><tbody>{rows}</tbody></table>'
def rating_line(product: Mapping[str, Any]) -> str:
filled = int(float(product["rating"]) + 0.5)
stars = "★" * filled + "☆" * (5 - filled)
return (
f'<div class="rating"><span class="rating__stars">{stars}</span> '
f'{float(product["rating"]):.1f} ({int(product["review_count"]):,})</div>'
)
def price_line(product: Mapping[str, Any]) -> str:
price = int(product["price_cents"])
was = product.get("was_cents")
extra = ""
if was:
extra = (
f'<span class="price__was">Was {cents(int(was))}</span>'
f'<span class="price__save">Save {cents(int(was) - price)}</span>'
)
return f'<div class="price"><span class="price__amount">{cents(price)}</span>{extra}</div>'
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 = (
'<span class="product-card__flag"></span>'
f'<span class="product-card__flag-text">{escape(str(product["badge"]))}</span>'
)
url = escape(str(product["url"]), quote=True)
return f"""
<article class="product-card">{flag}
<a class="product-card__media" href="{url}"><img src="{catalog_art(int(product['id']))}" width="320" height="320" loading="lazy" alt="{escape(str(product['title']), quote=True)}"></a>
<div class="product-card__body"><span class="product-card__brand">{escape(str(product['brand']))}</span>
<a class="product-card__title" href="{url}">{escape(str(product['title']))}</a>
{rating_line(product)}{price_line(product)}
<form action="/cart/add" method="post"><input type="hidden" name="product_id" value="{int(product['id'])}"><button class="button button--primary button--block" type="submit">Add to Cart</button></form>
</div>
</article>"""
def catalog_grid(products: Sequence[Mapping[str, Any]]) -> str:
if not products:
return (
'<div class="empty-state"><h2>No matching items</h2>'
"<p>Clear a filter or widen the price range to see this clone's "
"catalog again.</p></div>"
)
return '<div class="card-grid">' + "".join(catalog_card(row) for row in products) + "</div>"
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'<span aria-hidden="true" class="ui-icon">{icons.get(name, "•")}</span>'
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'<button class="utility" type="button" data-account-open>{icon("account")}'
f"<span>{escape(label)}</span></button>"
)
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 = ' <span class="badge-new">New</span>' if label == "$99 Maintenance" else ""
child_links = "".join(
f'<a href="{child_href}">{escape(child_label)}</a>'
for child_label, child_href in children
)
items.append(
'<li class="catnav__item"><details data-catnav-menu>'
f'<summary class="catnav__link{strong}">{escape(label)}{badge}</summary>'
f'<div class="catnav__menu"><strong>{escape(label.lstrip("▦♙◇♧ "))}</strong>'
f'{child_links}<a class="catnav__all" href="{href}">View all →</a></div>'
"</details></li>"
)
return '<nav class="catnav" aria-label="Primary"><ul class="shell catnav__list">' + "".join(items) + "</ul></nav>"
def header(
cart_count: int = 0, query: str = "", account: dict[str, Any] | None = None
) -> str:
q = escape(query, quote=True)
return f"""
<div class="promo-strip"><div class="shell">
<span class="promo-strip__deal">Shop this week’s top deals now. &gt;</span>
<ul class="promo-strip__links"><li><a href="/l/Credit">Lowe's Credit Center</a></li><li><a href="/mylowes/orders">Order Status</a></li><li><a href="/weekly-ad">Weekly Ad</a></li><li><a href="/l/Pro">Lowe's PRO</a></li></ul>
</div></div>
<header class="masthead"><div class="shell masthead__row">
<button class="header-menu" type="button" aria-label="Open menu">{icon('menu')}</button>
<a class="brand-logo lowes-wordmark" href="/" aria-label="Lowe's home"><span>LOWE'S</span></a>
<div class="locator"><button class="locator__button" type="button">{icon('store')} <strong>Find a Store Near Me</strong>⌄</button></div>
<div class="searchbar">
<form class="searchbar__form" action="/search" method="get" data-suggest-form>
{icon('search')}<input class="searchbar__input" name="q" value="{q}" placeholder="What can we help you find?" autocomplete="off" data-suggest-input aria-expanded="false">
<button class="icon-button" type="submit" aria-label="Search">⌕</button>
</form><div class="suggestions" data-suggest-panel hidden></div>
</div>
<nav class="masthead__utilities" aria-label="Utilities">
<a class="utility utility-ai" href="/ai">{icon('ai')}<span>AI Assist</span></a>
{account_utility(account)}
<a class="utility utility--cart" href="/cart">{icon('cart')}<span>Cart</span>{f'<b class="utility__count">{cart_count}</b>' if cart_count else ''}</a>
</nav>
</div></header>
{catnav()}<div class="mobile-locator"><button type="button">{icon('store')} Find a Store Near Me⌄</button></div>
"""
DRAWER_BENEFITS = (
'<ul class="drawer__benefits"><li>▣ <a href="/orders">Order Status</a></li>'
'<li>⚒ <a href="/l/install">Projects &amp; Installations</a></li>'
'<li>♡ <a href="/lists">Lists</a></li>'
'<li>♟ <a href="/l/about/honor-our-military">Military Discount</a></li>'
'<li>✱ <a href="/l/about/mylowes-rewards">MyLowe\'s Rewards Benefits</a></li></ul>'
)
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"""
<p class="drawer__intro">Signed in as <strong>{escape(str(account.get('contact_display', '')))}</strong> in this offline clone. Nothing here exists at Lowe's.</p>
<form action="/account/signout" method="post">
<button class="button button--primary button--block" type="submit">Sign Out</button>
</form>
<p class="drawer__legal">Signing out revokes this local session on the server before the cookie is deleted.</p>
{DRAWER_BENEFITS}"""
else:
title = "Sign In or Create Account"
contents = f"""
<p class="drawer__intro">Enter your <strong>email or phone number</strong> to get started. We'll check if you have an account.</p>
<form action="/account/start" method="post">
<label class="field"><span class="visually-hidden">Email or Phone Number</span><input class="field__control" name="identifier" placeholder="Email or Phone Number" required></label>
<label class="checkbox"><input type="checkbox" checked name="remember"> Remember me on this device ⓘ</label>
<button class="button button--primary button--block" type="submit">Continue</button>
</form>
<p class="drawer__legal"><a href="/account/reset">Forgot your password?</a></p>
<p class="drawer__legal">By signing in, you're agreeing to our <a href="/l/about/terms-and-conditions-of-use">Terms of Use</a>, <a href="/l/about/privacy-and-security-statement">Privacy Statement</a>, and local clone terms.</p>
{DRAWER_BENEFITS}"""
return f"""
<div class="drawer-overlay" data-account-overlay {hidden}></div>
<aside class="drawer" data-account-drawer="{state}" {hidden} aria-label="{escape(title, quote=True)}">
<div class="drawer__head"><h2 class="drawer__title">{escape(title)}</h2><button class="icon-button" data-account-close aria-label="Close">{icon('close')}</button></div>{contents}
</aside>
"""
# 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"<section><h3>{escape(title)}</h3><ul>"
+ "".join(
f'<li><a href="{escape(href, quote=True)}">{escape(label)}</a></li>'
for label, href in items
)
+ "</ul></section>"
for title, items in FOOTER_GROUPS.items()
)
return f'<footer class="site-footer"><div class="shell"><div class="footer-grid">{columns}</div><p class="footer-note">Offline WebsiteBench clone for evaluation. No real Lowe\'s account, payment, fulfillment, message, or order is created.</p></div></footer>'
def product_card(product: dict[str, object]) -> str:
price = float(product["price"])
was = float(product["was"])
return f"""
<article class="product-card">
<span class="product-card__flag"></span><span class="product-card__flag-text">SALE</span>
<a class="product-card__media" href="/product/{product['slug']}"><img src="/static/assets/playwright-20260821/{product['image']}" alt="{escape(str(product['title']), quote=True)}"></a>
<div class="product-card__body"><span class="product-card__brand">{escape(str(product['brand']))}</span>
<a class="product-card__title" href="/product/{product['slug']}">{escape(str(product['title']))}</a>
<div class="rating"><span class="rating__stars">★★★★★</span> {product['rating']} ({product['reviews']})</div>
<div class="price"><span class="price__amount">{money(price)}</span><span class="price__was">Was {money(was)}</span><span class="price__save">Save {money(was-price)}</span></div>
<form action="/cart/add" method="post"><input type="hidden" name="slug" value="{product['slug']}"><button class="button button--primary button--block" type="submit">Add to Cart</button></form>
</div>
</article>"""
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"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{escape(title)}</title><link rel="icon" href="/static/site/img/lowes-logo.svg" type="image/svg+xml"><link rel="stylesheet" href="/static/site/lowes.css"><link rel="stylesheet" href="/static/site/overrides.css"></head><body>{header(cart_count, query, account)}{body}{footer()}{drawer(account_open, account)}<script src="/static/site/lowes.js" defer></script></body></html>"""
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"""
<main><section class="section shell recommendation"><div class="section__head"><h2 class="section__title">Recommended searches</h2></div><div class="chip-row">
<a class="chip" href="/search?q=cordless+drill">Cordless drills</a><a class="chip" href="/search?q=refrigerator">Refrigerators</a><a class="chip" href="/search?q=patio">Patio furniture</a><a class="chip" href="/search?q=paint">Interior paint</a><a class="chip" href="/search?q=grill">Grills</a>
</div></section>
<section class="shell hero-wrap"><div class="hero"><h1 class="hero__title">Electrolux End-of-Summer Sale</h1><div class="hero__brands">ELECTROLUX · FRIGIDAIRE · FRIGIDAIRE GALLERY · FRIGIDAIRE PROFESSIONAL</div><div class="playwright-hero"><img src="/static/assets/playwright-20260821/004-a219863c39ce7ce3.webp" alt="Save up to $300 when you bundle select Frigidaire major appliances"></div><div class="members"><strong>myLowe's Rewards — Members Get More</strong><span>FREE Delivery and Haul Away</span><span>FREE Basic Installation and Installation Parts</span><span>2-Year Lowe's Protection Plan</span></div></div></section>
<section class="section shell"><div class="section__head"><h2 class="section__title">Featured appliance deals</h2><a class="section__more" href="/search?q=appliances">Shop all deals</a></div><div class="card-grid">{cards}</div></section>
<section class="section shell"><div class="section__head"><h2 class="section__title">Services for every project</h2></div><div class="service-grid"><article class="service-card"><h3>Installation Services</h3><p>Get help from independent installers in this local demo flow.</p><a href="/installations">Explore installations</a></article><article class="service-card"><h3>Find a Store</h3><p>Select a synthetic store for pickup and local availability.</p><a href="/stores">Choose a store</a></article><article class="service-card"><h3>Lowe's for Pros</h3><p>Tools and savings represented as offline-only sample data.</p><a href="/pro">Explore Pro services</a></article></div></section>
</main>"""
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'<li><a href="/c/{quote_plus(label.lower().replace(" & ", "-").replace(" ", "-"))}">{escape(label)}</a></li>' for label, _image in BEST_SELLER_DEPARTMENTS)
cards = "".join(
f'<a class="department-card" href="/c/{quote_plus(label.lower().replace(" & ", "-").replace(" ", "-"))}"><span class="department-card__image"><img src="/multipage-assets/{image}" alt=""></span><strong>{escape(label)}</strong></a>'
for label, image in BEST_SELLER_DEPARTMENTS
)
body = f"""<main class="best-sellers-page">
<section class="best-sellers-hero"><h1>Lowe’s Best Sellers</h1></section>
<button class="mobile-departments" type="button">Departments <span>›</span></button>
<div class="shell best-sellers-layout"><aside class="department-sidebar"><h2>All Departments</h2><ul>{sidebar}</ul></aside><section class="department-grid">{cards}<a class="button button--outline all-departments" href="/search">See All Departments</a></section></div>
</main>"""
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 = """<main class="shell campaign-page">
<div class="breadcrumbs"><a href="/">Home</a> / Workshops</div>
<h1>Welcome to MyLowe’s Rewards™ Kids Club!</h1>
<img class="campaign-wide" src="/multipage-assets/6413d48a98ac64be263b.webp" alt="Kids Club — your next family adventure starts here">
<a href="/?account=open"><img class="campaign-wide campaign-strip" src="/multipage-assets/c1a3471e45fbf690307d.avif" alt="Create your Kids Profile and sign up for workshops"></a>
<img class="campaign-wide" src="/multipage-assets/ebc23e062899cdd23b5a.avif" alt="Build, laugh and learn at a free workshop">
<section class="campaign-copy"><h2>Free workshops and family fun</h2><p>MyLowe’s Rewards members can create a kids profile, collect digital badges and register for hands-on family workshops in this local demo.</p><a class="button button--primary" href="/?account=open">Get Started</a></section>
</main>"""
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'<section class="state-group"><h2>{letter}</h2>{"".join(f"<a href=/stores/{quote_plus(state.lower().replace(chr(32), chr(45)))}>{escape(state)}</a>" for state in states)}</section>'
for letter, states in STATES.items()
)
body = f"""<main class="shell stores-page"><div class="breadcrumbs"><a href="/stores">Find a Store</a> / Store Directory</div><h1>State Directory</h1><p>Lowe's Stores in the U.S.</p><div class="states-grid">{groups}</div></main>"""
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'<main class="shell section"><div class="breadcrumbs"><a href="/Lowes-Stores">Store Directory</a> / {escape(label)}</div><h1>Lowe\'s Stores in {escape(label)}</h1><div class="store-results"><article class="service-card"><h2>{escape(label)} Lowe\'s</h2><p>Select a location in the header to see local pickup availability.</p><button class="button button--primary" type="button">Set as My Store</button></article></div></main>'
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 = '<div class="notice notice--sandbox">No matching local order was found. This form never contacts Lowe\'s.</div>' if result else ""
body = f"""<main class="order-search-page"><div class="shell"><div class="breadcrumbs"><a href="/">Home</a> / Orders Search</div><section class="order-search-card"><h1>Check Order Status</h1><div class="order-tabs"><button class="active" type="button">Online Orders</button><button type="button">Store Purchases</button><button type="button">Projects</button></div><form action="/mylowes/orders" method="get"><label class="field"><span class="visually-hidden">Email address</span><input class="field__control" type="email" name="email" placeholder="✉ Enter email address" required><small>Please enter the email address used to place the order</small></label><label class="field"><span class="visually-hidden">Order Number</span><input class="field__control" name="order_number" placeholder="▧ Enter Order Number" required><small>Found in your Order confirmation email</small></label><input type="hidden" name="result" value="not-found"><button class="button button--primary button--block">Check Order Status</button></form>{result_box}<p class="order-account-copy"><a href="/?account=open">Sign up</a> for a free MyLowe's account to track your orders and enjoy all the benefits.</p><p>Already have a MyLowe's account? <a href="/?account=open">Sign In</a></p></section></div></main>"""
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'<a class="subscription-tile" href="/search?q={quote_plus(label)}"><img src="/multipage-assets/{image}" alt=""><strong>{escape(label)}</strong></a>' for label, image in categories)
body = f"""<main class="subscriptions-page"><section class="subscriptions-hero"><img src="/multipage-assets/1c329ae2e5024a0fc51d.png" alt="Woman changing an air filter"><div class="subscriptions-panel"><h1><span>SUBSCRIPTIONS</span><br>MADE SIMPLE</h1><ul><li>Free Standard Shipping</li><li>5% Off Select Items</li><li>Automatic Repeat Deliveries</li><li>Cancel Anytime</li></ul><a class="button button--primary button--block" href="#how-it-works">Learn More</a><a href="/terms">Terms &amp; Conditions</a></div></section><section id="how-it-works" class="section shell"><h2 class="center-title">How does it work?</h2><div class="subscription-steps"><article><b>1</b><h3>Find eligible products</h3><p>Shop items available for repeat delivery.</p></article><article><b>2</b><h3>Choose your schedule</h3><p>Select a delivery frequency that works for you.</p></article><article><b>3</b><h3>Save automatically</h3><p>Manage or cancel your local demo subscription anytime.</p></article></div><h2 class="center-title">Popular subscription categories</h2><div class="subscription-grid">{tiles}</div></section></main>"""
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'<a href="/c/{child}"><span class="category-link__art" aria-hidden="true">{escape(child[0])}</span>{escape(child.replace("-", " ").title())}</a>'
for child in children
)
if not category_links:
category_links = f'<a href="/best-sellers">Best Sellers</a><a href="/search?q={quote_plus(label)}">Shop All {escape(label)}</a><a href="/subscriptions">Subscriptions</a>'
body = f'<main class="shell section category-page"><div class="breadcrumbs"><a href="/">Home</a> / {escape(label)}</div><h1>{escape(label)}</h1><div class="category-links">{category_links}</div><section class="section"><div class="section__head"><h2 class="section__title">Featured {escape(label)}</h2></div><div class="card-grid">{cards}</div></section></main>'
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'<main class="shell section"><div class="breadcrumbs"><a href="/">Home</a> / Search</div><div class="results-head"><div><h1 class="page-title">{escape(q) if q else "Shop All"}</h1><span class="results-head__count">{len(matches)} results</span></div><select class="field__control sort-select" aria-label="Sort"><option>Sort by: Relevance</option><option>Price: Low to High</option><option>Top Rated</option></select></div>{f"<div class=card-grid>{cards}</div>" if cards else "<div class=empty-state><h2>No exact results</h2><p>Try appliances, refrigerator, dishwasher, or range.</p></div>"}</main>'
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", '<main class="shell section empty-state"><h1>Product not found</h1><a href="/search">Continue shopping</a></main>', status_code=404)
body = f"""<main class="shell section"><div class="breadcrumbs"><a href="/">Home</a> / <a href="/search?q=appliances">Appliances</a> / {escape(str(product['brand']))}</div><div class="pdp"><div class="pdp__thumbs"><button class="pdp__thumb"><img src="/static/assets/playwright-20260821/{product['image']}" alt=""></button></div><div class="pdp__stage"><img src="/static/assets/playwright-20260821/{product['image']}" alt="{escape(str(product['title']), quote=True)}"></div><section class="pdp__buybox"><span class="product-card__brand">{escape(str(product['brand']))}</span><h1 class="pdp__title">{escape(str(product['title']))}</h1><div class="rating"><span class="rating__stars">★★★★★</span> {product['rating']} ({product['reviews']})</div><div class="price"><span class="price__amount">{money(float(product['price']))}</span><span class="price__was">Was {money(float(product['was']))}</span></div><div class="fulfillment"><h2>How do you want to get your item?</h2><label class="fulfillment-choice"><input type="radio" checked name="fulfillment"> Pickup — Select a store</label><label class="fulfillment-choice"><input type="radio" name="fulfillment"> Delivery — Available</label></div><form action="/cart/add" method="post"><input type="hidden" name="slug" value="{product['slug']}"><button class="button button--primary button--block" type="submit">Add to Cart</button></form><p class="notice notice--sandbox">Local demo only. No real inventory, fulfillment, or charge.</p></section></div><section class="section"><h2>Product details</h2><table class="spec-table"><tr><th>Brand</th><td>{escape(str(product['brand']))}</td></tr><tr><th>Category</th><td>{escape(str(product['category']))}</td></tr><tr><th>Model</th><td>WB-{str(product['slug'])[:12].upper()}</td></tr></table></section></main>"""
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 (
'<article class="cart-line">'
f'<a class="cart-line__media" href="{escape(href, quote=True)}">'
f'<img src="{art}" alt=""></a><div>'
f'<span class="product-card__brand">{escape(str(item["brand"]))}</span>'
f'<a class="product-card__title" href="{escape(href, quote=True)}">{escape(str(item["title"]))}</a>'
f"<p>{fulfillment} in this local demo.</p>"
'<form class="cart-line__actions" action="/cart/update" method="post">'
f'<input type="hidden" name="item_id" value="{int(item["item_id"])}">'
'<button name="action" value="minus">−</button>'
f'<strong>{int(item["quantity"])}</strong>'
'<button name="action" value="plus">+</button>'
'<button class="link-button" name="action" value="remove">Remove</button>'
"</form></div>"
f'<strong>{cents(int(item["line_total_cents"]))}</strong></article>'
)
@app.get("/cart", response_class=HTMLResponse)
def cart_page(request: Request) -> HTMLResponse:
_owner, cart = cart_for(request)
if not cart["items"]:
body = '<main class="shell section empty-state"><h1>Your cart is empty</h1><p>Find everything you need for your next project.</p><a class="button button--primary" href="/search">Start shopping</a></main>'
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'<div class="summary__row"><span>Savings</span><strong>-{cents(savings)}</strong></div>'
if savings
else ""
)
body = (
'<main class="shell section">'
f'<h1 class="page-title">Cart ({int(cart["units"])} items)</h1>'
f'<div class="cart-layout"><section>{lines}</section>'
'<aside class="summary"><h2>Order Summary</h2>'
f'<div class="summary__row"><span>Subtotal</span><strong>{cents(int(cart["subtotal_cents"]))}</strong></div>'
f"{savings_row}"
'<div class="summary__row"><span>Estimated tax</span><span>Calculated at checkout</span></div>'
f'<div class="summary__row summary__row--total"><span>Estimated total</span><strong>{cents(int(cart["subtotal_cents"]))}</strong></div>'
'<a class="button button--primary button--block" href="/checkout">Checkout</a>'
'<p class="notice notice--sandbox">All payments are local sandbox simulations.</p>'
"</aside></div></main>"
)
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'<option value="{escape(item["id"], quote=True)}">{escape(item["display_label"])} — {escape(item["outcome"])}</option>' for item in scenarios)
button_disabled = "disabled" if not backend_cart["items"] else ""
body = f'<main class="shell section"><div class="breadcrumbs"><a href="/cart">Cart</a> / Checkout</div><h1 class="page-title">Checkout</h1><form class="checkout-layout" action="/checkout/place" method="post"><section><div class="notice notice--sandbox"><strong>WebsiteBench local sandbox</strong><br>No real Lowe\'s order or payment will be created.</div><h2>Contact information</h2><div class="card-grid card-grid--two"><label class="field"><span class="field__label">First name</span><input class="field__control" name="first_name" required value="Site"></label><label class="field"><span class="field__label">Last name</span><input class="field__control" name="last_name" required value="Tester"></label></div><label class="field"><span class="field__label">Email</span><input class="field__control" type="email" name="email" required value="annotator@example.test"></label><h2>Fulfillment</h2><label class="fulfillment-choice"><input type="radio" checked name="fulfillment" value="pickup"> Store pickup</label><input type="hidden" name="store_id" value="{escape(site_store.stores()[0]["id"], quote=True)}"><h2>Sandbox payment outcome</h2><label class="field"><span class="field__label">Scenario</span><select class="field__control" name="scenario_id">{options}</select></label></section><aside class="summary"><h2>Order summary</h2><div class="summary__row"><span>Subtotal</span><strong>${site_store.money(totals["subtotal_cents"])}</strong></div><div class="summary__row"><span>Estimated tax</span><strong>${site_store.money(totals["tax_cents"])}</strong></div><div class="summary__row summary__row--total"><span>Total</span><strong>${site_store.money(totals["total_cents"])}</strong></div><button class="button button--primary button--block" {button_disabled}>Place sandbox order</button><p>No card number, CVV, expiry, bank, or wallet information is accepted.</p></aside></form></main>'
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'<main class="shell section"><div class="notice notice--error"><h1>Check your entry</h1><p>{escape(message)}</p><a class="button button--primary" href="/?account=open">Try again</a></div></main>', account_open=True),
token,
)
identity = identified["identity"]
if identified["account_exists"]:
body = f'<main class="shell section"><h1>Welcome back</h1><form action="/account/signin" method="post"><input type="hidden" name="identifier" value="{escape(identifier_raw, quote=True)}"><label class="field"><span class="field__label">Password</span><input class="field__control" type="password" name="password" required></label><button class="button button--primary">Sign In</button></form><p><a href="/account/reset?identifier={quote_plus(identifier_raw)}">Forgot your password?</a></p></main>'
else:
phone_note = '<p class="notice notice--sandbox">Phone registration uses reserved test numbers only: 555-0100 through 555-0199, such as (213) 555-0142.</p>' if identity["kind"] == "phone" else ''
body = f'<main class="shell section"><h1>Create your local account</h1>{phone_note}<p>Verification will go only to the local WebsiteBench outbox for <strong>{escape(identity["display"])}</strong>.</p><form action="/account/create" method="post"><input type="hidden" name="identifier" value="{escape(identifier_raw, quote=True)}"><div class="card-grid card-grid--two"><label class="field"><span class="field__label">First name</span><input class="field__control" name="first_name" required></label><label class="field"><span class="field__label">Last name</span><input class="field__control" name="last_name" required></label></div><label class="field"><span class="field__label">Password</span><input class="field__control" type="password" name="password" minlength="8" required></label><button class="button button--primary">Send local verification code</button></form></main>'
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'<div class="notice notice--sandbox"><strong>Local sandbox code:</strong> <code>{escape(code or "unavailable")}</code><br>This value comes from the repository-approved local outbox and was not sent externally.</div>'
body = f'<main class="shell section"><h1>Verify your contact</h1><p>Enter the local code for <strong>{escape(result["identity"]["display"])}</strong>.</p>{help_box}<form action="/account/verify" method="post"><label class="field"><span class="field__label">Verification code</span><input class="field__control" name="code" inputmode="numeric" required></label><button class="button button--primary">Verify and create account</button></form></main>'
except Exception as exc:
_field, message = account_backend.friendly_error(exc)
body = f'<main class="shell section"><div class="notice notice--error"><h1>Could not start registration</h1><p>{escape(message)}</p><a class="button button--primary" href="/">Start again</a></div></main>'
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'<main class="shell section"><div class="order-banner"><h1>Account created</h1><p>Welcome, {name}. Your account and contact verification exist only in this offline clone.</p><a class="button button--primary" href="/">Continue shopping</a></div></main>'
# 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'<main class="shell section"><div class="notice notice--error"><h1>Verification failed</h1><p>{escape(message)}</p><a href="/">Start again</a></div></main>'
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'<main class="shell section"><div class="notice notice--error"><h1>Sign in failed</h1><p>{escape(message)}</p><a href="/">Try again</a></div></main>'),
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 = (
"<p>Enter the email or reserved test phone number on your local account. "
"This clone answers the same way whether or not an account exists.</p>"
)
def reset_request_form(identifier: str = "", notice: str = "") -> str:
return (
'<main class="shell section"><h1>Reset your password</h1>'
f"{notice}{RESET_STEP_INTRO}"
'<form action="/account/reset/start" method="post">'
'<label class="field"><span class="field__label">Email or Phone Number</span>'
'<input class="field__control" name="identifier" required '
f'value="{escape(identifier, quote=True)}"></label>'
'<button class="button button--primary">Send local reset code</button>'
"</form></main>"
)
@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'<div class="notice notice--error"><p>{escape(message)}</p></div>'
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 = (
'<div class="notice notice--sandbox"><strong>Local sandbox code:</strong> '
f'<code>{escape(code)}</code><br>This value comes from the local outbox '
"and was not sent externally.</div>"
if code
else '<div class="notice notice--sandbox">No local sandbox code is '
"available to display. Nothing was sent to any external service.</div>"
)
body = (
'<main class="shell section"><h1>Check your local outbox</h1>'
f'<p>{escape(str(result["flow"]["message"]))}</p>{help_box}'
'<form action="/account/reset/verify" method="post">'
'<label class="field"><span class="field__label">Verification code</span>'
'<input class="field__control" name="code" inputmode="numeric" required>'
"</label><button class=\"button button--primary\">Verify code</button>"
"</form></main>"
)
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 = (
'<main class="shell section"><div class="notice notice--error">'
f"<h1>Verification failed</h1><p>{escape(message)}</p>"
'<a class="button button--primary" href="/account/reset">Start again</a>'
"</div></main>"
)
return set_session_cookie(
render(request, "Reset your password | Lowe's", body, status_code=400),
token,
)
body = (
'<main class="shell section"><h1>Choose a new password</h1>'
'<form action="/account/reset/complete" method="post">'
'<label class="field"><span class="field__label">New password</span>'
'<input class="field__control" type="password" name="password" '
'minlength="8" required></label>'
'<button class="button button--primary">Save new password</button>'
"</form></main>"
)
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 = (
'<main class="shell section"><div class="notice notice--error">'
f"<h1>Password was not changed</h1><p>{escape(message)}</p>"
'<a class="button button--primary" href="/account/reset">Start again</a>'
"</div></main>"
)
return set_session_cookie(
render(request, "Reset your password | Lowe's", body, status_code=400),
token,
)
body = (
'<main class="shell section"><div class="order-banner"><h1>Password updated</h1>'
"<p>Every earlier local session for this account was revoked and you are "
"signed in on this device only.</p>"
'<a class="button button--primary" href="/">Continue shopping</a></div></main>'
)
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'<main class="shell section"><div class="order-banner"><span class="tag tag--approved">Approved local simulation</span><h1>Thanks, your offline order is recorded</h1><p>Order <strong>{escape(order["order_number"])}</strong> totals <strong>${site_store.money(order["total_cents"])}</strong>.</p><p>A simulated confirmation was queued in the local outbox; nothing was sent to Lowe\'s or an external provider.</p><a class="button button--primary" href="/orders">View orders</a></div></main>'
else:
payment = result["payment"]
body = f'<main class="shell section"><div class="notice notice--error"><span class="tag tag--declined">{escape(payment["status"])}</span><h1>Sandbox payment was not approved</h1><p>Your cart is unchanged. Choose the approved scenario to continue.</p><a class="button button--primary" href="/checkout">Try another scenario</a></div></main>'
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'<main class="shell section"><div class="notice notice--error"><h1>Check your checkout details</h1><p>{escape(message)}</p><a href="/checkout">Return to checkout</a></div></main>', 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 = '<main class="shell section empty-state"><h1>Order Status</h1><p>No offline orders are associated with this browser session.</p><a class="button button--primary" href="/search">Start shopping</a></main>'
else:
cards = "".join(f'<article class="service-card"><span class="tag tag--approved">{escape(str(order["status"]))}</span><h2>{escape(str(order["order_number"]))}</h2><p>{escape(str(order["customer_name"]))} · ${site_store.money(int(order["total_cents"]))} · {escape(str(order["fulfillment"]))}</p><p>{len(order["items"])} line item(s), payment {escape(str(order["payment_status"]))}</p></article>' for order in rows)
body = f'<main class="shell section"><h1 class="page-title">Order Status</h1><div class="service-grid">{cards}</div></main>'
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 (
'<section class="section"><div class="section__head">'
f'<h2 class="section__title">{escape(heading)}</h2>'
'<a class="section__more" href="/best-sellers">Browse best sellers</a></div>'
f'{catalog_grid(result["products"])}</section>'
)
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 (
'<main class="shell section landing-page">'
+ breadcrumb_bar(trail)
+ f'<p class="results-head__count">{escape(page.family)}</p>'
+ f'<h1 class="page-title">{escape(page.heading)}</h1>'
+ f'<p class="landing-intro">{escape(page.intro)}</p>'
+ sandbox_notice(SOURCE_RESTRICTED_NOTE)
+ action_row(page.actions)
+ (
'<section class="section"><div class="section__head">'
'<h2 class="section__title">On this page</h2></div>'
+ highlight_grid(page.highlights)
+ "</section>"
if page.highlights
else ""
)
+ (
'<section class="section"><h2 class="section__title">'
"What this clone actually does</h2>" + fact_table(page.facts) + "</section>"
if page.facts
else ""
)
+ landing_catalog(page)
+ "</main>"
)
@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'<a class="chip" href="/ai?q={quote_plus(term)}">{escape(term)}</a>'
for term in AI_STARTERS
)
if question:
result = site_store.search(query=question, sort="relevance", page_size=6)
if result["products"]:
answer = (
f'<p class="landing-intro">{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.</p>"
+ catalog_grid(result["products"])
)
else:
answer = (
'<div class="empty-state"><h2>Nothing in this catalog matches that</h2>'
f"<p>“{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.</p></div>"
)
else:
answer = (
'<div class="empty-state"><h2>Ask about something in this catalog</h2>'
"<p>Pick a starter above or type a product, brand or category.</p></div>"
)
body = (
'<main class="shell section ai-page">'
+ breadcrumb_bar([("Home", "/"), ("AI Assist", None)])
+ '<p class="results-head__count">AI Assist</p>'
+ '<h1 class="page-title">Lowe\'s AI Assist</h1>'
+ '<p class="landing-intro">A local, deterministic shopping assistant. It '
"answers only from this clone's frozen catalog, so the same question "
"always returns the same items.</p>"
+ 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."
)
+ '<form class="ai-form" action="/ai" method="get">'
'<label class="field"><span class="field__label">What are you looking for?</span>'
f'<input class="field__control" name="q" value="{escape(question, quote=True)}" '
'placeholder="Describe the project or the product"></label>'
'<button class="button button--primary" type="submit">Ask</button></form>'
f'<div class="chip-row">{starters}</div>'
+ answer
+ "</main>"
)
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'<a class="brand-tile{" brand-tile--active" if name == selected else ""}" '
f'href="/b/lowesbrands?brand={quote_plus(name)}">'
f"<strong>{escape(name)}</strong>"
f'<span>{int(counts.get(name, 0))} items</span></a>'
for name in all_brands
)
if selected:
result = site_store.search(brand_names=[selected], sort="top-sellers", page_size=12)
listing = (
'<section class="section"><div class="section__head">'
f'<h2 class="section__title">{escape(selected)} in this catalog</h2>'
'<a class="section__more" href="/b/lowesbrands">Show every brand</a></div>'
f'{catalog_grid(result["products"])}</section>'
)
else:
listing = (
'<section class="section"><p class="landing-intro">Choose a brand to see '
"everything this clone's catalog carries under it.</p></section>"
)
body = (
'<main class="shell section brand-page">'
+ breadcrumb_bar([("Home", "/"), ("Brands", None)])
+ '<p class="results-head__count">Brand Directory</p>'
+ "<h1 class=\"page-title\">Lowe's Brands</h1>"
+ '<p class="landing-intro">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.</p>"
+ sandbox_notice(SOURCE_RESTRICTED_NOTE)
+ f'<div class="brand-grid">{tiles}</div>'
+ listing
+ "</main>"
)
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(
'<article class="service-card">'
f"<h3>{escape(title)}</h3><p>{escape(copy)}</p>"
f'<a class="button button--outline" href="{escape(href, quote=True)}">{escape(cta)}</a>'
"</article>"
for title, copy, href, cta in DIY_THEMES
)
body = (
'<main class="shell section diy-page">'
+ breadcrumb_bar([("Home", "/"), ("DIY Projects & Ideas", None)])
+ '<p class="results-head__count">Ideas &amp; Inspiration</p>'
+ '<h1 class="page-title">DIY Projects &amp; Ideas</h1>'
+ '<p class="landing-intro">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.</p>"
+ sandbox_notice(SOURCE_RESTRICTED_NOTE)
+ f'<div class="service-grid">{cards}</div>'
+ "</main>"
)
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"<li><h3>{escape(title)}</h3><p>{escape(copy)}</p></li>"
for title, copy in (
GRILL_HOW_TO["steps"] if is_grill else (("Plan the work", intro),)
)
)
supplies = "".join(
f"<li>{escape(item)}</li>"
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 = (
'<main class="shell section how-to-page">'
+ breadcrumb_bar(
[
("Home", "/"),
("DIY Projects & Ideas", "/diy-projects-and-ideas"),
(heading, None),
]
)
+ '<p class="results-head__count">How-To</p>'
+ f'<h1 class="page-title">{escape(heading)}</h1>'
+ f'<p class="landing-intro">{escape(intro)}</p>'
+ 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'<section class="section"><h2 class="section__title">Steps</h2><ol class="how-to-steps">{steps}</ol></section>'
+ f'<section class="section"><h2 class="section__title">What you need</h2><ul class="how-to-supplies">{supplies}</ul></section>'
+ (
'<section class="section"><div class="section__head">'
'<h2 class="section__title">Shop this project</h2>'
'<a class="section__more" href="/c/Outdoors">Shop outdoors</a></div>'
+ catalog_grid(related["products"])
+ "</section>"
if related["products"]
else ""
)
+ "</main>"
)
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(
'<article class="service-card">'
f'<h3>{escape(str(row["name"]))}</h3>'
f'<p>{escape(str(row["city"]))}, {escape(str(row["state"]))} {escape(str(row["zip"]))}<br>'
f'Closes at {escape(str(row["closes_at"]))}</p>'
f'<a class="button button--outline" href="/stores/{quote_plus(str(row["state"]).lower())}">'
f'Stores in {escape(str(row["state"]))}</a>'
"</article>"
for row in matches
)
if not matches:
cards = (
'<div class="empty-state"><h2>No store matches that search</h2>'
"<p>This clone carries four synthetic stores. Clear the search to see "
"them all.</p></div>"
)
body = (
'<main class="shell section store-finder">'
+ breadcrumb_bar([("Home", "/"), ("Find a Store", None)])
+ '<p class="results-head__count">Store Finder</p>'
+ "<h1 class=\"page-title\">Find a Lowe's Store</h1>"
+ '<p class="landing-intro">These four stores are the ones the local pickup '
"selector and the sandbox checkout actually use. Searching filters them "
"on the server.</p>"
+ sandbox_notice(SOURCE_RESTRICTED_NOTE)
+ '<form class="store-search" action="/store/" method="get">'
'<label class="field"><span class="field__label">City, state or ZIP code</span>'
f'<input class="field__control" name="q" value="{escape(q, quote=True)}" '
'placeholder="Hawthorne, CA or 90250"></label>'
'<button class="button button--primary" type="submit">Find stores</button></form>'
f'<p class="results-head__count">{len(matches)} of {len(rows)} stores</p>'
f'<div class="service-grid">{cards}</div>'
+ action_row(
(
("Full store directory", "/Lowes-Stores"),
("In-store services", "/l/about/store-services"),
)
)
+ "</main>"
)
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'<option value="{escape(str(row["id"]), quote=True)}"'
+ (" selected" if selected and row["id"] == selected["id"] else "")
+ f'>{escape(str(row["name"]))} — {escape(str(row["city"]))}, {escape(str(row["state"]))}</option>'
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 = (
'<main class="shell section weekly-ad-page">'
+ breadcrumb_bar([("Home", "/"), ("Weekly Ad", None)])
+ '<p class="results-head__count">Weekly Ad</p>'
+ '<h1 class="page-title">This Week\'s Ad</h1>'
+ '<p class="landing-intro">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.</p>"
+ sandbox_notice(WEEKLY_AD_EVIDENCE_NOTE)
+ '<form class="weekly-ad-store" action="/weekly-ad" method="get">'
'<label class="field"><span class="field__label">Ad for store</span>'
f'<select class="field__control" name="store" data-autosubmit>{options}</select></label>'
'<button class="button button--outline" type="submit">Show this ad</button></form>'
+ (
f'<p class="results-head__count">Showing the ad for {escape(str(selected["name"]))},'
f' {escape(str(selected["city"]))}, {escape(str(selected["state"]))}.</p>'
if selected
else ""
)
+ '<section class="section"><div class="section__head">'
'<h2 class="section__title">Front page</h2></div>'
+ catalog_grid(front["products"])
+ "</section>"
'<section class="section"><div class="section__head">'
'<h2 class="section__title">Inside the ad</h2>'
'<a class="section__more" href="/l/savings">All savings</a></div>'
+ catalog_grid(inside["products"])
+ "</section>"
+ action_row(
(
("Coupons", "/l/savings/coupons"),
("Daily deals", "/l/savings/daily-deals"),
("Find a store", "/store/"),
)
)
+ "</main>"
)
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'<tr><th scope="row">{escape(str(item["title"]))}</th>'
f'<td>{int(item["quantity"])}</td>'
f'<td>{cents(int(item["line_total_cents"]))}</td></tr>'
for item in order["items"]
)
result = (
'<div class="order-banner">'
f'<span class="tag tag--approved">{escape(str(order["status"]))}</span>'
f'<h2>{escape(str(order["order_number"]))}</h2>'
f'<p>{escape(str(order["customer_name"]))} · '
f'{escape(str(order["fulfillment"]))} · '
f'{cents(int(order["total_cents"]))}</p>'
'<table class="spec-table"><thead><tr><th>Item</th><th>Qty</th>'
f"<th>Line total</th></tr></thead><tbody>{items}</tbody></table>"
"<p>This is a local sandbox order. No Lowe's order exists.</p></div>"
)
else:
result = (
'<div class="notice notice--error">No local order matches that '
"order number and email address. This lookup only reads orders "
"placed inside this clone.</div>"
)
body = (
'<main class="order-search-page"><div class="shell">'
+ breadcrumb_bar(
[
("Home", "/"),
("Orders Search", "/mylowes/orders"),
("Check Order Status", None),
]
)
+ '<section class="order-search-card">'
"<h1>Look Up an Order</h1>"
'<p>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.</p>"
'<form action="/mylowes/orders/checkorderstatus" method="get">'
'<label class="field"><span class="visually-hidden">Email address</span>'
f'<input class="field__control" type="email" name="email" value="{escape(email, quote=True)}" '
'placeholder="✉ Enter email address" required>'
"<small>The email address used at local checkout</small></label>"
'<label class="field"><span class="visually-hidden">Order Number</span>'
f'<input class="field__control" name="order_number" value="{escape(order_number, quote=True)}" '
'placeholder="▧ Enter Order Number, for example LWS-700001" required>'
"<small>Shown on the local order confirmation</small></label>"
'<button class="button button--primary button--block">Look Up Order</button>'
"</form>"
+ result
+ '<p class="order-account-copy">Signed in? Your local order history is on '
'<a href="/orders">Order Status</a>.</p>'
'<p><a href="/mylowes/orders">Back to Orders Search</a></p>'
"</section></div></main>"
)
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 = (
'<main class="shell section">'
+ breadcrumb_bar([("Home", "/"), ("Lists", None)])
+ '<h1 class="page-title">Lists</h1>'
+ '<p class="landing-intro">Saved lists are an account feature. This clone '
"keeps a real per-session cart instead, and does not persist a separate "
"list.</p>"
+ '<div class="empty-state"><h2>No saved lists</h2>'
'<p><a class="button button--primary" href="/cart">Go to your cart</a></p></div>'
+ "</main>"
)
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'<button class="pdp__thumb" type="button" aria-current="{"true" if index == 0 else "false"}"'
f' data-gallery-thumb="{catalog_art(int(product["id"]), view)}"'
f' data-gallery-alt="{escape(detail["display_title"], quote=True)} — {view} view">'
f'<img src="{catalog_art(int(product["id"]), view)}" width="80" height="80" alt="">'
"</button>"
for index, view in enumerate(VIEWS)
)
specs = "".join(
f'<tr><th scope="row">{escape(str(name))}</th><td>{escape(str(value))}</td></tr>'
for name, value in product["specs"]
)
specs += (
f'<tr><th scope="row">Model</th><td>{escape(str(product["model_number"]))}</td></tr>'
f'<tr><th scope="row">Item</th><td>{escape(item_id)}</td></tr>'
f'<tr><th scope="row">Category</th><td>{escape(detail["category_label"])}</td></tr>'
)
pickup_note = (
"Free pickup today at your selected store"
if product["pickup_today"]
else "Not available for store pickup"
)
body = (
'<main class="shell section pdp-page">'
+ breadcrumb_bar(
[
("Home", "/"),
(detail["category_label"], f'/c/{quote_plus(detail["category_label"])}'),
(detail["display_title"], None),
]
)
+ '<div class="pdp">'
f'<div class="pdp__thumbs">{thumbs}</div>'
f'<div class="pdp__stage"><img src="{catalog_art(int(product["id"]))}" '
f'alt="{escape(detail["display_title"], quote=True)}" data-gallery-stage></div>'
'<section class="pdp__buybox">'
f'<span class="product-card__brand">{escape(str(product["brand"]))}</span>'
f'<h1 class="pdp__title">{escape(detail["display_title"])}</h1>'
f'<p class="results-head__count">Item # {escape(item_id)} · '
f'Model # {escape(str(product["model_number"]))}</p>'
+ rating_line(product)
+ price_line(product)
+ f'<p>{escape(str(product["summary"]))}</p>'
'<form action="/cart/add" method="post">'
f'<input type="hidden" name="product_id" value="{int(product["id"])}">'
'<div class="fulfillment"><h2>How do you want to get your item?</h2>'
'<label class="fulfillment-choice"><input type="radio" name="fulfillment" '
f'value="pickup"{" checked" if product["pickup_today"] else " disabled"}> '
f"Pickup — {escape(pickup_note)}</label>"
'<label class="fulfillment-choice"><input type="radio" name="fulfillment" '
f'value="delivery"{"" if product["pickup_today"] else " checked"}> '
f'Delivery — {"Free" if product["free_delivery"] else "Fee applies"} in '
f'{int(product["delivery_days"])} days</label></div>'
'<div class="quantity" data-quantity>'
'<button type="button" data-quantity-step="-1" aria-label="Decrease quantity">−</button>'
'<label class="visually-hidden" for="pdp-quantity">Quantity</label>'
'<input id="pdp-quantity" type="number" name="quantity" value="1" min="1" max="99" step="1">'
'<button type="button" data-quantity-step="1" aria-label="Increase quantity">+</button></div>'
'<button class="button button--primary button--block" type="submit">Add to Cart</button>'
"</form>"
f'<p class="results-head__count">{int(product["stock"])} in stock in this '
"clone's synthetic inventory.</p>"
+ sandbox_notice(SYNTHETIC_COMMERCE_NOTE)
+ "</section></div>"
f'<section class="section"><h2 class="section__title">Product details</h2>'
f'<table class="spec-table"><tbody>{specs}</tbody></table></section>'
+ (
'<section class="section"><div class="section__head">'
'<h2 class="section__title">Customers also viewed</h2></div>'
+ catalog_grid(detail["related"])
+ "</section>"
if detail["related"]
else ""
)
+ "</main>"
)
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(
'<label class="filters__option"><input type="checkbox" name="brand"'
f' value="{escape(name, quote=True)}"'
+ (" checked" if name in selected_brands else "")
+ f'><span>{escape(name)}</span>'
f'<span class="results-head__count">({count})</span></label>'
for name, count in sorted(facet_brands.items())
)
rating = request.query_params.get("rating", "")
rating_options = "".join(
'<label class="filters__option"><input type="radio" name="rating"'
f' value="{value}"' + (" checked" if rating == value else "")
+ f"><span>{value} stars &amp; up</span></label>"
for value in ("4.5", "4", "3")
)
return (
f'<form class="filters" method="get" action="{escape(action, quote=True)}">'
'<fieldset class="filters__group">'
'<legend class="filters__legend">Brand</legend>'
+ (brand_options or '<p class="results-head__count">No brands in scope</p>')
+ "</fieldset>"
'<fieldset class="filters__group">'
'<legend class="filters__legend">Price</legend>'
'<div class="filters__price">'
'<label class="visually-hidden" for="min-price">Minimum price</label>'
'<input class="field__control" id="min-price" type="number" min="0" step="1"'
f' name="min_price" value="{escape(request.query_params.get("min_price", ""), quote=True)}" placeholder="Min">'
'<label class="visually-hidden" for="max-price">Maximum price</label>'
'<input class="field__control" id="max-price" type="number" min="0" step="1"'
f' name="max_price" value="{escape(request.query_params.get("max_price", ""), quote=True)}" placeholder="Max">'
"</div></fieldset>"
'<fieldset class="filters__group">'
'<legend class="filters__legend">Customer Rating</legend>'
+ rating_options
+ "</fieldset>"
'<fieldset class="filters__group">'
'<legend class="filters__legend">Availability</legend>'
'<label class="filters__option"><input type="checkbox" name="pickup" value="1"'
+ (" checked" if request.query_params.get("pickup") else "")
+ "><span>Pickup today</span></label>"
'<label class="filters__option"><input type="checkbox" name="free_delivery" value="1"'
+ (" checked" if request.query_params.get("free_delivery") else "")
+ "><span>Free delivery</span></label>"
"</fieldset>"
f'<input type="hidden" name="sort" value="{escape(request.query_params.get("sort", "relevance"), quote=True)}">'
'<button class="button button--primary button--block" type="submit">Apply filters</button>'
f'<a class="link-button" href="{escape(action, quote=True)}">Clear all filters</a>'
"</form>"
)
def pagination_bar(path: str, request: Request, result: Mapping[str, Any]) -> str:
if int(result["page_count"]) <= 1:
return ""
links = "".join(
'<a class="pagination__link"'
+ (' aria-current="page"' if number == int(result["page"]) else "")
+ f' href="{escape(path, quote=True)}?{escape(query_string(request, page=number), quote=True)}">{number}</a>'
for number in range(1, int(result["page_count"]) + 1)
)
return f'<nav class="pagination" aria-label="Result pages">{links}</nav>'
@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'<option value="{key}"'
+ (" selected" if result["sort"] == key else "")
+ f">{escape(label)}</option>"
for key, label in site_store.SORT_OPTIONS
)
refinement_chips = "".join(
f'<span class="applied-filters__chip">{escape(label)}</span>'
for label in listing["refinements"]
)
body = (
'<main class="shell section plp-page">'
+ breadcrumb_bar(
[("Home", "/"), ("Shop", "/c/Departments"), (listing["heading"], None)]
)
+ '<p class="results-head__count">Collection ' + escape(collection_id) + "</p>"
+ f'<h1 class="page-title">{escape(listing["heading"])}</h1>'
+ (f'<div class="applied-filters">{refinement_chips}</div>' if refinement_chips else "")
+ sandbox_notice(SYNTHETIC_COMMERCE_NOTE)
+ '<div class="results-layout">'
+ list_filters_form(action, request, result)
+ "<section>"
+ '<div class="results-head">'
+ (
f'<p class="results-head__count">Showing {int(result["first_index"])}–'
f'{int(result["last_index"])} of {int(result["total"])} results in '
f'{escape(listing["scope"]["label"])}</p>'
if int(result["total"])
else '<p class="results-head__count">0 results</p>'
)
+ f'<form method="get" action="{escape(action, quote=True)}">'
+ "".join(
f'<input type="hidden" name="brand" value="{escape(name, quote=True)}">'
for name in params.getlist("brand")
)
+ '<label class="visually-hidden" for="pl-sort">Sort by</label>'
f'<select class="field__control sort-select" id="pl-sort" name="sort" data-autosubmit>{sort_options}</select>'
'<button class="visually-hidden" type="submit">Sort</button></form>'
"</div>"
+ catalog_grid(result["products"])
+ pagination_bar(action, request, result)
+ "</section></div></main>"
)
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(
'<article class="package-member">'
f'<a class="package-member__media" href="{escape(str(product["url"]), quote=True)}">'
f'<img src="{catalog_art(int(product["id"]))}" width="320" height="320" alt=""></a>'
f'<div><span class="results-head__count">{escape(role)}</span>'
f'<span class="product-card__brand">{escape(str(product["brand"]))}</span>'
f'<a class="product-card__title" href="{escape(str(product["url"]), quote=True)}">'
f'{escape(str(product["title"]))}</a>{rating_line(product)}</div>'
f'<strong>{cents(int(product["price_cents"]))}</strong></article>'
for role, product in package["members"]
)
hidden_ids = "".join(
f'<input type="hidden" name="product_id" value="{product_id}">'
for product_id in package["product_ids"]
)
body = (
'<main class="shell section collection-page">'
+ breadcrumb_bar(
[
("Home", "/"),
("Appliances", "/c/Appliances"),
(package["display_title"], None),
]
)
+ '<p class="results-head__count">Appliance Suite '
+ escape(collection_id)
+ "</p>"
+ f'<h1 class="page-title">{escape(package["display_title"])}</h1>'
+ '<p class="landing-intro">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.</p>"
+ sandbox_notice(SYNTHETIC_COMMERCE_NOTE)
+ '<div class="cart-layout"><section class="package-list">'
+ rows
+ "</section>"
'<aside class="summary"><h2>Suite total</h2>'
f'<div class="summary__row"><span>{len(package["members"])} items at list</span>'
f'<strong>{cents(package["list_total_cents"])}</strong></div>'
f'<div class="summary__row"><span>Suite savings</span>'
f'<strong>-{cents(package["discount_cents"])}</strong></div>'
'<div class="summary__row summary__row--total"><span>Suite price</span>'
f'<strong>{cents(package["package_total_cents"])}</strong></div>'
'<form action="/cart/add" method="post">'
+ hidden_ids
+ '<input type="hidden" name="fulfillment" value="delivery">'
'<button class="button button--primary button--block" type="submit">'
"Add all four to cart</button></form>"
'<p class="results-head__count">The suite discount is a local display rule; '
"each cart line is recorded at its own catalog price.</p>"
"</aside></div>"
+ action_row(
(
("Shop appliances", "/c/Appliances"),
("Installation services", "/l/install"),
("Delivery details", "/l/help/shipping-delivery"),
)
)
+ "</main>"
)
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'<option value="{escape(value, quote=True)}"'
+ (" selected" if value == selected else "")
+ f">{escape(text)}</option>"
for value, text in options
)
return (
f'<label class="field"><span class="field__label">{escape(label)}</span>'
f'<select class="field__control" name="{name}">{choices}</select></label>'
)
@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 = (
'<main class="shell section configure-page">'
+ breadcrumb_bar(
[
("Home", "/"),
("Window Treatments", "/c/Window-treatments-Home-decor"),
(quote["display_title"], None),
]
)
+ '<p class="results-head__count">Made to Measure · Item # '
+ escape(item_id)
+ "</p>"
+ f'<h1 class="page-title">Configure: {escape(quote["display_title"])}</h1>'
+ '<p class="landing-intro">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.</p>"
+ sandbox_notice(SYNTHETIC_COMMERCE_NOTE)
+ '<div class="cart-layout"><section>'
f'<form class="configure-form" method="get" action="{escape(action, quote=True)}">'
+ 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"])
+ '<button class="button button--primary" type="submit">Update quote</button>'
"</form>"
f'<div class="configure-preview"><img src="{catalog_art(int(product["id"]), "detail")}" '
f'width="320" height="320" alt="{escape(quote["display_title"], quote=True)}"></div>'
"</section>"
'<aside class="summary"><h2>Your configuration</h2>'
+ "".join(
f'<div class="summary__row"><span>{escape(label)}</span><span>{escape(value)}</span></div>'
for label, value in (
("Size", f'{quote["width"]} in × {quote["height"]} in'),
("Area", f'{quote["square_feet"]} sq ft'),
("Mount", quote["labels"]["mount"]),
("Lift", quote["labels"]["control"]),
("Opacity", quote["labels"]["opacity"]),
("Colour", quote["labels"]["color"]),
)
)
+ f'<div class="summary__row"><span>Base</span><span>{cents(quote["base_cents"])}</span></div>'
f'<div class="summary__row"><span>Oversize</span><span>{cents(quote["size_cents"])}</span></div>'
f'<div class="summary__row"><span>Lift upgrade</span><span>{cents(quote["control_cents"])}</span></div>'
'<div class="summary__row summary__row--total"><span>Configured quote</span>'
f'<strong>{cents(quote["unit_cents"])}</strong></div>'
'<form action="/cart/add" method="post">'
f'<input type="hidden" name="product_id" value="{int(product["id"])}">'
'<input type="hidden" name="fulfillment" value="delivery">'
'<button class="button button--primary button--block" type="submit">'
"Add the base item to cart</button></form>"
'<p class="results-head__count">Truthful-simulation boundary: the local '
"cart records the base catalog item at "
f"{cents(quote['base_cents'])}. The configured quote above is computed "
"for display and is not stored as a cart line, because this clone's cart "
"schema holds no configuration.</p>"
"</aside></div>"
+ action_row(
(
("Special orders", "/l/help/special-orders"),
("Installation services", "/l/install"),
("Shop window treatments", "/c/Window-treatments-Home-decor"),
)
)
+ "</main>"
)
return render(
request, f"Configure {quote['display_title']} | Lowe's", body
)
# ---------------------------------------------------------------------------
# not found
# ---------------------------------------------------------------------------
def not_found(request: Request, path: str) -> HTMLResponse:
body = (
'<main class="shell section empty-state"><h1>Page not found</h1>'
f"<p>Nothing is served at <code>{escape(path)}</code> in this offline "
"clone.</p>"
'<p><a class="button button--primary" href="/">Back to home</a> '
'<a class="button button--outline" href="/c/Departments">Shop all departments</a></p>'
"</main>"
)
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)