AgPerry's picture
Add files using upload-large-folder tool
489b6e2 verified
Raw History Blame Contribute Delete
44.8 kB
"""Page bodies for the Lowe's offline clone.
Home-page structure follows the captured desktop screenshot top to bottom:
promotion strip, masthead, category nav, "Recommended Searches for You" chips,
the dark promotional hero with its brand row and savings table, the
"Members Get More" strip, then the deal cards. Everything below that fold, and
every route other than ``/`` and the account drawer, is clone-authored around
the synthetic catalog; ``scope/claims.jsonl`` records which is which.
"""
from __future__ import annotations
from typing import Any, Mapping, Sequence
from urllib.parse import urlencode
from backend import store as site_store
from ui.icons import icon
from ui.layout import Chrome, attr, esc
STAR_FULL = "★"
STAR_EMPTY = "☆"
# ---------------------------------------------------------------------------
# small components
# ---------------------------------------------------------------------------
def image_url(product: Mapping[str, Any], view: str = "front") -> str:
return f"/img/p/{product['id']}/{view}.svg"
def price_block(product: Mapping[str, Any]) -> str:
dollars, cents = site_store.money_parts(int(product["price_cents"]))
was = product.get("was_cents")
extra = ""
if was:
saved = int(was) - int(product["price_cents"])
extra = (
f'<span class="price__was">was ${esc(site_store.money(int(was)))}</span>'
f'<span class="price__save">Save ${esc(site_store.money(saved))}</span>'
)
return (
'<div class="price">'
f'<span class="price__amount">${esc(dollars)}<sup>{esc(cents)}</sup></span>'
f"{extra}</div>"
)
def rating_block(product: Mapping[str, Any]) -> str:
rating = float(product["rating"])
filled = int(rating + 0.5)
stars = STAR_FULL * filled + STAR_EMPTY * (5 - filled)
average = "{:.1f}".format(rating)
reviews = "{:,}".format(int(product["review_count"]))
return (
'<span class="rating">'
f'<span class="rating__stars" aria-hidden="true">{esc(stars)}</span>'
f"<span>{esc(average)} ({esc(reviews)} reviews)</span>"
"</span>"
)
def fulfillment_block(product: Mapping[str, Any], store_name: str) -> str:
pickup = (
f"<span><strong>Free pickup</strong> today at {esc(store_name)}</span>"
if product["pickup_today"]
else "<span>Not available for store pickup</span>"
)
delivery = (
f"<span><strong>Free delivery</strong> in {esc(product['delivery_days'])} days</span>"
if product["free_delivery"]
else f"<span>Delivery in {esc(product['delivery_days'])} days</span>"
)
return f'<div class="fulfillment">{pickup}{delivery}</div>'
def product_card(product: Mapping[str, Any], store_name: str) -> str:
flag = ""
if product.get("badge"):
flag = (
'<span class="product-card__flag" aria-hidden="true"></span>'
f'<span class="product-card__flag-text">{esc(product["badge"])}</span>'
)
return (
'<article class="product-card">'
f"{flag}"
f'<a class="product-card__media" href="{attr(product["url"])}">'
f'<img src="{attr(image_url(product))}" width="320" height="320" loading="lazy"'
f' alt="{attr(product["title"])}"></a>'
'<div class="product-card__body">'
f'<span class="product-card__brand">{esc(product["brand"])}</span>'
f'<a class="product-card__title" href="{attr(product["url"])}">'
f'{esc(product["title"])}</a>'
+ price_block(product)
+ rating_block(product)
+ fulfillment_block(product, store_name)
+ "</div></article>"
)
def card_grid(products: Sequence[Mapping[str, Any]], store_name: str) -> str:
return (
'<div class="card-grid">'
+ "".join(product_card(product, store_name) for product in products)
+ "</div>"
)
def breadcrumbs(trail: Sequence[tuple[str, str | None]]) -> str:
parts: list[str] = []
for label, href in trail:
if href:
parts.append(f'<a href="{attr(href)}">{esc(label)}</a>')
else:
parts.append(f"<span>{esc(label)}</span>")
return '<nav class="breadcrumbs shell" aria-label="Breadcrumb">' + " / ".join(parts) + "</nav>"
def _query_string(base: Mapping[str, Any], **overrides: Any) -> str:
merged: list[tuple[str, str]] = []
for key, value in base.items():
if key in overrides:
continue
if isinstance(value, (list, tuple)):
merged.extend((key, str(item)) for item in value)
elif value not in (None, "", False):
merged.append((key, str(value)))
for key, value in overrides.items():
if isinstance(value, (list, tuple)):
merged.extend((key, str(item)) for item in value)
elif value not in (None, "", False):
merged.append((key, str(value)))
return urlencode(merged)
# ---------------------------------------------------------------------------
# home
# ---------------------------------------------------------------------------
def home(
chrome: Chrome,
*,
recommended: Sequence[str],
deals: Sequence[Mapping[str, Any]],
top_sellers: Sequence[Mapping[str, Any]],
) -> str:
store_name = (chrome.store or {}).get("name", "your store")
chips = "".join(
f'<a class="chip" href="/search?q={attr(term.replace(" ", "+"))}">{esc(term)}</a>'
for term in recommended
)
return (
'<section class="section shell">'
'<div class="section__head">'
'<h2 class="section__title">Recommended Searches for You</h2>'
'<a class="section__more" href="/departments">More Suggestions for You '
+ icon("chevron", 14)
+ "</a>"
"</div>"
f'<div class="chip-row">{chips}</div>'
"</section>"
+ hero_section()
+ '<section class="section shell">'
'<div class="section__head">'
'<h2 class="section__title">Appliance Special Values</h2>'
'<a class="section__more" href="/search?sort=savings">Shop all deals '
+ icon("chevron", 14)
+ "</a></div>"
+ card_grid(deals, store_name)
+ "</section>"
'<section class="section shell">'
'<div class="section__head">'
'<h2 class="section__title">Top Sellers in Your Area</h2>'
'<a class="section__more" href="/search?sort=top-sellers">Shop top sellers '
+ icon("chevron", 14)
+ "</a></div>"
+ card_grid(top_sellers, store_name)
+ "</section>"
+ services_section()
)
def hero_section() -> str:
brands = "".join(
f"<span>{esc(name)}</span>"
for name in (
"Electrolux",
"Frigidaire",
"Frigidaire Gallery",
"Frigidaire Professional",
)
)
return (
'<section class="section shell"><div class="hero">'
'<h2 class="hero__title">Electrolux End-of-Summer Sale</h2>'
f'<div class="hero__brands">{brands}</div>'
'<div class="hero__panel">'
"<div>"
'<p class="hero__eyebrow">Frigidaire</p>'
'<p class="hero__save">Save up to</p>'
'<p class="hero__amount"><sup>$</sup>300</p>'
'<p class="hero__copy">When you bundle select Frigidaire major appliances.</p>'
'<table class="hero__table">'
"<thead><tr><th>Save</th><th>When You Buy</th></tr></thead>"
"<tbody>"
"<tr><td>$100</td><td>2</td></tr>"
"<tr><td>$200</td><td>3</td></tr>"
"<tr><td>$300</td><td>4 or More</td></tr>"
"</tbody></table>"
'<a class="button button--light" href="/search?category=appliances">Shop Now</a>'
"</div>"
'<div class="hero__art">'
'<img src="/static/site/img/hero-appliances.svg" width="720" height="340"'
' alt="Illustrated kitchen with a range, refrigerator and island">'
"</div>"
"</div>"
'<div class="members">'
"<strong>myLowe&#8217;s Rewards</strong>"
"<span><strong>Members Get More</strong> when you spend $1,799 or more on "
"select Frigidaire and Electrolux major appliances.</span>"
"<span><strong>FREE</strong> Delivery and Haul Away</span>"
"<span><strong>FREE</strong> Basic Installation and Installation Parts</span>"
"<span>2-Year Lowe&#8217;s Protection Plan</span>"
"</div>"
"</div></section>"
)
SERVICES: tuple[tuple[str, str, str, str], ...] = (
(
"tools",
"Installation Services",
"Book a local installer for appliances, flooring, windows and more.",
"/services/installation",
),
(
"truck",
"Delivery & Haul Away",
"Schedule delivery to your ZIP code and have the old unit taken away.",
"/help/delivery",
),
(
"store",
"Store Pickup",
"Buy online and pick up at the store you selected in the header.",
"/help/pickup",
),
(
"points",
"myLowe's Rewards",
"Earn points on eligible purchases and get member-only offers.",
"/rewards",
),
)
def services_section() -> str:
cards = "".join(
'<article class="service-card">'
+ icon(glyph, 26)
+ f"<h3>{esc(title)}</h3><p>{esc(copy)}</p>"
f'<a class="button button--outline" href="{attr(href)}">Learn more</a>'
"</article>"
for glyph, title, copy, href in SERVICES
)
return (
'<section class="section shell">'
'<div class="section__head"><h2 class="section__title">How We Can Help</h2></div>'
f'<div class="service-grid">{cards}</div>'
"</section>"
)
# ---------------------------------------------------------------------------
# search results
# ---------------------------------------------------------------------------
def search_results(
chrome: Chrome,
*,
result: Mapping[str, Any],
params: Mapping[str, Any],
categories: Sequence[Mapping[str, Any]],
brands: Sequence[str],
) -> str:
store_name = (chrome.store or {}).get("name", "your store")
heading = (
f'Results for "{result["query"]}"' if result["query"] else "Shop all products"
)
label_by_id = {str(row["id"]): str(row["label"]) for row in categories}
applied: list[str] = []
for category_id in params.get("category", []):
applied.append(
'<a class="applied-filters__chip" href="/search?'
f'{attr(_query_string(params, category=[c for c in params.get("category", []) if c != category_id], page=1))}">'
f'{esc(label_by_id.get(category_id, category_id))} {icon("close", 12)}</a>'
)
for brand in params.get("brand", []):
applied.append(
'<a class="applied-filters__chip" href="/search?'
f'{attr(_query_string(params, brand=[b for b in params.get("brand", []) if b != brand], page=1))}">'
f'{esc(brand)} {icon("close", 12)}</a>'
)
if params.get("min_price") or params.get("max_price"):
applied.append(
'<a class="applied-filters__chip" href="/search?'
f'{attr(_query_string(params, min_price="", max_price="", page=1))}">'
f'${esc(params.get("min_price") or "0")}&ndash;${esc(params.get("max_price") or "any")} '
f'{icon("close", 12)}</a>'
)
if params.get("rating"):
applied.append(
'<a class="applied-filters__chip" href="/search?'
f'{attr(_query_string(params, rating="", page=1))}">'
f'{esc(params["rating"])}+ stars {icon("close", 12)}</a>'
)
for flag, label in (("pickup", "Pickup today"), ("free_delivery", "Free delivery")):
if params.get(flag):
applied.append(
'<a class="applied-filters__chip" href="/search?'
f'{attr(_query_string(params, **{flag: "", "page": 1}))}">'
f'{esc(label)} {icon("close", 12)}</a>'
)
applied_html = (
f'<div class="applied-filters">{"".join(applied)}'
'<a class="applied-filters__chip" href="/search?'
f'{attr(_query_string({"q": params.get("q", ""), "sort": params.get("sort", "relevance")}))}">'
"Clear all</a></div>"
if applied
else ""
)
sort_options = "".join(
f'<option value="{attr(key)}"'
+ (" selected" if params.get("sort", "relevance") == key else "")
+ f">{esc(label)}</option>"
for key, label in site_store.SORT_OPTIONS
)
body = (
card_grid(result["products"], store_name)
if result["products"]
else (
'<div class="empty-state"><p><strong>No results.</strong></p>'
"<p>Try fewer filters or a different search term. This offline clone "
"carries a fixed synthetic catalog, so it will not match every real "
"Lowe&#8217;s product.</p>"
'<p><a class="button button--outline" href="/search">Browse everything</a></p>'
"</div>"
)
)
return (
breadcrumbs([("Home", "/"), ("Search results", None)])
+ '<div class="shell">'
f'<h1 class="page-title">{esc(heading)}</h1>'
'<div class="results-layout">'
+ _filters_form(params, categories, brands, result)
+ "<section>"
+ applied_html
+ '<div class="results-head">'
'<p class="results-head__count">'
+ (
f'Showing {esc(result["first_index"])}&ndash;{esc(result["last_index"])} of '
f'{esc(result["total"])} results'
if result["total"]
else "0 results"
)
+ "</p>"
'<form method="get" action="/search">'
+ _hidden_params(params, drop={"sort", "page"})
+ '<label class="visually-hidden" for="sort-select">Sort by</label>'
'<select class="field__control" id="sort-select" name="sort" data-autosubmit>'
+ sort_options
+ "</select>"
'<button class="visually-hidden" type="submit">Sort</button>'
"</form>"
"</div>"
+ body
+ _pagination(result, params)
+ "</section></div></div>"
)
def _hidden_params(params: Mapping[str, Any], *, drop: set[str]) -> str:
fields: list[str] = []
for key, value in params.items():
if key in drop:
continue
values = value if isinstance(value, (list, tuple)) else [value]
for item in values:
if item in (None, "", False):
continue
fields.append(
f'<input type="hidden" name="{attr(key)}" value="{attr(item)}">'
)
return "".join(fields)
def _filters_form(
params: Mapping[str, Any],
categories: Sequence[Mapping[str, Any]],
brands: Sequence[str],
result: Mapping[str, Any],
) -> str:
selected_categories = set(params.get("category", []))
selected_brands = set(params.get("brand", []))
facet_categories = result["facet_categories"]
facet_brands = result["facet_brands"]
category_options = "".join(
'<label class="filters__option"><input type="checkbox" name="category"'
f' value="{attr(row["id"])}"'
+ (" checked" if str(row["id"]) in selected_categories else "")
+ f'><span>{esc(row["label"])}</span>'
+ (
f'<span class="results-head__count">({esc(facet_categories.get(str(row["id"]), 0))})</span>'
if facet_categories.get(str(row["id"]))
else ""
)
+ "</label>"
for row in categories
)
brand_options = "".join(
'<label class="filters__option"><input type="checkbox" name="brand"'
f' value="{attr(name)}"'
+ (" checked" if name in selected_brands else "")
+ f'><span>{esc(name)}</span>'
+ (
f'<span class="results-head__count">({esc(facet_brands.get(name, 0))})</span>'
if facet_brands.get(name)
else ""
)
+ "</label>"
for name in brands
)
rating_options = "".join(
'<label class="filters__option"><input type="radio" name="rating"'
f' value="{attr(value)}"'
+ (" checked" if str(params.get("rating", "")) == value else "")
+ f'><span>{esc(value)} stars &amp; up</span></label>'
for value in ("4.5", "4", "3")
)
return (
'<form class="filters" method="get" action="/search">'
f'<input type="hidden" name="q" value="{attr(params.get("q", ""))}">'
f'<input type="hidden" name="sort" value="{attr(params.get("sort", "relevance"))}">'
'<fieldset class="filters__group">'
'<legend class="filters__legend">Department</legend>'
+ category_options
+ "</fieldset>"
'<fieldset class="filters__group">'
'<legend class="filters__legend">Brand</legend>'
+ brand_options
+ "</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="{attr(params.get("min_price", ""))}" 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="{attr(params.get("max_price", ""))}" 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 params.get("pickup") else "")
+ "><span>Pickup today</span></label>"
'<label class="filters__option"><input type="checkbox" name="free_delivery"'
' value="1"'
+ (" checked" if params.get("free_delivery") else "")
+ "><span>Free delivery</span></label>"
"</fieldset>"
'<button class="button button--primary button--block" type="submit">'
"Apply filters</button>"
"</form>"
)
def _pagination(result: Mapping[str, Any], params: Mapping[str, Any]) -> str:
if result["page_count"] <= 1:
return ""
links: list[str] = []
if result["page"] > 1:
links.append(
'<a class="pagination__link" rel="prev" href="/search?'
f'{attr(_query_string(params, page=result["page"] - 1))}">Previous</a>'
)
for number in range(1, int(result["page_count"]) + 1):
current = ' aria-current="page"' if number == result["page"] else ""
links.append(
f'<a class="pagination__link"{current} href="/search?'
f'{attr(_query_string(params, page=number))}">{esc(number)}</a>'
)
if result["page"] < result["page_count"]:
links.append(
'<a class="pagination__link" rel="next" href="/search?'
f'{attr(_query_string(params, page=result["page"] + 1))}">Next</a>'
)
return (
'<nav class="pagination" aria-label="Search result pages">'
+ "".join(links)
+ "</nav>"
)
# ---------------------------------------------------------------------------
# product detail
# ---------------------------------------------------------------------------
def product_detail(
chrome: Chrome,
*,
product: Mapping[str, Any],
category_label: str,
related: Sequence[Mapping[str, Any]],
message: str = "",
error: str = "",
) -> str:
store_name = (chrome.store or {}).get("name", "your store")
thumbs = "".join(
f'<button class="pdp__thumb" type="button" aria-current="{"true" if index == 0 else "false"}"'
f' data-gallery-thumb="{attr(image_url(product, view))}"'
f' data-gallery-alt="{attr(product["title"])} ({esc(view)} view)">'
f'<img src="{attr(image_url(product, view))}" width="80" height="80"'
f' alt="{attr(product["title"])} {esc(view)} view"></button>'
for index, view in enumerate(("front", "angle", "detail"))
)
specs = "".join(
f"<tr><th scope=\"row\">{esc(name)}</th><td>{esc(value)}</td></tr>"
for name, value in product["specs"]
)
notices = ""
if message:
notices += f'<p class="notice">{esc(message)}</p>'
if error:
notices += f'<p class="notice notice--error">{esc(error)}</p>'
pickup_disabled = "" if product["pickup_today"] else " disabled"
pickup_note = (
f"Free pickup today at {store_name}"
if product["pickup_today"]
else "Not available for pickup"
)
return (
breadcrumbs(
[
("Home", "/"),
(category_label, f"/search?category={product['category_id']}"),
(product["title"], None),
]
)
+ '<div class="shell section">'
+ notices
+ '<div class="pdp">'
f'<div class="pdp__thumbs">{thumbs}</div>'
'<div class="pdp__stage">'
f'<img src="{attr(image_url(product))}" width="320" height="320"'
f' alt="{attr(product["title"])}" data-gallery-stage>'
"</div>"
'<div class="pdp__buybox">'
f'<p class="product-card__brand">{esc(product["brand"])}</p>'
f'<h1 class="pdp__title">{esc(product["title"])}</h1>'
+ rating_block(product)
+ price_block(product)
+ f"<p>{esc(product['summary'])}</p>"
f'<p class="results-head__count">Model # {esc(product["model_number"])} '
f'&middot; Item # {esc(product["id"])}</p>'
'<form method="post" action="/cart/add">'
f'<input type="hidden" name="product_id" value="{attr(product["id"])}">'
f'<input type="hidden" name="next" value="{attr(product["url"])}">'
'<div class="fulfillment-choice">'
'<label><span><input type="radio" name="fulfillment" value="pickup"'
+ (" checked" if product["pickup_today"] else "")
+ pickup_disabled
+ ">Pickup</span>"
f"<span>{esc(pickup_note)}</span></label>"
'<label><span><input type="radio" name="fulfillment" value="delivery"'
+ ("" if product["pickup_today"] else " checked")
+ ">Delivery</span>"
f'<span>{esc("Free" if product["free_delivery"] else "Fee applies")} in '
f'{esc(product["delivery_days"])} days to {esc(chrome.postal_code)}</span></label>'
"</div>"
'<div class="cart-line__actions">'
'<div class="quantity" data-quantity>'
'<button type="button" data-quantity-step="-1" aria-label="Decrease quantity">'
"&minus;</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" type="submit">Add to Cart</button>'
"</div></form>"
+ fulfillment_block(product, store_name)
+ f'<p class="results-head__count">{esc(product["stock"])} in stock at this '
"location in the clone&#8217;s synthetic inventory.</p>"
"</div></div>"
'<section class="section">'
"<h2 class=\"section__title\">Specifications</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>" + card_grid(related, store_name) + "</section>"
if related
else ""
)
+ "</div>"
)
# ---------------------------------------------------------------------------
# cart
# ---------------------------------------------------------------------------
def cart_page(
chrome: Chrome,
*,
cart: Mapping[str, Any],
totals: Mapping[str, Any],
message: str = "",
error: str = "",
) -> str:
if not cart["items"]:
return (
breadcrumbs([("Home", "/"), ("Cart", None)])
+ '<div class="shell section">'
'<h1 class="page-title">Your cart is empty</h1>'
'<div class="empty-state"><p>Nothing has been added yet.</p>'
'<p><a class="button button--primary" href="/search?sort=top-sellers">'
"Shop top sellers</a></p></div></div>"
)
lines = "".join(_cart_line(item) for item in cart["items"])
notices = ""
if message:
notices += f'<p class="notice">{esc(message)}</p>'
if error:
notices += f'<p class="notice notice--error">{esc(error)}</p>'
return (
breadcrumbs([("Home", "/"), ("Cart", None)])
+ '<div class="shell section">'
f'<h1 class="page-title">Cart ({esc(cart["units"])} '
f'{esc("item" if cart["units"] == 1 else "items")})</h1>'
+ notices
+ '<div class="cart-layout"><section>'
+ lines
+ "</section>"
+ summary_panel(totals, cart, action="/checkout", action_label="Proceed to Checkout")
+ "</div></div>"
)
def _cart_line(item: Mapping[str, Any]) -> str:
art = "/img/p/{}/front.svg".format(int(item["product_id"]))
return (
'<article class="cart-line">'
'<div class="cart-line__media">'
f'<img src="{attr(art)}" width="320"'
f' height="320" alt="{attr(item["title"])}"></div>'
"<div>"
f'<p class="product-card__brand">{esc(item["brand"])}</p>'
f'<a class="product-card__title" href="{attr(item["url"])}">{esc(item["title"])}</a>'
'<div class="cart-line__actions">'
'<form method="post" action="/cart/update">'
f'<input type="hidden" name="item_id" value="{attr(item["item_id"])}">'
'<div class="quantity" data-quantity>'
'<button type="button" data-quantity-step="-1" aria-label="Decrease quantity">'
"&minus;</button>"
f'<label class="visually-hidden" for="qty-{attr(item["item_id"])}">Quantity for '
f'{esc(item["title"])}</label>'
f'<input id="qty-{attr(item["item_id"])}" type="number" name="quantity"'
f' value="{attr(item["quantity"])}" min="0" max="99" step="1">'
'<button type="button" data-quantity-step="1" aria-label="Increase quantity">'
"+</button></div>"
'<button class="button button--outline" type="submit">Update</button>'
"</form>"
'<form method="post" action="/cart/remove">'
f'<input type="hidden" name="item_id" value="{attr(item["item_id"])}">'
'<button class="link-button" type="submit">Remove</button>'
"</form>"
'<form method="post" action="/cart/fulfillment">'
f'<input type="hidden" name="item_id" value="{attr(item["item_id"])}">'
'<input type="hidden" name="fulfillment" value="'
+ ("delivery" if item["fulfillment"] == "pickup" else "pickup")
+ '">'
'<button class="link-button" type="submit">Switch to '
+ esc("delivery" if item["fulfillment"] == "pickup" else "pickup")
+ "</button></form>"
"</div>"
'<p class="fulfillment"><span><strong>'
+ esc("Store pickup" if item["fulfillment"] == "pickup" else "Delivery")
+ "</strong></span></p>"
"</div>"
'<div class="cart-line__price">'
f'<span class="price__amount">${esc(site_store.money(int(item["line_total_cents"])))}</span>'
"</div>"
"</article>"
)
def summary_panel(
totals: Mapping[str, Any],
cart: Mapping[str, Any],
*,
action: str | None = None,
action_label: str = "",
submit: bool = False,
) -> str:
rows = [
("Subtotal", f"${site_store.money(int(totals['subtotal_cents']))}"),
(
"Savings",
f"-${site_store.money(int(totals['savings_cents']))}"
if totals["savings_cents"]
else "$0.00",
),
(
"Delivery",
"FREE"
if totals["delivery_cents"] == 0
else f"${site_store.money(int(totals['delivery_cents']))}",
),
("Estimated tax", f"${site_store.money(int(totals['tax_cents']))}"),
]
row_html = "".join(
f'<div class="summary__row"><span>{esc(label)}</span><span>{esc(value)}</span></div>'
for label, value in rows
)
cta = ""
if action and not submit:
cta = (
f'<a class="button button--primary button--block" href="{attr(action)}">'
f"{esc(action_label)}</a>"
)
elif submit:
cta = (
'<button class="button button--primary button--block" type="submit">'
f"{esc(action_label)}</button>"
)
return (
'<aside class="summary">'
'<h2 class="section__title">Order Summary</h2>'
f'<div class="summary__row"><span>{esc(cart["units"])} items</span>'
f'<span>{esc(cart["count"])} lines</span></div>'
+ row_html
+ '<div class="summary__row summary__row--total"><span>Total</span>'
f'<span>${esc(site_store.money(int(totals["total_cents"])))}</span></div>'
+ cta
+ "</aside>"
)
# ---------------------------------------------------------------------------
# checkout
# ---------------------------------------------------------------------------
def checkout_page(
chrome: Chrome,
*,
cart: Mapping[str, Any],
totals: Mapping[str, Any],
form: Mapping[str, Any],
errors: Mapping[str, str],
scenarios: Sequence[Mapping[str, str]],
payment: Mapping[str, Any] | None = None,
) -> str:
fulfillment = str(form.get("fulfillment", "pickup"))
store_options = "".join(
f'<option value="{attr(item["id"])}"'
+ (" selected" if form.get("store_id") == item["id"] else "")
+ f'>{esc(item["name"])} &middot; {esc(item["city"])}, {esc(item["state"])}</option>'
for item in chrome.stores
)
scenario_inputs = "".join(
'<label class="filters__option">'
f'<input type="radio" name="scenario_id" value="{attr(item["id"])}"'
+ (" checked" if form.get("scenario_id") == item["id"] else "")
+ f'><span>{esc(item["display_label"])}</span>'
f'<span class="tag tag--{attr(item["outcome"])}">{esc(item["outcome"])}</span>'
"</label>"
for item in scenarios
)
payment_notice = ""
if payment:
status = str(payment["status"])
wording = {
"DECLINED": "The local sandbox declined this simulated payment. Nothing "
"was charged and your cart is unchanged. Pick another scenario to retry.",
"RETRYABLE": "The local sandbox returned a retryable result. Nothing was "
"charged and your cart is unchanged. Submit again to retry.",
}.get(status, "The local sandbox returned an unexpected result.")
payment_notice = (
'<p class="notice notice--error"><span class="tag tag--'
+ attr(status.casefold())
+ f'">{esc(status)}</span> {esc(wording)}</p>'
)
error_summary = ""
if errors:
error_summary = (
'<p class="notice notice--error">Check the highlighted fields below.</p>'
)
def field_error(name: str) -> str:
return (
f'<span class="field__error">{esc(errors[name])}</span>'
if name in errors
else ""
)
return (
breadcrumbs([("Home", "/"), ("Cart", "/cart"), ("Checkout", None)])
+ '<div class="shell section">'
'<h1 class="page-title">Checkout</h1>'
'<ol class="steps">'
'<li>Cart</li>'
'<li aria-current="step">Fulfillment &amp; payment</li>'
"<li>Confirmation</li></ol>"
+ error_summary
+ payment_notice
+ '<form method="post" action="/checkout">'
'<div class="checkout-layout"><section>'
'<fieldset class="filters__group">'
'<legend class="filters__legend">How do you want it?</legend>'
'<label class="filters__option"><input type="radio" name="fulfillment"'
' value="pickup"'
+ (" checked" if fulfillment == "pickup" else "")
+ "><span>Store pickup (free)</span></label>"
'<label class="filters__option"><input type="radio" name="fulfillment"'
' value="delivery"'
+ (" checked" if fulfillment == "delivery" else "")
+ "><span>Delivery to an address</span></label>"
+ field_error("fulfillment")
+ '<label class="field" for="checkout-store">'
'<span class="field__label">Pickup store</span>'
'<select class="field__control" id="checkout-store" name="store_id">'
+ store_options
+ "</select></label>"
+ field_error("store_id")
+ "</fieldset>"
'<fieldset class="filters__group">'
'<legend class="filters__legend">Contact</legend>'
+ _text_field("first_name", "First name", form, errors, "given-name")
+ _text_field("last_name", "Last name", form, errors, "family-name")
+ _text_field("email", "Email", form, errors, "email", kind="email")
+ "</fieldset>"
'<fieldset class="filters__group">'
'<legend class="filters__legend">Delivery address</legend>'
'<p class="results-head__count">Required only when delivery is selected.</p>'
+ _text_field("address_1", "Street address", form, errors, "address-line1")
+ _text_field(
"address_2", "Apartment, suite (optional)", form, errors, "address-line2"
)
+ _text_field("city", "City", form, errors, "address-level2")
+ _text_field("state", "State (2 letters)", form, errors, "address-level1")
+ _text_field("zip", "ZIP code", form, errors, "postal-code")
+ "</fieldset>"
'<fieldset class="filters__group">'
'<legend class="filters__legend">Local sandbox payment</legend>'
'<p class="notice notice--sandbox"><strong>Local sandbox only.</strong> This '
"clone never accepts a card number, CVV, expiry, bank or wallet credential. "
"Choose one deterministic outcome below; the amount, currency and order "
"fingerprint are computed on the server from your saved cart.</p>"
+ scenario_inputs
+ field_error("scenario_id")
+ "</fieldset>"
+ field_error("cart")
+ "</section>"
+ summary_panel(totals, cart, action_label="Place order", submit=True)
+ "</div></form></div>"
)
def _text_field(
name: str,
label: str,
form: Mapping[str, Any],
errors: Mapping[str, str],
autocomplete: str,
*,
kind: str = "text",
) -> str:
error = (
f'<span class="field__error">{esc(errors[name])}</span>' if name in errors else ""
)
return (
f'<label class="field" for="checkout-{attr(name)}">'
f'<span class="field__label">{esc(label)}</span>'
f'<input class="field__control" id="checkout-{attr(name)}" type="{attr(kind)}"'
f' name="{attr(name)}" value="{attr(form.get(name, ""))}"'
f' autocomplete="{attr(autocomplete)}"></label>{error}'
)
# ---------------------------------------------------------------------------
# order confirmation + account
# ---------------------------------------------------------------------------
def _order_line(item: Mapping[str, Any]) -> str:
art = "/img/p/{}/front.svg".format(int(item["product_id"]))
return (
'<article class="cart-line">'
f'<div class="cart-line__media"><img src="{attr(art)}"'
f' width="320" height="320" alt="{attr(item["title"])}"></div>'
f'<div><p class="product-card__brand">{esc(item["brand"])}</p>'
f'<a class="product-card__title" href="/pd/{attr(item["slug"])}/{attr(item["product_id"])}">'
f'{esc(item["title"])}</a>'
f'<p class="fulfillment"><span>Qty {esc(item["quantity"])} &middot; '
+ esc("Store pickup" if item["fulfillment"] == "pickup" else "Delivery")
+ "</span></p></div>"
f'<div class="cart-line__price"><span class="price__amount">'
f'${esc(site_store.money(int(item["line_total_cents"])))}</span></div>'
"</article>"
)
def order_confirmation(order: Mapping[str, Any]) -> str:
items = "".join(_order_line(item) for item in order["items"])
if order["fulfillment"] == "pickup":
store = order.get("store") or {}
where = (
f"Pickup at {store.get('name', 'your store')}, {store.get('city', '')}, "
f"{store.get('state', '')}"
)
else:
address = order.get("address") or {}
where = (
f"Delivery to {address.get('address_1', '')}, {address.get('city', '')}, "
f"{address.get('state', '')} {address.get('zip', '')}"
)
mail = order.get("mail") or {}
return (
breadcrumbs([("Home", "/"), ("Orders", "/account/orders"), (order["order_number"], None)])
+ '<div class="shell section">'
'<div class="order-banner">'
f'<h1 class="page-title">Order {esc(order["order_number"])} is placed</h1>'
f'<p>{esc(where)}</p>'
f'<p><span class="tag tag--approved">payment {esc(order["payment_status"])}</span> '
f'<span class="tag">scenario {esc(order["scenario_id"])}</span> '
f'<span class="tag">mail {esc(mail.get("status", "none"))}</span></p>'
'<p class="results-head__count">Simulated locally. No payment was taken and '
"no message was delivered; the confirmation was written to this clone&#8217;s "
"local outbox with template variables only.</p>"
"</div>"
'<div class="cart-layout"><section>'
+ items
+ "</section>"
+ summary_panel(
{
"subtotal_cents": order["subtotal_cents"],
"savings_cents": order["savings_cents"],
"delivery_cents": order["delivery_cents"],
"tax_cents": order["tax_cents"],
"total_cents": order["total_cents"],
},
{
"units": sum(int(item["quantity"]) for item in order["items"]),
"count": len(order["items"]),
},
action="/search?sort=top-sellers",
action_label="Keep shopping",
)
+ "</div></div>"
)
def account_page(
chrome: Chrome, *, account: Mapping[str, Any], orders: Sequence[Mapping[str, Any]]
) -> str:
order_rows = "".join(
"<tr>"
f'<th scope="row"><a href="/orders/{attr(order["order_number"])}">'
f'{esc(order["order_number"])}</a></th>'
f'<td>{esc(order["fulfillment"])}</td>'
f'<td>{esc(len(order["items"]))} items</td>'
f'<td>${esc(site_store.money(int(order["total_cents"])))}</td>'
f'<td><span class="tag tag--approved">{esc(order["payment_status"])}</span></td>'
"</tr>"
for order in orders
)
table = (
'<table class="spec-table"><thead><tr><th>Order</th><th>Fulfillment</th>'
"<th>Items</th><th>Total</th><th>Payment</th></tr></thead>"
f"<tbody>{order_rows}</tbody></table>"
if orders
else '<div class="empty-state"><p>No orders in this clone yet.</p></div>'
)
return (
breadcrumbs([("Home", "/"), ("Account", None)])
+ '<div class="shell section">'
f'<h1 class="page-title">Hi, {esc(account.get("display_name", ""))}</h1>'
f'<p>Signed in as {esc(account.get("contact_display", ""))}.</p>'
'<section class="section"><h2 class="section__title">Order Status</h2>'
+ table
+ "</section>"
'<form method="post" action="/account/sign-out">'
'<button class="button button--outline" type="submit">Sign Out</button>'
"</form>"
"</div>"
)
def orders_page(chrome: Chrome, *, orders: Sequence[Mapping[str, Any]]) -> str:
if not orders:
return (
breadcrumbs([("Home", "/"), ("Order Status", None)])
+ '<div class="shell section"><h1 class="page-title">Order Status</h1>'
'<div class="empty-state"><p>This browser session has no orders yet.</p>'
'<p><a class="button button--outline" href="/cart">Go to your cart</a></p>'
"</div></div>"
)
rows = "".join(
"<tr>"
f'<th scope="row"><a href="/orders/{attr(order["order_number"])}">'
f'{esc(order["order_number"])}</a></th>'
f'<td>{esc(order["customer_name"])}</td>'
f'<td>{esc(order["fulfillment"])}</td>'
f'<td>${esc(site_store.money(int(order["total_cents"])))}</td>'
"</tr>"
for order in orders
)
return (
breadcrumbs([("Home", "/"), ("Order Status", None)])
+ '<div class="shell section"><h1 class="page-title">Order Status</h1>'
'<table class="spec-table"><thead><tr><th>Order</th><th>Name</th>'
"<th>Fulfillment</th><th>Total</th></tr></thead>"
f"<tbody>{rows}</tbody></table></div>"
)
# ---------------------------------------------------------------------------
# supporting pages
# ---------------------------------------------------------------------------
def departments_page(
chrome: Chrome, *, categories: Sequence[Mapping[str, Any]], counts: Mapping[str, int]
) -> str:
cards = "".join(
'<article class="service-card">'
+ icon("grid", 24)
+ f'<h3>{esc(row["label"])}</h3>'
f'<p>{esc(counts.get(str(row["id"]), 0))} products in this clone.</p>'
f'<a class="button button--outline" href="/search?category={attr(row["id"])}">'
"Shop department</a></article>"
for row in categories
)
return (
breadcrumbs([("Home", "/"), ("Shop All", None)])
+ '<div class="shell section"><h1 class="page-title">Shop All Departments</h1>'
f'<div class="service-grid">{cards}</div></div>'
)
def stores_page(chrome: Chrome, *, stores: Sequence[Mapping[str, Any]]) -> str:
cards = "".join(
'<article class="service-card">'
+ icon("store", 24)
+ f'<h3>{esc(row["name"])}</h3>'
f'<p>{esc(row["city"])}, {esc(row["state"])} {esc(row["zip"])}<br>'
f'Closes at {esc(row["closes_at"])}</p>'
'<form method="post" action="/preferences">'
f'<input type="hidden" name="store_id" value="{attr(row["id"])}">'
f'<input type="hidden" name="postal_code" value="{attr(row["zip"])}">'
'<input type="hidden" name="next" value="/stores">'
'<button class="button button--outline" type="submit">Make this my store</button>'
"</form></article>"
for row in stores
)
return (
breadcrumbs([("Home", "/"), ("Store Locator", None)])
+ '<div class="shell section"><h1 class="page-title">Store Locator</h1>'
'<p>Four synthetic stores back the pickup selector in this clone.</p>'
f'<div class="service-grid">{cards}</div></div>'
)
def info_page(chrome: Chrome, *, title: str, blocks: Sequence[str]) -> str:
body = "".join(f"<p>{esc(block)}</p>" for block in blocks)
return (
breadcrumbs([("Home", "/"), (title, None)])
+ f'<div class="shell section"><h1 class="page-title">{esc(title)}</h1>'
f"{body}</div>"
)
def external_boundary(chrome: Chrome, *, slug: str) -> str:
return (
breadcrumbs([("Home", "/"), ("External link", None)])
+ '<div class="shell section"><h1 class="page-title">External link boundary</h1>'
'<p class="notice">This offline clone does not open third-party or legal '
f"destinations. The source page linked to <strong>{esc(slug)}</strong>; no "
"remote request was made and nothing was fetched.</p>"
'<p><a class="button button--outline" href="/">Return to the home page</a></p>'
"</div>"
)
def not_found(chrome: Chrome, *, path: str) -> str:
return (
'<div class="shell section"><h1 class="page-title">We can&#8217;t find that page</h1>'
f"<p>Nothing is served at <code>{esc(path)}</code> in this offline clone.</p>"
'<p><a class="button button--primary" href="/">Back to the home page</a> '
'<a class="button button--outline" href="/departments">Shop all departments</a></p>'
"</div>"
)