from __future__ import annotations
import contextvars
import json
from html import escape
from pathlib import Path
from typing import Any, Iterable, Mapping
from urllib.parse import quote_plus, urlencode
from home_category_catalog import home_category_products, load_home_category_groups
from payment_methods import DEFAULT_PAYMENT_METHOD, public_payment_methods
from stripe_gateway import PAYMENT_MODE_STRIPE_TEST
from product_options import T7_SOURCE_OPTIONS, option_groups_from_detail
from review_catalog import render_reviews_section
from search_catalog import (
DEFAULT_SEARCH_DEPARTMENT,
SOURCE_DEPARTMENTS,
SOURCE_DEPARTMENT_BY_SLUG,
SearchPage,
SearchRequest,
normalize_search_query,
search_href,
source_department_for_query,
source_department_for_rail,
)
from store import (
BEST_SELLERS_PATH,
DEFAULT_DELIVERY_COUNTRY,
DESKTOP_TERMINAL_PATH,
MOBILE_TERMINAL_PATH,
PDP_PATH,
SUPPORTED_DELIVERY_COUNTRIES,
TARGET_ASIN,
)
# The storefront delivery location is per-browser-session state, but it is read
# by header/PDP/notice renderers that sit ~200 call sites below `layout()`.
# Threading it through every signature would be churn, so the request handler
# publishes it once per request and the renderers read it here. Each request is
# served on its own thread, and a thread starts from an empty context, so the
# default applies to anything rendered outside a request (tests, tooling).
_DELIVERY_COUNTRY: contextvars.ContextVar[tuple[str, str]] = contextvars.ContextVar(
"amazon_delivery_country", default=DEFAULT_DELIVERY_COUNTRY
)
_DELIVERY_TOKEN: contextvars.ContextVar[str] = contextvars.ContextVar(
"amazon_delivery_token", default=""
)
def set_delivery_context(country: tuple[str, str], token: str = "") -> None:
"""Publish the delivery location for everything rendered in this request."""
_DELIVERY_COUNTRY.set(country)
_DELIVERY_TOKEN.set(token)
def current_delivery_country() -> tuple[str, str]:
return _DELIVERY_COUNTRY.get()
def current_delivery_label() -> str:
return _DELIVERY_COUNTRY.get()[1]
def delivery_country_options(selected_code: str | None = None) -> str:
"""Render the storefront delivery option set.
The header picker, its no-JavaScript landing page and the JSON endpoint all
read this one function so the three surfaces cannot drift apart.
"""
code = (selected_code or current_delivery_country()[0]).upper()
return "".join(
f''
for country, label in SUPPORTED_DELIVERY_COUNTRIES
)
def delivery_location_picker(error: bool = False) -> str:
"""Header delivery-location dialog.
Progressive enhancement only: the trigger in `header()` is a real link to
DELIVERY_PREFERENCE_HREF, and this dialog posts a real form, so both the
no-JavaScript and the scripted path go through the same server route.
"""
status = (
"The address has not been updated. Choose a country/region and try again."
if error
else ""
)
return f"""
Choose your location
{escape(status)}
"""
SITE_NAME = "Amazon.com"
CUSTOMER_SERVICE_HREF = "/gp/help/customer/display.html?nodeId=508510"
SHIPPING_POLICIES_HREF = "/gp/help/customer/display.html?nodeId=468520"
RETURNS_REPLACEMENTS_HREF = "/gp/help/customer/display.html?nodeId=201819200"
CONDITIONS_OF_USE_HREF = "/gp/help/customer/display.html?nodeId=508088"
PRIVACY_NOTICE_HREF = "/gp/help/customer/display.html?nodeId=468496"
GIFT_CARDS_HREF = "/gift-cards/b/?ie=UTF8&node=2238192011"
DELIVERY_PREFERENCE_HREF = "/gp/delivery/ajax/address-change.html"
DELIVERY_SELECTIONS_HREF = "/gp/delivery/ajax/address-selections"
SITE_DIRECTORY_HREF = "/gp/site-directory"
T7_TITLE = (
"Samsung T7 Portable SSD, 1TB External Solid State Drive, Speeds Up to "
"1,050MB/s, USB 3.2 Gen 2, Reliable Storage for Gaming, Students, "
"Professionals, MU-PC1T0T/AM, Gray"
)
def money(minor: int | None, currency: str = "USD") -> str:
if minor is None:
return ""
symbol = "$" if currency == "USD" else f"{currency} "
return f"{symbol}{minor / 100:,.2f}"
def _quote_data_attributes(product: dict[str, Any]) -> str:
"""Embed server-resolved transaction facts without executable markup.
JSON lives in quoted data attributes so the HTML parser decodes entities
before the frontend reads them. The browser must never derive a quote
from the visible price or from option-button copy.
"""
quote_matrix = product.get("option_quote_matrix")
if not isinstance(quote_matrix, (list, tuple)):
quote_matrix = []
public_quote_matrix: list[dict[str, Any]] = []
for quote in quote_matrix:
if not isinstance(quote, Mapping):
continue
transaction_target = quote.get("transaction_target")
selection_key = (
transaction_target.get("selection_key")
if isinstance(transaction_target, Mapping)
else None
)
public_quote = {
key: quote[key]
for key in (
"availability",
"price_minor",
"currency",
"image_path",
"display_availability",
"selected_options",
)
if key in quote
}
if isinstance(selection_key, str) and selection_key:
public_quote["transaction_target"] = {"selection_key": selection_key}
public_quote_matrix.append(public_quote)
default_selection = product.get("default_selected_options")
if not isinstance(default_selection, dict):
default_selection = {}
unavailable_copy = str(
product.get("option_unavailable_copy")
or "This selection is currently unavailable"
)
quote_json = escape(
json.dumps(public_quote_matrix, ensure_ascii=True, sort_keys=True, separators=(",", ":")),
quote=True,
)
default_json = escape(
json.dumps(default_selection, ensure_ascii=True, sort_keys=True, separators=(",", ":")),
quote=True,
)
return (
f'data-product-quote-matrix="{quote_json}" '
f'data-default-selected-options="{default_json}" '
f'data-option-unavailable-copy="{escape(unavailable_copy, quote=True)}"'
)
def product_href(product: dict[str, Any]) -> str:
canonical_path = product.get("canonical_path")
if isinstance(canonical_path, str) and canonical_path.startswith("/") and not canonical_path.startswith("//"):
return canonical_path
slug = product.get("slug")
if isinstance(slug, str) and slug:
return f"/{slug}/dp/{product['asin']}"
return f"/dp/{product['asin']}"
def product_review_href(product: dict[str, Any]) -> str:
"""Link every server-known product to its live local review surface."""
asin = str(product.get("asin", "")).upper()
return f"/product-reviews/{escape(asin, quote=True)}"
def amazon_logo() -> str:
return (
'amazon'
''
)
def source_department_href(department: dict[str, Any]) -> str:
return f'/s?i={quote_plus(str(department["slug"]))}'
def source_department_navigation(active_slug: str = "") -> str:
"""Render only real, rail-backed department destinations."""
links = []
for department in SOURCE_DEPARTMENTS:
slug = str(department["slug"])
current = ' aria-current="page"' if slug == active_slug else ""
links.append(
f'{escape(str(department["title"]))}'
)
return "".join(links)
def shopping_browse_href(label: str, page_category: str = "") -> str:
"""Return a local department or search destination for PDP browse links."""
query = " ".join(str(label).split()).strip()
normalized = query.casefold().replace("&", "and")
for department in SOURCE_DEPARTMENTS:
aliases = {
str(department["slug"]).casefold().replace("-", " "),
str(department["title"]).casefold().replace("&", "and"),
*(
str(alias).casefold().replace("&", "and")
for alias in department.get("aliases", ())
),
}
if normalized in aliases:
return source_department_href(department)
parameters: dict[str, str] = {"k": query or "products"}
category = " ".join(str(page_category).split()).strip().casefold().replace("&", "and")
for department in SOURCE_DEPARTMENTS:
aliases = {
str(department["title"]).casefold().replace("&", "and"),
*(str(alias).casefold().replace("&", "and") for alias in department.get("aliases", ())),
}
if category in aliases:
parameters["i"] = str(department["slug"])
break
return "/s?" + urlencode(parameters)
def pdp_full_view_controls(image_path: str, title: str) -> tuple[str, str]:
"""Build the keyboard-operable full-image trigger and its local dialog."""
safe_image = escape(str(image_path), quote=True)
safe_alt = escape(str(title), quote=True)
trigger = (
''
)
dialog = f"""
"""
return trigger, dialog
def secure_transaction_dialog() -> str:
"""Explain the modeled checkout boundary without implying a live processor."""
return """
"""
def all_menu(
account_name: str | None = None,
*,
initially_open: bool = False,
) -> str:
"""Render Amazon's persistent All navigation as a usable modal drawer.
The ordinary links remain real server destinations. JavaScript only changes
how the menu is revealed, so ``/gp/site-directory`` remains the no-script
fallback for both All triggers.
"""
short_name = account_name.strip().split()[0] if account_name and account_name.strip() else ""
account_href = (
"/gp/css/homepage.html"
if short_name
else "/ap/signin?openid.return_to=%2Fgp%2Fcss%2Fhomepage.html"
)
greeting = f"Hello, {escape(short_name)}" if short_name else "Hello, sign in"
auth_action = (
''
if short_name
else 'Sign In'
)
root_class = "nav-drawer-layer is-open" if initially_open else "nav-drawer-layer"
hidden = "false" if initially_open else "true"
return f"""
Delivering to {escape(delivery_label)}
{all_menu(account_name, initially_open=all_menu_open)}
{delivery_location_picker()}
"""
def mobile_shipping_notice() -> str:
"""Render the anonymous delivery notice seen on mobile source pages."""
return f"""
We're showing you items that ship to {escape(current_delivery_label())}. To see items that ship to a different country, change your delivery address.
"""
def home_collection_page(
collection_key: str,
tile_index: int | None,
products: list[dict[str, Any]],
cart_count: int,
account_name: str | None = None,
) -> str | None:
"""Render one homepage collection with the shared product-card family."""
group = HOME_COLLECTIONS_BY_KEY.get(collection_key)
if group is None or (
tile_index is not None and tile_index not in range(1, 5)
):
return None
tiles = list(group["tiles"])
selected = tiles[tile_index - 1] if tile_index is not None else None
heading = str(selected["label"]) if selected is not None else str(group["title"])
focus = ""
if selected is not None:
focus = f"""
From {escape(str(group["title"]))}
{escape(heading)}
Browse products in this category.
"""
else:
focus = f"""
Homepage collection
{escape(heading)}
Choose a category from this storefront collection.
"""
choices = "".join(
f"""
{escape(str(tile["label"]))}Explore collection
"""
for index, tile in enumerate(tiles, start=1)
)
matching_products = _home_collection_products(group, tile_index, products)
if not matching_products:
raise ValueError(f"home collection has no captured products: {collection_key}")
cards = "".join(
home_collection_product_card(product) for product in matching_products
)
product_section = f"""
Products in {escape(heading)}
See available products, ratings, prices, and buying options.
{product_section}
"""
return layout(
f"Amazon.com : {heading}",
body,
cart_count,
search_value=heading,
body_class="home-collection-page",
account_name=account_name,
)
def _evidence_placement_label(product: dict[str, Any]) -> str:
labels: list[str] = []
placements = product.get("placements")
if isinstance(placements, list):
for placement in placements:
if not isinstance(placement, dict):
continue
label = placement.get("railTitle")
if isinstance(label, str) and label and label not in labels:
labels.append(label)
return " · ".join(labels[:2])
def compare_add_form(product: dict[str, Any], *, compact: bool = False) -> str:
asin = str(product.get("asin") or "")
if not asin or product.get("compare_eligible") is not True:
return ""
class_name = "compare-add-form compact" if compact else "compare-add-form"
label = "Compare" if compact else "Add to compare"
safe_asin = escape(asin, quote=True)
selected_options = product.get("default_selected_options")
option_fields = "".join(
f''
for option_label, option_value in (
selected_options.items()
if isinstance(selected_options, dict)
else ()
)
)
return f''
def search_product_card(
product: dict[str, Any], *, result_layout: str = "list"
) -> str:
"""Render the common Amazon search-result card for every product source."""
asin = str(product["asin"])
title = str(product["title"])
href = product_href(product)
rating = str(product.get("rating") or "")
reviews = product.get("reviews")
reviews_display = str(product.get("reviews_display") or "")
if not reviews_display and isinstance(reviews, int) and reviews > 0:
reviews_display = f"{reviews:,}"
rating_markup = (
f''
f'{escape(rating)} ★★★★★ '
f'({escape(reviews_display)})'
if rating and reviews_display
else f'Customer reviews'
)
sponsored = (
'Sponsored'
if product.get("sponsored")
else ""
)
product_format = product.get("format")
format_markup = (
f'
{escape(str(product_format))}
'
if isinstance(product_format, str) and product_format
else ""
)
badge = str(product.get("badge") or "")
badge_markup = (
f'{escape(badge)}' if badge else ""
)
placement = _evidence_placement_label(product)
placement_markup = (
f'
Featured in {escape(placement)}
'
if placement
else ""
)
availability = str(product.get("availability") or "")
availability_markup = (
f'
{escape(availability)}
' if availability else ""
)
if result_layout == "grid":
# Grid cards reserve the same two information rows for every product.
# Source titles, availability and placement copy vary considerably; the
# stable slots keep the buying controls aligned without truncating the
# product identity above them.
grid_availability_markup = (
f'
{escape(availability)}
'
if availability
else '
'
)
grid_placement_markup = (
f'
Featured in {escape(placement)}
'
if placement
else '
'
)
grid_compare_markup = compare_add_form(product, compact=True)
if not grid_compare_markup:
grid_compare_markup = (
''
)
return f"""
"""
def _result_departments(products: list[dict[str, Any]]) -> str:
labels: list[str] = []
for product in products:
placements = product.get("placements")
if not isinstance(placements, list):
continue
for placement in placements:
if not isinstance(placement, dict):
continue
label = placement.get("railTitle")
if isinstance(label, str) and label and label not in labels:
labels.append(label)
return "".join(
f'{escape(label)}' for label in labels
)
PORTABLE_SEARCH_DISPLAY: dict[str, dict[str, Any]] = {
"B08HN37XC1": {
"image_path": "/static/assets/source-current/2026-07-21/search/search-sandisk-extreme-1tb.jpg",
"bought": "5K+ bought in past month",
"delivery": "$6.86 delivery Wednesday, July 29",
"buying_choices": "More Buying Choices $256.26 (12+ used & new offers)",
},
"B08GTYFC37": {
"image_path": "/static/assets/source-current/2026-07-21/search/search-sandisk-extreme-1tb.jpg",
"bought": "3K+ bought in past month",
"delivery": "$6.72 delivery Monday, July 27",
"buying_choices": "More Buying Choices $180.49 (10+ used & new offers)",
},
"B0F6NKYDTY": {
"image_path": "/static/assets/source-current/2026-07-21/search/search-sponsored-1tb.jpg",
"bought": "100+ bought in past month",
"delivery": "$6.21 delivery Monday, July 27",
"sponsored": True,
},
"B0BGKXX9TK": {
"image_path": "/static/assets/source-current/2026-07-21/search/search-ssk-500gb.jpg",
"bought": "1K+ bought in past month",
"delivery": "$6.34 delivery Monday, July 27",
},
"B0874XN4D8": {
"image_path": "/static/assets/source-current/2026-07-21/search/search-samsung-t7-1tb.jpg",
"bought": "4K+ bought in past month",
"delivery": "$7.30 delivery Sunday, July 26",
},
"B0C5JQ68FY": {
"image_path": "/static/assets/source-current/2026-07-21/search/search-sandisk-portable-1tb.jpg",
"bought": "2K+ bought in past month",
"delivery": "$6.52 delivery Monday, July 27",
},
"B0CHFSWM2P": {
"bought": "10K+ bought in past month",
"delivery": "$7.61 delivery Monday, July 27",
},
}
PORTABLE_SEARCH_ASINS = frozenset(
{
"B08HN37XC1",
"B08GTYFC37",
"B0F6NKYDTY",
"B0BGKXX9TK",
"B0874XN4D8",
"B0C5JQ68FY",
"B08GV9M64L",
"B09VLK9W3S",
"B0CHFSWM2P",
}
)
def _search_money_parameter(minor: int) -> str:
whole, cents = divmod(minor, 100)
return str(whole) if cents == 0 else f"{whole}.{cents:02d}".rstrip("0")
def _search_state_hidden_fields(request: SearchRequest) -> str:
pairs: list[tuple[str, str]] = []
if request.query:
pairs.append(("k", request.query))
if request.department != DEFAULT_SEARCH_DEPARTMENT:
pairs.append(("i", request.department))
pairs.extend(("brand", brand) for brand in request.brands)
if request.min_price_minor is not None:
pairs.append(("minPrice", _search_money_parameter(request.min_price_minor)))
if request.max_price_minor is not None:
pairs.append(("maxPrice", _search_money_parameter(request.max_price_minor)))
if request.rating is not None:
pairs.append(("rating", request.rating))
if request.availability is not None:
pairs.append(("availability", request.availability))
return "".join(
f''
for name, value in pairs
)
def _search_filter_link(
label: str,
href: str,
*,
selected: bool = False,
navigation: bool = False,
) -> str:
class_name = "search-filter-link is-selected" if selected else "search-filter-link"
state = (
(' aria-current="page"' if selected else "")
if navigation
else f' role="checkbox" aria-checked="{"true" if selected else "false"}"'
)
return (
f''
f''
f'{escape(label)}'
)
def _search_department_filters(
request: SearchRequest, available_departments: Iterable[str]
) -> str:
available = set(available_departments)
links = [
_search_filter_link(
"All Departments",
search_href(request, department=DEFAULT_SEARCH_DEPARTMENT, page=1),
selected=request.department == DEFAULT_SEARCH_DEPARTMENT,
navigation=True,
)
]
for department in SOURCE_DEPARTMENTS:
slug = str(department["slug"])
if slug not in available and request.department != slug:
continue
links.append(
_search_filter_link(
str(department["title"]),
search_href(request, department=slug, page=1),
selected=request.department == slug,
navigation=True,
)
)
return "".join(links)
def _search_refinements(
request: SearchRequest,
available_brands: Iterable[str],
available_facets: Mapping[str, Any],
) -> str:
clear_href = search_href(
request,
brands=(),
min_price_minor=None,
max_price_minor=None,
rating=None,
availability=None,
sort="relevance",
page=1,
)
brand_values = sorted(
{brand for brand in available_brands if brand} | set(request.brands),
key=str.casefold,
)
brand_links = []
active_brand_keys = {brand.casefold() for brand in request.brands}
for brand in brand_values:
selected = brand.casefold() in active_brand_keys
updated = tuple(
existing
for existing in request.brands
if existing.casefold() != brand.casefold()
)
if not selected:
updated = (*updated, brand)
brand_links.append(
_search_filter_link(
brand,
search_href(request, brands=updated, page=1),
selected=selected,
)
)
price_ranges = (
("Under $25", None, 2499),
("$25 to $50", 2500, 4999),
("$50 to $100", 5000, 9999),
("$100 to $200", 10000, 19999),
("$200 & above", 20000, None),
)
available_price_ranges = {
tuple(raw_range)
for raw_range in available_facets.get("price_ranges", ())
if isinstance(raw_range, (list, tuple)) and len(raw_range) == 2
}
price_links = "".join(
_search_filter_link(
label,
search_href(
request,
min_price_minor=(None if selected else minimum),
max_price_minor=(None if selected else maximum),
page=1,
),
selected=selected,
)
for label, minimum, maximum in price_ranges
if (minimum, maximum) in available_price_ranges
or (
request.min_price_minor == minimum
and request.max_price_minor == maximum
)
for selected in (
request.min_price_minor == minimum
and request.max_price_minor == maximum,
)
)
rating_selected = request.rating == "4-up"
availability_selected = request.availability == "in-stock"
available_departments = available_facets.get("departments", ())
department_section = (
f'
Department
{_search_department_filters(request, available_departments)}'
if available_departments or request.department != DEFAULT_SEARCH_DEPARTMENT
else ""
)
brand_section = (
f'
Brand
{"".join(brand_links)}'
if (available_facets.get("brand") or request.brands) and brand_links
else ""
)
price_section = (
f'
Price
{price_links}' if price_links else ""
)
rating_section = (
'
Customer Reviews
'
+ _search_filter_link(
"4 Stars & Up",
search_href(
request, rating=None if rating_selected else "4-up", page=1
),
selected=rating_selected,
)
if available_facets.get("rating") or rating_selected
else ""
)
availability_section = (
'
Availability
'
+ _search_filter_link(
"In Stock",
search_href(
request,
availability=None if availability_selected else "in-stock",
page=1,
),
selected=availability_selected,
)
if available_facets.get("availability") or availability_selected
else ""
)
return f"""
"""
def _active_search_filters(request: SearchRequest) -> str:
chips: list[str] = []
for brand in request.brands:
remaining = tuple(
value for value in request.brands if value.casefold() != brand.casefold()
)
chips.append(
f'{escape(brand)} ×'
)
if request.min_price_minor is not None or request.max_price_minor is not None:
if request.min_price_minor is None:
label = f"Up to ${_search_money_parameter(request.max_price_minor or 0)}"
elif request.max_price_minor is None:
label = f"${_search_money_parameter(request.min_price_minor)} & above"
else:
label = (
f"${_search_money_parameter(request.min_price_minor)}–"
f"${_search_money_parameter(request.max_price_minor)}"
)
chips.append(
f'{escape(label)} ×'
)
if request.rating is not None:
chips.append(
f'4 Stars & Up ×'
)
if request.availability is not None:
chips.append(
f'In Stock ×'
)
return (
f''
if chips
else ""
)
def _search_sort_form(request: SearchRequest) -> str:
options = (
("relevance", "Featured"),
("price-asc", "Price: Low to High"),
("price-desc", "Price: High to Low"),
("rating-desc", "Avg. Customer Review"),
)
option_markup = "".join(
f''
for value, label in options
)
return f"""
"""
def _search_pagination(page: SearchPage) -> str:
if page.page_count <= 1:
return ""
page_numbers = sorted(
{1, page.page_count, page.page - 1, page.page, page.page + 1}
& set(range(1, page.page_count + 1))
)
parts = []
if page.page > 1:
parts.append(
f'‹ Previous'
)
else:
parts.append('‹ Previous')
previous_number = 0
for number in page_numbers:
if previous_number and number > previous_number + 1:
parts.append('…')
if number == page.page:
parts.append(
f'{number}'
)
else:
parts.append(
f'{number}'
)
previous_number = number
if page.page < page.page_count:
parts.append(
f'Next ›'
)
else:
parts.append('Next ›')
return f''
DEPARTMENT_LANDING_CONTENT: dict[str, dict[str, Any]] = {
"books": {
"label": "books",
"category_heading": "books",
"hero": "What everyone's reading",
"primary_rail": "Best sellers in print",
"secondary_rail": "New releases in print",
"categories": ("Kindle eBooks", "Print Books", "Audible Audiobooks"),
"sidebar": (),
},
"home-kitchen": {
"label": "Amazon Home",
"category_heading": "Amazon Home",
"hero": "Outdoor furniture & more",
"primary_rail": "Decorate for the season",
"secondary_rail": "Fresh finds for every room",
"categories": (
"Premium",
"New arrivals",
"Sales & deals",
"Amazon Home Kids",
"Garden & outdoor",
"Decor",
),
"sidebar": (),
},
"toys-games": {
"label": "Toys & Games",
"category_heading": "Toys & Games",
"hero": "Summer fun for little scholars",
"primary_rail": "Shop top categories",
"secondary_rail": "More playtime favorites",
"categories": (
"Shop all toys",
"Deals",
"Best sellers",
"New releases",
"Screen free play",
"Summer learning",
),
"sidebar": (),
},
"computers": {
"label": "Computers & Accessories",
"category_heading": "Computers & Accessories",
"hero": "Computers & Accessories",
"primary_rail": "Shop featured products",
"secondary_rail": "Storage and accessories",
"categories": (
"Laptops",
"Desktops",
"PC Gaming",
"Monitors",
"Tablets",
"Computer Accessories",
),
"sidebar": (
"Handpicked Electronics",
"Laptops",
"Desktops",
"PC Gaming",
"Monitors",
"Tablets",
"Networking",
"Computer Components",
"Drives & Storage",
),
},
"beauty-personal-care": {
"label": "Beauty",
"category_heading": "Featured categories",
"hero": "Featured categories",
"primary_rail": "Beauty favorites",
"secondary_rail": "More to explore",
"categories": (
"Personal Care",
"Skin Care",
"Hair Care",
"Makeup",
"Fragrance",
"Foot, Hand & Nail Care",
"Tools & Accessories",
"Shave & Hair Removal",
"Salon & Spa Equipment",
),
"sidebar": (
"Makeup",
"Skin Care",
"Hair Care",
"Fragrance",
"Foot, Hand & Nail Care",
"Tools & Accessories",
"Shave & Hair Removal",
"Personal Care",
"Gift Sets",
"Salon & Spa Equipment",
),
},
}
def _is_default_department_landing(request: SearchRequest) -> bool:
return bool(
request.department in DEPARTMENT_LANDING_CONTENT
and not request.query
and not request.brands
and request.min_price_minor is None
and request.max_price_minor is None
and request.rating is None
and request.availability is None
and request.sort == "relevance"
and request.page == 1
)
def _department_landing_tiles(
slug: str,
categories: Iterable[str],
products: list[dict[str, Any]],
) -> str:
if not products:
return ""
return "".join(
f''
f''
f'{escape(label)}'
for index, label in enumerate(categories)
)
def _department_compact_product_card(product: dict[str, Any]) -> str:
title = str(product["title"])
href = product_href(product)
rating = str(product.get("rating") or "")
reviews = int(product.get("reviews") or 0)
rating_markup = (
f''
f'{escape(rating)} ★★★★★ {reviews:,}'
if rating and reviews
else ""
)
delivery = str(product.get("delivery_copy") or "")
return f"""
"""
return layout(
f"Amazon.com: {content['label']}",
body,
cart_count,
search_value="",
body_class=f"department-landing-page department-{slug}-page",
account_name=account_name,
active_department=slug,
)
def search_results_page(
page: SearchPage,
cart_count: int,
account_name: str | None = None,
*,
available_brands: Iterable[str] = (),
available_facets: Mapping[str, Any] | None = None,
result_layout: str = "list",
department_rail_products: Iterable[dict[str, Any]] = (),
) -> str:
"""Render one server-refined Amazon search page."""
request = page.request
if _is_default_department_landing(request):
return department_landing_page(
page,
cart_count,
account_name,
rail_products=department_rail_products,
)
safe_query = escape(request.query)
department = SOURCE_DEPARTMENT_BY_SLUG.get(request.department)
department_slug = str(department["slug"]) if department is not None else ""
start = (page.page - 1) * page.page_size + 1 if page.total else 0
end = start + len(page.items) - 1 if page.items else 0
if department is not None and not request.query:
context = f'in {escape(str(department["title"]))}'
else:
context = f'for "{safe_query}"'
summary = f"{start}-{end} of {page.total} results {context}" if page.total else f"0 results {context}"
if result_layout not in {"list", "grid"}:
raise ValueError(f"unsupported search result layout: {result_layout}")
result_markup = [
search_product_card(dict(hit.product), result_layout=result_layout)
for hit in page.items
]
if result_markup:
heading = escape(str(department["title"])) if department is not None else "Results"
results = f"""
{heading}
Browse products and buying options.
{''.join(result_markup)}
{_search_pagination(page)}
"""
else:
has_refinements = bool(
request.brands
or request.min_price_minor is not None
or request.max_price_minor is not None
or request.rating is not None
or request.availability is not None
)
if department is not None and not request.query:
empty_heading = f'No results in {escape(str(department["title"]))}'
else:
empty_heading = f'No results for “{safe_query}”'
if has_refinements:
action = (
f'Clear filters'
)
elif request.department != DEFAULT_SEARCH_DEPARTMENT and request.query:
action = (
f'Search all departments'
)
else:
action = 'Return to Amazon home'
results = f"""
{empty_heading}
Try removing a filter, checking your spelling, or using fewer words.
{action}
"""
active_filters = _active_search_filters(request)
body = f"""
{summary}
{summary}{_search_sort_form(request)}
{active_filters}
{_search_refinements(request, available_brands, available_facets or {})}{results}
"""
return layout(
f"Amazon.com : {request.query or (department or {}).get('title', 'Search')}",
body,
cart_count,
search_value=request.query,
body_class="search-page",
account_name=account_name,
active_department=request.department,
)
def site_directory_page(
sections: list[dict[str, Any]],
cart_count: int,
account_name: str | None = None,
) -> str:
"""Render the All trigger's no-script destination as the same open drawer.
Amazon's All control is a navigation drawer rather than a product-results
page. Keeping the server fallback in that state prevents a missed script
interception, refresh, or copied URL from changing page families.
"""
del sections
body = """
All Amazon departments
"""
return layout(
"Amazon.com - All departments",
body,
cart_count,
body_class="site-directory-page",
account_name=account_name,
all_menu_open=True,
)
def generic_add_to_cart_form(
product: dict[str, Any],
*,
quantity_max: int = 30,
quantity_id: str | None = None,
button_class: str = "",
selected_options: dict[str, str] | None = None,
) -> str:
"""Render the ordinary commerce form used outside the strict T7 journey."""
asin = escape(str(product["asin"]), quote=True)
field_id = quantity_id or f"quantity-{asin.lower()}"
limit = max(1, min(int(quantity_max), 30))
options = "".join(
f''
for quantity in range(1, limit + 1)
)
extra_button_class = f" {button_class}" if button_class else ""
option_fields = "".join(
f''
for label, value in (selected_options or {}).items()
)
return f"""
"""
def wishlist_add_form(
product: dict[str, Any],
selected_options: dict[str, str] | None = None,
*,
css_class: str = "add-to-list-form",
) -> str:
"""Render the PDP entry point while keeping Wishlist views decoupled.
The lazy import avoids a module cycle: ``wishlist_views`` reuses the global
Amazon layout, money, and option-markup helpers from this module.
"""
from wishlist_views import wishlist_entry_form
defaults = product.get("default_selected_options")
selection = (
{str(label): str(value) for label, value in defaults.items()}
if selected_options is None and isinstance(defaults, dict)
else dict(selected_options or {})
)
return wishlist_entry_form(
product,
selection,
css_class=css_class,
)
def _deals_filter_url(
filters: dict[str, Any], **overrides: Any
) -> str:
state: dict[str, Any] = {
"theme": filters.get("theme") or "",
"department": filters.get("department") or "",
"brand": list(filters.get("brands") or ()),
"rating": filters.get("rating") or "",
"minPrice": filters.get("min_price_text") or "",
"maxPrice": filters.get("max_price_text") or "",
"minDiscount": filters.get("min_discount_text") or "",
"maxDiscount": filters.get("max_discount_text") or "",
"dealType": filters.get("deal_type") or "",
}
state.update(overrides)
pairs: list[tuple[str, str]] = []
for key in (
"theme",
"department",
"rating",
"minPrice",
"maxPrice",
"minDiscount",
"maxDiscount",
"dealType",
):
value = state.get(key)
if isinstance(value, str) and value:
pairs.append((key, value))
raw_brands = state.get("brand")
if isinstance(raw_brands, (list, tuple)):
pairs.extend(
("brand", str(brand)) for brand in raw_brands if str(brand)
)
query = urlencode(pairs, doseq=True)
return "/gp/goldbox/" + (f"?{query}" if query else "")
def _deals_quick_add_form(product: dict[str, Any]) -> str:
asin = escape(str(product["asin"]), quote=True)
label = escape(f"Add {product['title']} to cart", quote=True)
return f"""
"""
def deals_product_card(
product: dict[str, Any], filters: dict[str, Any] | None = None
) -> str:
"""Render one product in the Deals page family."""
active_filters = filters or {}
asin = escape(str(product["asin"]), quote=True)
title = escape(str(product["title"]))
href = escape(product_href(product), quote=True)
review_href = escape(product_review_href(product), quote=True)
image_path = escape(str(product["image_path"]), quote=True)
price = money(int(product["price_minor"]), str(product["currency"]))
brand = str(product.get("brand") or "").strip()
brand_markup = (
f'{escape(brand)}'
if brand
else ""
)
rating = str(product.get("rating") or "").strip()
reviews = product.get("reviews")
rating_markup = ""
if rating and isinstance(reviews, int) and reviews > 0:
rating_markup = (
f''
f'{escape(rating)}★★★★★{reviews:,}'
)
discount = product.get("discount_percent")
list_price = product.get("list_price_minor")
discount_markup = ""
reference_markup = ""
if (
isinstance(list_price, int)
and not isinstance(list_price, bool)
and list_price > int(product["price_minor"])
):
reference_label = escape(
str(product.get("reference_price_label") or "List price")
)
reference_markup = (
f'
' if capacity_buttons else "")
if primary_option_value
else ""
)
choice_groups_markup = ""
raw_choice_groups = detail.get("choice_groups", [])
option_spec = product.get("option_spec")
if not raw_choice_groups and isinstance(option_spec, (list, tuple)):
raw_choice_groups = [
{
"label": str(group["label"]),
"value": str(group["default"]),
"options": [str(value) for value in group["options"]],
"mode": "buttons",
}
for group in option_spec
if isinstance(group, Mapping)
and group.get("label")
and group.get("default")
and isinstance(group.get("options"), (list, tuple))
]
for group in raw_choice_groups:
if not isinstance(group, dict):
continue
group_label = str(group.get("label", ""))
group_value = str(group.get("value", ""))
group_options = group.get("options", [])
if not group_label or not group_value or not isinstance(group_options, list):
continue
if group.get("mode") == "select":
select_options = "".join(
f''
for option in group_options
if isinstance(option, str) and option
)
if select_options:
choice_groups_markup += (
f'
{escape(group_label)}: '
f'{escape(group_value)}
'
f''
)
continue
group_buttons: list[str] = []
if group.get("mode") == "swatch":
for option in group_options:
if not isinstance(option, dict) or not option.get("name"):
continue
option_name = str(option["name"])
selected = option_name == group_value
offer_copy = str(option.get("offer_copy", ""))
image_path = str(option.get("image", ""))
image_markup = (
f''
if image_path
else ""
)
group_buttons.append(
f''
)
options_class = "pdp-choice-options pdp-choice-swatches"
else:
for option in group_options:
option_name = str(option)
selected = option_name == group_value
group_buttons.append(
f''
)
options_class = "pdp-choice-options"
if group_buttons:
choice_groups_markup += (
f'
' if byline else ""
)
source_rating = product.get("rating")
source_reviews = product.get("reviews")
if isinstance(source_rating, str) and source_rating and isinstance(source_reviews, int) and source_reviews > 0:
rating_markup = (
f'
'
)
else:
# A direct PDP may establish that a product currently has no reviews
# without establishing a rating. Do not manufacture stars or an
# aggregate from the local-review system in that case.
source_review_copy = detail.get("source_review_copy")
rating_markup = (
f'
{detail_table}
{important_information_markup}
{recommendations}
"""
if reviews_html:
body = body.replace("\n ", f"\n {reviews_html}\n ", 1)
return layout(
f"Amazon.com: {product['title']} : {page_category}",
body,
cart_count,
body_class="pdp-page detailed-pdp-page unified-pdp-page",
account_name=account_name,
)
def product_page(
product: dict[str, Any],
cart_count: int,
flow_ready: bool,
account_name: str | None = None,
*,
local_reviews: Iterable[dict[str, Any]] | None = None,
review_star: int | None = None,
review_sort: str = "recent",
review_base_path: str | None = None,
review_form_error: str | None = None,
) -> str:
source_rating_summary: dict[str, Any] | None = None
detail = product.get("pdp")
detail_summary = detail.get("review_summary") if isinstance(detail, Mapping) else None
if isinstance(detail_summary, Mapping):
rating = detail_summary.get("rating")
rating_count = detail_summary.get("review_count")
if rating not in (None, "") and isinstance(rating_count, int) and rating_count >= 0:
try:
numeric_rating = float(rating)
except (TypeError, ValueError):
numeric_rating = None
if numeric_rating is not None:
source_rating_summary = {
"rating": numeric_rating,
"rating_count": rating_count,
"count_label": "ratings",
}
elif product.get("display_provenance") in {"direct", "legacy"}:
# Direct and legacy display records carry captured aggregate facts even
# when the richer review fixture has no row for the ASIN. Keep that
# source aggregate separate from locally-authored reviews.
rating = product.get("rating")
rating_count = product.get("reviews")
if rating not in (None, "") and isinstance(rating_count, int) and rating_count >= 0:
try:
numeric_rating = float(rating)
except (TypeError, ValueError):
numeric_rating = None
if numeric_rating is not None:
source_rating_summary = {
"rating": numeric_rating,
"rating_count": rating_count,
"count_label": "ratings",
}
reviews_html = (
render_reviews_section(
product["asin"],
local_reviews,
star=review_star,
sort=review_sort,
account_name=account_name,
base_path=review_base_path,
form_error=review_form_error,
product_label=str(product["title"]),
source_rating_summary=source_rating_summary,
)
if local_reviews is not None
else ""
)
return unified_product_page(
product,
cart_count,
account_name,
reviews_html,
flow_ready=flow_ready,
)
def product_reviews_page(
product: dict[str, Any],
reviews_html: str,
cart_count: int,
account_name: str | None = None,
) -> str:
"""Render a live review destination for every product review link."""
href = escape(product_href(product), quote=True)
image_path = escape(str(product.get("image_path", "")), quote=True)
title = escape(str(product["title"]))
if reviews_html:
content = reviews_html
else:
content = (
''
'
Customer reviews
'
'
There are no customer ratings or review summaries for this item yet.
'
f'Return to the product page'
)
body = f"""
{content}
"""
return layout(
f"Amazon.com: Customer reviews: {product['title']}",
body,
cart_count,
body_class="product-reviews-page",
account_name=account_name,
)
def cart_page(
lines: list[dict[str, Any]],
cart_count: int,
account_name: str | None = None,
saved_lines: list[dict[str, Any]] | None = None,
recommendation_products: Iterable[dict[str, Any]] = (),
) -> str:
saved = list(saved_lines or [])
has_active = bool(lines)
has_saved = bool(saved)
has_cart_content = has_active or has_saved
saved_markup = ""
if has_saved:
saved_count = sum(max(1, int(line.get("quantity", 1))) for line in saved)
saved_label = "item" if saved_count == 1 else "items"
saved_items = "".join(cart_line(line, saved=True) for line in saved)
saved_markup = f"""
Saved for later ({saved_count} {saved_label})
{saved_items}
"""
if has_active:
items = "".join(cart_line(line) for line in lines)
subtotal = sum(int(line["price_minor"]) * int(line["quantity"]) for line in lines)
currency = str(lines[0].get("currency", "USD"))
active_content = f"""
"""
if has_cart_content:
content = active_content + saved_markup
recommendations = ""
else:
content = active_content + """
Continue shopping
"""
recommendations = cart_recommendations(
recommendation_products, id_prefix="cart"
)
main_state = "populated-cart-main" if has_cart_content else "empty-cart-main"
canvas_state = "populated" if has_cart_content else "empty"
if has_saved and not has_active:
canvas_state += " saved-only"
body = f"""
{content}
The price and availability of items at Amazon.com are subject to change. The Cart is a temporary place to store a list of your items and reflects each item's most recent price. Learn more Do you have a gift card or promotional code? We'll ask you to enter your claim code when it's time to pay.
Sign inContinue shopping
"""
return layout(f"Amazon.com - {title}", body, cart_count, body_class="boundary-page", account_name=account_name)
def customer_service_page(
cart_count: int,
account_name: str | None = None,
*,
help_query: str = "",
) -> str:
"""Render a navigable support hub instead of a generic boundary card."""
account_href = (
"/gp/css/homepage.html"
if account_name
else "/ap/signin?openid.return_to=%2Fgp%2Fcss%2Fhomepage.html"
)
topics = (
(
"📦",
"Your Orders",
"Track a package, inspect a placed order, or review its delivery status.",
"/gp/css/order-history",
"order package tracking purchase",
),
(
"↩",
"Returns & refunds",
"Find return and replacement guidance, then open the relevant order.",
RETURNS_REPLACEMENTS_HREF,
"return refund replacement exchange",
),
(
"🚚",
"Shipping & delivery",
"Compare delivery choices and learn where shipping charges are shown.",
SHIPPING_POLICIES_HREF,
"shipping delivery rate charge address singapore",
),
(
"👤",
"Manage your account",
"Sign in, review account access, and update the checkout address you use.",
account_href,
"account sign in login password address",
),
(
"🎁",
"Gift Cards & gifts",
"Open Gift Cards or browse gift ideas from the marketplace departments.",
GIFT_CARDS_HREF,
"gift card balance redeem present",
),
(
"🛒",
"Cart & checkout",
"Review your cart before selecting an address, delivery, and payment method.",
"/gp/cart/view.html",
"cart checkout payment buy",
),
)
def topic_card(topic: tuple[str, str, str, str, str], css_class: str) -> str:
icon, title, copy, href, _ = topic
return f"""
{icon}{escape(title)}{escape(copy)}
"""
normalized_query = " ".join(help_query.split())[:160]
search_results = ""
if normalized_query:
terms = tuple(term.lower() for term in normalized_query.split() if term)
matches = tuple(
topic
for topic in topics
if any(
term in f"{topic[1]} {topic[2]} {topic[4]}".lower()
for term in terms
)
)
if matches:
result_cards = "".join(topic_card(topic, "help-search-result") for topic in matches)
search_results = f"""
Help results for “{escape(normalized_query)}”
{result_cards}
"""
else:
search_results = f"""
No exact help result for “{escape(normalized_query)}”
Try a shorter search, or choose one of the help topics below.
"""
topic_cards = "".join(topic_card(topic, "help-topic-card") for topic in topics)
greeting = f"Hello, {escape(account_name.split()[0])}." if account_name else "Hello."
body = f"""
{greeting}
What can we help you with?
{search_results}
Some things you can do here
{topic_cards}
Need help with an order?
Open Your Orders for order-specific delivery and payment details.
Go to Your Orders
"""
return layout(
"Amazon Customer Service",
body,
cart_count,
body_class="help-page customer-service-page",
account_name=account_name,
)
def shipping_policies_page(
cart_count: int,
account_name: str | None = None,
) -> str:
"""Describe the delivery choices that the checkout backend actually supports."""
body = f"""
Shipping Rates & Policies
Shipping availability and charges are shown before an order is placed. Product pages show offer-specific delivery information when it is available.
Delivery choices at checkout
Standard deliveryFREE
Included in the supported checkout flow.
Expedited delivery$12.99
A faster delivery choice available during checkout.
Delivering to {escape(current_delivery_label())}
The storefront currently shows offers for delivery to {escape(current_delivery_label())}. Change the delivery location from the header, then select the full shipping address while checking out.
"""
return layout(
"Amazon.com Help: Shipping Rates & Policies",
body,
cart_count,
body_class="help-page help-article-page shipping-policies-page",
account_name=account_name,
)
def conditions_of_use_page(
cart_count: int,
account_name: str | None = None,
) -> str:
"""State the terms that actually govern this local storefront.
The source article describes a real marketplace. Restating it here would
claim obligations this clone cannot carry, so this page describes the local
storefront truthfully instead and says plainly that it is not the real one.
"""
body = f"""
Conditions of Use
These conditions govern this local storefront only.
What this storefront is
This is a self-contained storefront that serves every page, image, and script from its own server. It is not operated by Amazon.com, Inc., and using it creates no relationship with that company.
Orders and payments
Orders placed here are recorded in this storefront's own database. No goods are dispatched, no money moves, and no payment instrument is charged. Card details entered during checkout are sandbox values handled by a local test gateway.
Your account
An account created here exists only in this storefront and is not shared with any other site. You may stop using it at any time; see Privacy Notice for what is stored.
Catalog content
Product titles, images, prices, and reviews are captured reference material shown to reproduce a shopping interface. They are not offers, and prices are not honoured.
"""
return layout(
"Amazon.com Help: Conditions of Use",
body,
cart_count,
body_class="help-page help-article-page conditions-of-use-page",
account_name=account_name,
)
def privacy_notice_page(
cart_count: int,
account_name: str | None = None,
) -> str:
"""Describe the data this storefront actually stores, and nothing else."""
body = f"""
Privacy Notice
Everything this storefront records stays on this storefront.
What is stored
A browser session identifier, and — if you create an account — an email address, a display name, a password hash, and the delivery location, cart, wish lists, orders, and reviews belonging to that account.
What is not stored
Passwords are never stored in readable form. Verification codes are stored only as hashes and expire. No payment instrument is stored: checkout uses sandbox values handled by a local test gateway.
Where it goes
Nowhere. This storefront makes no requests to other sites while you browse, sets no third-party cookies, and runs no analytics or advertising trackers. Verification email is written to a local outbox rather than delivered, unless this deployment has been explicitly configured otherwise.
Retention
Storefront data lives in a single local database and is rebuilt from a fixed seed whenever the storefront is reset, which discards accounts and their contents.
"""
return layout(
"Amazon.com Help: Privacy Notice",
body,
cart_count,
body_class="help-page help-article-page privacy-notice-page",
account_name=account_name,
)
def returns_replacements_page(
cart_count: int,
account_name: str | None = None,
) -> str:
"""Provide a useful path from return help to the shopper's real orders."""
order_action = "View Your Orders" if account_name else "Sign in to view orders"
body = f"""
Returns & Replacements
Start with Your Orders so the available action stays tied to the correct order and delivery state. This clone provides a local return-and-refund simulation; it does not create a real label, shipment, or money movement.
1
Open Your Orders
Sign in and locate the order that contains the item.
2
Wait for simulated delivery
The Return items action appears on eligible order details after the local shipment reaches Delivered.
3
Submit and track the return
Choose a reason, submit the request, and follow its Requested, Received, and Refunded states from the order.
Refund timing in this clone
A completed simulated refund record appears only after the local return advances through Received to Refunded. It is a state model only and never contacts a bank or card network.
"""
return layout(
"Amazon.com Help: Returns & Replacements",
body,
cart_count,
body_class="help-page help-article-page returns-page",
account_name=account_name,
)
def gift_cards_page(
cart_count: int,
account_name: str | None = None,
) -> str:
"""Render a branded Gift Cards destination with only usable local actions."""
account_href = (
"/gp/css/homepage.html"
if account_name
else "/ap/signin?openid.return_to=%2Fgift-cards%2Fb%2F"
)
account_action = "Go to your account" if account_name else "Sign in"
departments = (
("Books", "/s?k=books", "For readers of every kind"),
("Home & Kitchen", "/s?k=home+kitchen", "Useful picks for the home"),
("Toys & Games", "/s?k=toys", "Gifts for play and discovery"),
("Beauty", "/s?k=beauty+personal+care", "Beauty and personal care picks"),
)
department_cards = "".join(
f'{escape(title)}{escape(copy)}Shop now ›'
for title, href, copy in departments
)
body = f"""
Amazon Gift Cards
Give them more ways to find the right gift
Browse current marketplace departments and deals, or sign in for account help.
Customer Service connects gift questions with account, order, and shopping help.
Visit Customer Service
"""
return layout(
"Amazon.com Gift Cards",
body,
cart_count,
body_class="gift-cards-page",
account_name=account_name,
)
def navigation_landing_page(
title: str,
copy: str,
links: Iterable[tuple[str, str]],
cart_count: int,
account_name: str | None = None,
) -> str:
"""Render a shallow but usable destination for secondary Amazon navigation."""
actions = "".join(
f'{escape(label)}'
for label, href in links
)
body = f"""
{escape(title)}
{escape(copy)}
{actions}
"""
return layout(
f"Amazon.com - {title}",
body,
cart_count,
body_class="boundary-page navigation-landing-page",
account_name=account_name,
)
def delivery_location_page(
cart_count: int,
account_name: str | None = None,
*,
error: bool = False,
) -> str:
"""The no-JavaScript destination for the header delivery-location control.
This is the same server route the scripted dialog posts to, so a browser
with JavaScript disabled reaches an identical outcome one navigation later.
"""
code, label = current_delivery_country()
status = (
'
'
"That country/region is not one of the storefront delivery locations. "
"The delivery location has not been changed.
"
if error
else ""
)
body = f"""
Choose your delivery location
Delivery options and delivery speeds may vary for different locations. The storefront is currently showing offers for delivery to {escape(label)}.
{status}
A full shipping address is selected while placing an order.
{money(line_total, item_currency)}'
)
return "".join(rows) or '
No items are attached to this checkout.
'
def _checkout_summary(checkout: dict[str, Any]) -> str:
currency = str(checkout.get("currency") or "USD")
items = _checkout_items(checkout)
computed_subtotal = sum(
_minor_value(item.get("line_total_minor"), _minor_value(item.get("price_minor")) * max(1, _minor_value(item.get("quantity"), 1)))
for item in items
)
subtotal = _minor_value(checkout.get("items_subtotal_minor"), computed_subtotal)
shipping = _minor_value(checkout.get("shipping_minor"))
total = _minor_value(checkout.get("total_minor"), subtotal + shipping)
shipping_copy = "FREE" if shipping == 0 else money(shipping, currency)
return f"""
"""
def _address_markup(address: dict[str, Any]) -> str:
fields = (
address.get("full_name"),
address.get("address_line1"),
address.get("address_line2"),
" ".join(
part
for part in (
str(address.get("city") or ""),
str(address.get("state_region") or ""),
str(address.get("postal_code") or ""),
)
if part
),
address.get("country_code"),
address.get("phone"),
)
lines = [escape(str(value)) for value in fields if value]
if not lines:
return '
No shipping address selected.
'
return f'{" ".join(lines)}'
def _delivery_label(value: Any) -> str:
return "Expedited delivery" if str(value).lower() == "expedited" else "Standard delivery"
def _payment_markup(payment: Any) -> str:
if not isinstance(payment, dict):
return '
No payment method selected.
'
status = escape(str(payment.get("status") or "Selected"))
label = escape(str(payment.get("method_label") or "Sandbox payment method"))
environment = (
"Stripe test environment"
if str(payment.get("method") or "") == "stripe-test"
else "Local simulation"
)
return f'
{label} {environment} · {status}
'
def _simulation_notice(payload: dict[str, Any]) -> str:
notice = str(
payload.get("simulation_notice")
or "This is a local simulation. No real order, payment, shipment, or email is sent outside this workspace."
)
return f'
Local simulation
{escape(notice)}
'
def _checkout_reconciliation_notice(payload: dict[str, Any]) -> str:
notice = str(payload.get("notice") or "")
if notice == "cart-changed":
return (
'
'
'Your cart changed'
'
Items, quantities, options, or prices changed after the previous '
'payment approval. Review the updated order total and select a sandbox '
'payment method again.
'
)
if notice == "payment-declined":
return (
'
'
'The sandbox issuer declined this payment'
'
No money was moved and no real account was contacted. Choose a '
'different sandbox method below and retry.
'
)
if notice == "payment-cancelled":
return (
'
'
'Stripe test Checkout was cancelled'
'
No order was created. Your checkout and cart were kept, so you '
'can review them and try again.
'
)
if notice == "unsupported-delivery-country":
return (
'
'
'Choose a supported delivery country'
'
The previously selected address cannot be used for this local '
'checkout. Choose or add one of the countries listed below.
'
)
return ""
def checkout_address_page(
checkout: dict[str, Any], cart_count: int, account_name: str | None
) -> str:
selected_address = _checkout_address(checkout)
raw_saved = checkout.get("saved_addresses", [])
saved_addresses = (
[item for item in raw_saved if isinstance(item, dict)]
if isinstance(raw_saved, list)
else []
)
selected_id = _minor_value(selected_address.get("address_id"), 0)
if not selected_id:
default_address = next(
(item for item in saved_addresses if item.get("is_default")),
saved_addresses[0] if saved_addresses else None,
)
selected_id = (
_minor_value(default_address.get("address_id"), 0)
if default_address
else 0
)
saved_markup = ""
if saved_addresses:
choices: list[str] = []
for address in saved_addresses:
address_id = int(address["address_id"])
revision = int(address["revision"])
checked = " checked" if address_id == selected_id else ""
default_badge = (
'Default'
if address.get("is_default")
else ""
)
choices.append(
f"""
"""
)
saved_markup = f"""
Only this selection will be ordered. Items already in your cart will remain there.
'
if str(checkout.get("checkout_mode") or "CART") == "BUY_NOW"
else ""
)
stripe_mode = payment_mode == PAYMENT_MODE_STRIPE_TEST
payment = checkout.get("payment")
if stripe_mode and not isinstance(payment, dict):
payment = {
"method": "stripe-test",
"method_label": "Stripe test Checkout",
"status": (
"PENDING"
if checkout.get("status") == "PAYMENT_PENDING"
else "NOT_STARTED"
),
}
place_action = (
"/gp/buy/stripe-checkout" if stripe_mode else "/gp/buy/place-order"
)
place_label = (
"Retry Stripe test Checkout"
if stripe_mode and checkout.get("status") == "PAYMENT_PENDING"
else "Pay with Stripe test Checkout"
if stripe_mode
else "Place your order"
)
place_copy = (
"You will continue to Stripe's hosted test page. The order is created "
"only after the server verifies a paid test Session."
if stripe_mode
else "By placing your order, you agree to this local simulation. No real charge is created."
)
body = f"""
{_checkout_steps("review")}
"""
return _checkout_layout("Amazon Checkout - Review your order", body, cart_count, account_name, body_class="checkout-review-page")
def stripe_payment_status_page(
checkout: dict[str, Any],
cart_count: int,
account_name: str | None,
*,
session_id: str,
state: str,
cancelled: bool,
) -> str:
safe_session_id = escape(session_id, quote=True)
normalized_state = str(state or "unpaid").casefold()
if normalized_state == "unavailable":
heading = "Stripe status is temporarily unavailable"
detail = (
"No order was created from this page. Your frozen checkout remains "
"locked so you can refresh safely when the test service is available."
)
elif normalized_state == "mismatch":
heading = "We could not verify this Stripe Session"
detail = (
"The Session did not match the server-owned amount, currency, "
"account, or frozen cart. No order was created."
)
elif cancelled:
heading = "You returned from Stripe test Checkout"
detail = (
"The Session is not paid. Expire it below to unlock the checkout, "
"or return to Stripe and complete the test payment."
)
else:
heading = "Stripe test payment is pending"
detail = (
"No order exists yet. Refreshing is safe; only a verified paid "
"Session can create the order."
)
cancel_form = (
'"
if normalized_state not in {"mismatch"}
else ""
)
refresh_href = (
"/gp/buy/stripe-return?"
+ urlencode({"session_id": session_id, **({"cancelled": "1"} if cancelled else {})})
)
body = f"""
{_checkout_steps("payment")}
"""
return _checkout_layout(
"Amazon Checkout - Stripe test payment",
body,
cart_count,
account_name,
body_class="checkout-payment-page",
)
def _shipment_markup(order: dict[str, Any]) -> str:
shipment = order.get("shipment")
if not isinstance(shipment, dict):
return '
Shipment preparation is pending.
'
raw_status = str(
shipment.get("lifecycle_status") or shipment.get("status") or "PREPARING"
)
status = escape(_order_status_label(raw_status))
carrier = escape(str(shipment.get("carrier") or "Local simulated carrier"))
tracking = escape(
str(
shipment.get("tracking_code")
or "Generated when the simulated shipment advances"
)
)
delivery = _delivery_label(shipment.get("delivery_method") or order.get("delivery_method"))
timestamps = []
for label, key in (
("Shipped", "shipped_at"),
("Delivered", "delivered_at"),
("Cancelled", "cancelled_at"),
):
value = shipment.get(key)
if value:
timestamps.append(
f"
{label}
{escape(str(value))}
"
)
return (
'
Local shipment simulation'
"No real carrier or parcel is connected to this order.
"
f'
Status
{status}
'
f"
Delivery
{escape(delivery)}
Carrier
{carrier}
"
f"
Tracking
{tracking}
{''.join(timestamps)}
"
)
def _order_status_label(status: Any) -> str:
labels = {
"PLACED": "Order placed",
"PREPARING": "Preparing for shipment",
"SHIPPED": "Shipped",
"DELIVERED": "Delivered",
"CANCELLED": "Cancelled",
"RETURN_REQUESTED": "Return requested",
"RETURN_RECEIVED": "Return received",
"RETURN_REFUNDED": "Return refunded",
"REQUESTED": "Return requested",
"RECEIVED": "Return received",
"REFUNDED": "Return refunded",
}
raw = str(status or "PREPARING")
return labels.get(raw, raw.replace("_", " ").title())
def _refunds_markup(order: dict[str, Any]) -> str:
refunds = order.get("refunds")
if not isinstance(refunds, list) or not refunds:
return ""
cards = []
for refund in refunds:
if not isinstance(refund, dict):
continue
kind = (
"Cancellation refund"
if refund.get("kind") == "CANCELLATION"
else "Return refund"
)
cards.append(
''
f"
{kind}{escape(str(refund.get('created_at') or ''))}
"
f"{money(_minor_value(refund.get('amount_minor')), str(refund.get('currency') or order.get('currency') or 'USD'))}"
f"{escape(str(refund.get('status') or 'COMPLETED').title())}"
""
)
if not cards:
return ""
return (
'
Refunds
'
'
Local refund simulation'
"This record models the order state only. No money was moved and no bank or card network was contacted.
"
f"{''.join(cards)}"
)
def _order_actions_markup(order: dict[str, Any]) -> str:
raw_order_id = str(order.get("order_id") or "")
order_id = escape(raw_order_id, quote=True)
tokens = order.get("action_tokens")
keys = order.get("action_idempotency_keys")
tokens = tokens if isinstance(tokens, dict) else {}
keys = keys if isinstance(keys, dict) else {}
actions: list[str] = []
if order.get("can_cancel") and tokens.get("cancel") and keys.get("cancel"):
actions.append(
'"
)
if order.get("can_return"):
href = (
"/gp/your-account/returns/create?orderID="
+ quote_plus(raw_order_id)
)
actions.append(
'
'
f'Return items'
'Start a whole-order return in this local simulation.
'
)
specs = _compare_specs(product)
product_specs.append(specs)
for normalized, (label, _) in specs.items():
spec_union.setdefault(normalized, label)
common_rows = "".join(
f'
{escape(label)}
{"".join(f"
{escape(value)}
" for value in values)}
'
for label, values in _compare_common_rows(selected)
)
spec_rows = ""
if spec_union:
rendered_spec_rows = []
for normalized, label in spec_union.items():
cells = "".join(
f"
{escape(specs.get(normalized, (label, '—'))[1])}
"
for specs in product_specs
)
rendered_spec_rows.append(
f'