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""" """ 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"""

Product image

{safe_alt}
""" return trigger, dialog def secure_transaction_dialog() -> str: """Explain the modeled checkout boundary without implying a live processor.""" return """

Secure transaction

Payment details are selected during checkout. You can review the delivery address, payment method, items, and order total before placing this local test order.

Review your cart
""" 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"""
""" def header( cart_count: int, search_value: str = "", account_name: str | None = None, active_department: str = "aps", all_menu_open: bool = False, ) -> str: value = escape(search_value, quote=True) delivery_label = current_delivery_label() short_name = account_name.strip().split()[0] if account_name and account_name.strip() else "" desktop_greeting = f"Hello, {escape(short_name)}" if short_name else "Hello, sign in" mobile_greeting = f"{escape(short_name)} ›" if short_name else "Sign in ›" account_href = ( "/gp/css/homepage.html" if short_name else "/ap/signin?openid.return_to=%2Fgp%2Fcss%2Fhomepage.html" ) account_auth = ( f"""
Welcome, {escape(short_name)}
""" if short_name else """
Sign in New customer? Start here.
""" ) account_markup = f""" """ department_options = "".join( f'' for department in SOURCE_DEPARTMENTS ) all_selected = " selected" if active_department in {"", "aps"} else "" department_links = source_department_navigation() all_menu_expanded = "true" if all_menu_open else "false" return f""" """ 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.

Change Address
""" def footer(account_name: str | None = None) -> str: signin_link = ( "" if account_name else 'Already a customer? Sign in' ) return """ """.format( logo=amazon_logo(), signin_link=signin_link, customer_service_href=CUSTOMER_SERVICE_HREF.replace("&", "&"), shipping_href=SHIPPING_POLICIES_HREF.replace("&", "&"), returns_href=RETURNS_REPLACEMENTS_HREF.replace("&", "&"), gift_cards_href=GIFT_CARDS_HREF.replace("&", "&"), conditions_href=CONDITIONS_OF_USE_HREF.replace("&", "&"), privacy_href=PRIVACY_NOTICE_HREF.replace("&", "&"), ) def layout( title: str, body: str, cart_count: int, *, search_value: str = "", body_class: str = "", extra_head: str = "", account_name: str | None = None, active_department: str = "aps", all_menu_open: bool = False, ) -> str: resolved_body_class = " ".join( part for part in (body_class, "all-menu-open" if all_menu_open else "") if part ) return f""" {escape(title)} {extra_head} {header(cart_count, search_value, account_name, active_department, all_menu_open)} {mobile_shipping_notice()} {body} {footer(account_name)} """ HOME_ASSET_ROOT = "/static/assets/source-current/2026-07-21/home" HOME_RAIL_FIXTURE_PATH = Path(__file__).resolve().parent / "fixtures" / "home-rails.json" HOME_COLLECTION_FIXTURE_PATH = ( Path(__file__).resolve().parent / "fixtures" / "home-collections.json" ) def _load_home_rail_fixture() -> dict[str, dict[str, Any]]: payload = json.loads(HOME_RAIL_FIXTURE_PATH.read_text(encoding="utf-8")) return {rail["key"]: rail for rail in payload["rails"]} HOME_RAILS_BY_KEY = _load_home_rail_fixture() def _load_home_collection_fixture() -> dict[str, dict[str, Any]]: payload = json.loads(HOME_COLLECTION_FIXTURE_PATH.read_text(encoding="utf-8")) if payload.get("schema") != "amazon-home-collections-fixture.v1": raise ValueError("unsupported home collection fixture schema") raw_groups = payload.get("groups") if not isinstance(raw_groups, list) or not raw_groups: raise ValueError("home collection fixture requires groups") groups: dict[str, dict[str, Any]] = {} for raw_group in raw_groups: if not isinstance(raw_group, dict): raise ValueError("home collection group must be an object") key = raw_group.get("key") title = raw_group.get("title") tiles = raw_group.get("tiles") if ( not isinstance(key, str) or not key or key in groups or not isinstance(title, str) or not title or not isinstance(tiles, list) or len(tiles) != 4 ): raise ValueError("invalid home collection group") normalized_tiles: list[dict[str, str]] = [] for tile in tiles: if not isinstance(tile, dict): raise ValueError(f"home collection {key} has an invalid tile") label = tile.get("label") asset_id = tile.get("assetId") if ( not isinstance(label, str) or not label or not isinstance(asset_id, str) or not asset_id ): raise ValueError(f"home collection {key} has incomplete tile evidence") normalized_tiles.append({"label": label, "asset_id": asset_id}) groups[key] = {"key": key, "title": title, "tiles": normalized_tiles} return groups HOME_COLLECTIONS_BY_KEY = _load_home_collection_fixture() HOME_CATEGORY_GROUPS_BY_KEY = load_home_category_groups( HOME_COLLECTION_FIXTURE_PATH.parent ) HOME_COLLECTION_QUERY_ALIASES: dict[str, tuple[str, int | None]] = { normalize_search_query(query): (key, None) for query, key in { "home arrivals": "home-arrivals", "kitchen products": "kitchen-appliances", "fashion": "fashion-trends", "home products": "elevated-spaces", "gaming merchandise": "gaming-merchandise", "watches": "most-loved-watches", "home": "home-finds", "beauty products": "beauty-discovery", }.items() } HOME_COLLECTION_LEGACY_SEARCH_TILES: dict[str, tuple[int, ...]] = { "fashion-less": (1, 2, 3, 4), "school-supplies": (3, 4), "fashion-trends": (1, 2, 3, 4), "fitness": (1, 2, 3), "wireless-tech": (2,), "gaming-merchandise": (1, 2, 4), "gaming-platforms": (1, 2, 3), "deal-categories": (2,), "most-loved-watches": (1, 2, 3, 4), } for _collection_key, _tile_indexes in HOME_COLLECTION_LEGACY_SEARCH_TILES.items(): _collection_group = HOME_COLLECTIONS_BY_KEY[_collection_key] for _tile_index in _tile_indexes: _collection_tile = _collection_group["tiles"][_tile_index - 1] HOME_COLLECTION_QUERY_ALIASES.setdefault( normalize_search_query(str(_collection_tile["label"])), (_collection_key, _tile_index), ) def _home_asset(asset_id: str) -> str: return f"{HOME_ASSET_ROOT}/{asset_id}.jpg" def home_collection_href(key: str, tile_index: int | None = None) -> str: """Return the Amazon search destination represented by a homepage tile. The captured homepage cards lead to ``/s`` result pages. The historical local collection URL remains accepted by the server as a redirect, but it is no longer emitted into public HTML or rendered as a separate product family. """ category_group = HOME_CATEGORY_GROUPS_BY_KEY.get(key) if category_group is None: raise ValueError(f"unknown home collection {key}") if tile_index is None: query = str(category_group["title"]) elif tile_index in range(1, 5): query = str(category_group["tiles"][tile_index - 1]["query"]) else: raise ValueError(f"invalid home collection tile {key}/{tile_index}") return f"/s?k={quote_plus(query)}" def home_collection_target_for_query( query: str, ) -> tuple[str, int | None] | None: """Resolve legacy homepage search URLs to their semantic collection.""" return HOME_COLLECTION_QUERY_ALIASES.get(normalize_search_query(query)) def _home_rail_destination(key: str) -> str: if key == "related-items": return "/s?k=portable+ssd" if key == "top-picks-singapore": return "/s?k=top+picks+singapore" department = source_department_for_rail(key) if department is not None: return f"/s?i={quote_plus(str(department['slug']))}" return f"/s?k={quote_plus(key.replace('-', ' '))}" def _home_single_card(title: str, asset_id: str, link_text: str, href: str) -> str: return f"""

{escape(title)}

{escape(title, quote=True)} {escape(link_text)}
""" def _home_quad_card( title: str, tiles: list[tuple[str, str] | tuple[str, str, str]], link_text: str, href: str, *, collection_key: str, ) -> str: group = HOME_COLLECTIONS_BY_KEY.get(collection_key) if group is None: raise ValueError(f"unknown home collection {collection_key}") expected_tiles = [ (str(tile["label"]), str(tile["asset_id"])) for tile in group["tiles"] ] supplied_tiles = [(str(tile[0]), str(tile[1])) for tile in tiles] if str(group["title"]) != title or expected_tiles != supplied_tiles: raise ValueError(f"home collection {collection_key} drifted from homepage") rendered_tiles = "" for tile_index, tile in enumerate(tiles, start=1): label, asset_id = tile[:2] tile_href = home_collection_href(collection_key, tile_index) rendered_tiles += ( f'{escape(label, quote=True)}' f'{escape(label)}' ) href = home_collection_href(collection_key) return f"""

{escape(title)}

{rendered_tiles}
{escape(link_text)}
""" def _home_product_rail( title: str, products: Iterable[dict[str, str]], extra_class: str = "", link_text: str = "", link_href: str = "", ) -> str: items = "".join( f'{escape(product[' for product in products ) action = ( f'{escape(link_text)}' if link_text and link_href else "" ) return f"""

{escape(title)}

{action}
{items}
""" def _home_frozen_rail(key: str) -> str: rail = HOME_RAILS_BY_KEY[key] extra_class = " home-related-rail" if key == "related-items" else "" return _home_product_rail( rail["title"], rail["items"], extra_class=extra_class, link_text="See all", link_href=_home_rail_destination(key), ) def home_page( products: list[dict[str, Any]], cart_count: int, account_name: str | None = None ) -> str: del products cards = "".join( ( _home_single_card("Get your game on", "4541d8781270e263", "Shop gaming", "/s?k=gaming"), _home_single_card("Must-haves for every student", "25ffc20ec0a7e38e", "Shop Back to School", "/s?k=school+supplies"), _home_quad_card("Shop Fashion for less", [("Jeans under $50", "014f2bdb67865e0e"), ("Tops under $25", "31686248cca236ec"), ("Dresses under $30", "b9b5c2175c9e968e"), ("Shoes under $50", "f760d9376ddef80d")], "See all deals", "/gp/goldbox/", collection_key="fashion-less"), _home_quad_card("Must-have school supplies", [("Backpacks", "13b4e86ff2941173"), ("Electronics", "864424c08dd196b8"), ("Stationery", "9752a198d4271456"), ("Fashion", "c6d42e4f6bd30f7d")], "Shop Back to School", "/s?k=school+supplies", collection_key="school-supplies"), _home_quad_card("New home arrivals under $50", [("Kitchen & dining", "4caab0b1d3f3ed6f"), ("Home improvement", "d821da00440eec1c"), ("Décor", "950f9fa40eca21de"), ("Bedding & bath", "cdeb1caaa6497025")], "Shop the latest from Home", "/s?k=home+arrivals", collection_key="home-arrivals"), _home_quad_card("Top categories in Kitchen appliances", [("Cooker", "49eee639f994b488"), ("Coffee", "b48141567982327c"), ("Pots and Pans", "9f3b26ba35bc8e01"), ("Kettles", "d1794b7faf501a9d")], "Explore all products in Kitchen", "/s?k=kitchen+products", collection_key="kitchen-appliances"), _home_quad_card("Fashion trends you like", [("Dresses", "f4963edd4e122be7"), ("Knits", "c0514a4ba72c5b37"), ("Jackets", "867dd3e0a203917a"), ("Jewelry", "779a6383af8ffb6e")], "Explore more", "/s?k=fashion", collection_key="fashion-trends"), _home_quad_card("Easy updates for elevated spaces", [("Baskets & hampers", "64f21735e1c74948"), ("Hardware", "369381e3dd82f9f8"), ("Accent furniture", "dc8f8bbc2c6b4bab"), ("Wallpaper & paint", "389bf293eaa51bc0")], "Shop home products", "/s?k=home+products", collection_key="elevated-spaces"), _home_frozen_rail("related-items"), _home_frozen_rail("best-sellers-home-kitchen"), _home_quad_card("Gear up to get fit", [("Clothing", "6938765e159953cd"), ("Trackers", "c84abc45d3c7831b"), ("Equipment", "4bcaecb91986cc37"), ("Deals", "6d06fd12fb426900")], "Discover more", "/s?k=weight+lifting", collection_key="fitness"), _home_quad_card("Have more fun with family", [("Outdoor play", "007d6dcf1fdb975a"), ("Learning toys", "616b49f5ba5b5080"), ("Action figures", "45496c7680c4f68c"), ("Pretend play", "b31a1ce1611d39bb")], "See more", "/s?i=toys-games", collection_key="family-fun"), _home_quad_card("Wireless Tech", [("Smartphones", "wireless-tech/smartphones", "/s?i=computers"), ("Watches", "wireless-tech/watches", "/s?k=watches"), ("Headphones", "wireless-tech/headphones", "/s?i=computers"), ("Tablets", "wireless-tech/tablets", "/s?i=computers")], "Discover more", "/s?i=computers", collection_key="wireless-tech"), _home_quad_card("Gaming merchandise", [("Apparel", "bdaf957e8276af10"), ("Hats", "14d4ecc4ed87b683"), ("Action figures", "66789d6ab1fe9905"), ("Mugs", "77748f7f125db3cf")], "See more", "/s?k=gaming+merchandise", collection_key="gaming-merchandise"), _home_frozen_rail("top-sellers-toys"), _home_frozen_rail("best-sellers-computers-accessories"), _home_quad_card("Level up your gaming", [("PC gaming", "1f00662f2c41fe99"), ("Xbox", "1915b416636972ea"), ("PlayStation", "1044f0abd1b0a9a4"), ("Nintendo", "308a8232dbd7f66b")], "Shop gaming", "/s?k=gaming", collection_key="gaming-platforms"), _home_quad_card("Deals on top categories", [("Books", "f806a7aed4925070"), ("Fashion", "b2eb0a31612bba2b"), ("Desktops", "59f62bc9e9953c91"), ("Beauty", "1a61cc11afe4a3d9")], "Explore all deals", "/gp/goldbox/", collection_key="deal-categories"), _home_quad_card("Level up your beauty routine", [("Makeup", "5d4f18f300b34f3f"), ("Brushes", "f83db64a2f3cbec8"), ("Sponges", "a753d6bf393e34c4"), ("Mirrors", "3197d03b8e86fb9c")], "See more", "/s?k=beauty", collection_key="beauty-routine"), _home_quad_card("Level up your PC here", [("Laptops", "c15c7d78fd314a2d"), ("PCs", "918f344527c4b4de"), ("Hard drives", "12237c942f7639ab"), ("Monitors", "47795f5c030aaad1")], "Shop now", "/s?k=computers", collection_key="pc-upgrades"), _home_frozen_rail("best-sellers-books"), _home_frozen_rail("top-picks-singapore"), _home_quad_card("Most-loved watches", [("Women", "a0aa517f7d0f803e"), ("Men", "8020e47a983015ab"), ("Girls", "34a6123442d40dd2"), ("Boys", "0570588e61329a69")], "Discover more", "/s?k=watches", collection_key="most-loved-watches"), _home_quad_card("Finds for Home", [("Kitchen", "79d09d346509aa4f"), ("Home décor", "a82abedd503127bb"), ("Dining", "834d20af59880114"), ("Smart home", "876c2616cc6fd466")], "See more", "/s?k=home", collection_key="home-finds"), _home_single_card("Transformers toys & more", "9341c0aa5ab587ad", "Shop now", "/s?i=toys-games"), _home_quad_card("Discover these beauty products for you", [("Skincare", "1a2952451fe8674c"), ("Makeup", "2b4ed40de0adcc4e"), ("Nails", "7f62214a5481cf69"), ("Fragrance", "5dbaa9ffe04c6573")], "Explore more", "/s?k=beauty+products", collection_key="beauty-discovery"), _home_frozen_rail("best-sellers-beauty-personal-care"), ) ) body = f"""
Shop Back to School: School essentials at every price Featured Amazon offer Featured Amazon deals Summer essentials
{cards}
""" return layout("Amazon.com. Spend less. Smile more.", body, cart_count, body_class="home-page", account_name=account_name) def home_product(product: dict[str, Any]) -> str: return f"""{escape(product['title'], quote=True)}{escape(product['brand'])}""" def best_product( product: dict[str, Any], rank: int, *, compact: bool = False, image_path: str | None = None, ) -> str: card_image = image_path or product["image_path"] return f"""
#{rank} {escape(product['title'], quote=True)} {escape(product['title'])} {product['rating']}★★★★★ {product['reviews']:,} {money(product['price_minor'], product['currency'])}
""" def best_sellers_root( products: list[dict[str, Any]], cart_count: int, account_name: str | None = None ) -> str: sections = [ "Best Sellers in Computers & Accessories", "Best Sellers in Electronics", "Best Sellers in Home & Kitchen", "Best Sellers in Books", "Best Sellers in Beauty & Personal Care", "Best Sellers in Sports & Outdoors", ] expanded = products + list(reversed(products)) rails = "".join( f"""

{escape(section)}

{''.join(best_product(p, i + 1, compact=True) for i, p in enumerate(expanded))}
See More
""" for section in sections ) body = f"""

Amazon Best Sellers

Our most popular products based on sales. Updated frequently.

{rails}
""" return layout("Amazon Best Sellers", body, cart_count, body_class="best-page", account_name=account_name) def external_ssd_best_sellers( ranking: list[dict[str, Any]], cart_count: int, account_name: str | None = None ) -> str: cards = "".join( best_product( product, int(product["rank"]), image_path=f"/static/assets/rank-{int(product['rank']):02d}-current.jpg", ) for product in ranking ) body = f"""

Amazon Best Sellers

Our most popular products based on sales. Updated frequently.

Best Sellers in External Solid State Drives

{cards}
""" return layout( "Amazon Best Sellers: Best External Solid State Drives", body, cart_count, body_class="ranking-list-page", account_name=account_name, ) def _home_collection_products( group: dict[str, Any], tile_index: int | None, products: Iterable[dict[str, Any]], ) -> list[dict[str, Any]]: """Return the dated category-card products bound to this exact tile.""" provided = [ dict(product) for product in products if product.get("category_key") == group["key"] and ( tile_index is None or product.get("category_index") == tile_index ) ] if provided: return provided return home_category_products( HOME_COLLECTION_FIXTURE_PATH.parent, str(group["key"]), tile_index, ) def home_collection_product_card(product: dict[str, Any]) -> str: asin = escape(str(product["asin"]), quote=True) title = escape(str(product["title"])) title_attr = escape(str(product["title"]), quote=True) href = f"/dp/{asin}" image_path = escape(str(product["image_path"]), quote=True) rating = str(product.get("rating") or "") reviews = int(product.get("reviews") or 0) rating_markup = ( f'' f'{escape(rating)} ★★★★★ ' f'({reviews:,})' if rating and reviews else "" ) return f"""
{title_attr}

{title}

{rating_markup}
{money(int(product["price_minor"]), str(product["currency"]))} {generic_add_to_cart_form(product, quantity_id=f'home-category-quantity-{str(product["asin"]).lower()}')}
See product details
""" 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"""
{escape(heading, quote=True)}

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[ {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.

{cards}
""" body = f"""
{focus}

Shop by category

{escape(str(group["title"]))}

Back to Amazon home
{choices}
{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'
{option_fields}
' 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 = ( '' 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"""
{escape(title, quote=True)}
{sponsored}{badge_markup}

{escape(title)}

{format_markup}
{rating_markup}
{money(int(product['price_minor']), str(product['currency']))} {grid_availability_markup}{grid_placement_markup} {generic_add_to_cart_form(product, quantity_id=f'search-quantity-{asin.lower()}', selected_options=product.get('default_selected_options'))}
{grid_compare_markup} See product details
""" return f"""
{escape(title, quote=True)}
{sponsored}{badge_markup}

{escape(title)}

{format_markup}{rating_markup}{money(int(product['price_minor']), str(product['currency']))}{availability_markup}{placement_markup}{generic_add_to_cart_form(product, quantity_id=f'search-quantity-{asin.lower()}', selected_options=product.get('default_selected_options'))}{compare_add_form(product, compact=True)}See product details
""" 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"""
{_search_state_hidden_fields(request)}
""" 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"""
{escape(title, quote=True)}

{escape(title)}

{rating_markup} {money(int(product['price_minor']), str(product['currency']))} {f'

{escape(delivery)}

' if delivery else ''}
""" def _department_landing_rail(title: str, products: list[dict[str, Any]]) -> str: return f"""

{escape(title)}

See more
{''.join(_department_compact_product_card(product) for product in products)}
""" def department_landing_page( page: SearchPage, cart_count: int, account_name: str | None = None, rail_products: Iterable[dict[str, Any]] = (), ) -> str: """Render the five captured Amazon department landing-page families.""" request = page.request slug = request.department content = DEPARTMENT_LANDING_CONTENT[slug] products = [dict(hit.product) for hit in page.items] supplied_rail_products = [dict(product) for product in rail_products] categories = tuple(str(label) for label in content["categories"]) tiles = _department_landing_tiles(slug, categories, products) sidebar_items = "".join( f'{escape(str(label))}' for label in content["sidebar"] ) sidebar = ( f'' if sidebar_items else "" ) hero_products = "".join( f'' for product in products[:3] ) hero = f"""

{escape(str(content['label']))}

{escape(str(content['hero']))}

Shop now
""" category_strip = f"""

{escape(str(content['category_heading']))}

{tiles}
""" primary_title = str(content["primary_rail"]) if slug == "computers" and supplied_rail_products: primary_title = "Shop Sandisk" primary = supplied_rail_products[:8] secondary = products[:8] else: primary = supplied_rail_products[:8] or products[:8] secondary = products[8:] rails = _department_landing_rail(primary_title, primary) if secondary: rails += _department_landing_rail(str(content["secondary_rail"]), secondary) body = f"""
{sidebar}
{category_strip} {hero} {rails} {_search_pagination(page)}
""" 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"""
{option_fields}
""" 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'

{reference_label}: {money(list_price, str(product["currency"]))}

' ) if ( isinstance(discount, int) and discount > 0 ): limited_label = ( 'Limited time deal' if product.get("limited_time_deal") else "" ) discount_markup = ( f'
-{discount}%{limited_label}
' ) image_alt = escape( str(product.get("image_alt") or product["title"]), quote=True ) return f"""
{image_alt}{_deals_quick_add_form(product)}
{discount_markup}{price}{reference_markup}{brand_markup}

{title}

{rating_markup}
""" def deals_page( deals_view: dict[str, Any], cart_count: int, account_name: str | None = None, ) -> str: """Render Deals with server-owned, copyable GET filters.""" products = deals_view.get("products") products = products if isinstance(products, list) else [] filters = deals_view.get("filters") filters = filters if isinstance(filters, dict) else {} result_count = int(deals_view.get("result_count") or 0) all_count = int(deals_view.get("all_count") or 0) active_count = int(deals_view.get("active_filter_count") or 0) cards = "".join(deals_product_card(product, filters) for product in products) theme_label = str(deals_view.get("theme_label") or "All deals") all_deals_active = not filters.get("theme") all_deals_current = ' aria-current="page"' if all_deals_active else "" theme_pills = [ f'All deals' ] for raw_theme in deals_view.get("theme_chips", ()): if not isinstance(raw_theme, (list, tuple)) or len(raw_theme) != 2: continue slug, label = str(raw_theme[0]), str(raw_theme[1]) active = filters.get("theme") == slug current = ' aria-current="page"' if active else "" theme_pills.append( f'{escape(label)}' ) primary_key = "todays-deals" if filters.get("theme") == "lightning-deals": primary_key = "lightning-deals" elif filters.get("theme") == "amazon-brands": primary_key = "amazon-brands" elif ( filters.get("max_price_text") == "50" and not filters.get("min_price_text") and not filters.get("theme") ): primary_key = "under-50" primary_tabs = ( ("todays-deals", "Today's Deals", "/gp/goldbox/"), ("lightning-deals", "Lightning Deals", "/gp/goldbox/?theme=lightning-deals"), ("under-50", "Deals under $50", "/gp/goldbox/?maxPrice=50"), ("amazon-brands", "Amazon Brands", "/gp/goldbox/?theme=amazon-brands"), ) primary_navigation_parts: list[str] = [] for key, label, href in primary_tabs: current = ' aria-current="page"' if key == primary_key else "" primary_navigation_parts.append( f'{escape(label)}' ) primary_navigation = "".join(primary_navigation_parts) department_rows = [ '' ] for department in deals_view.get("departments", ()): if not isinstance(department, dict): continue slug = str(department.get("slug") or "") department_rows.append( f'' ) selected_brands = set(filters.get("brands") or ()) brand_rows = [] for brand in deals_view.get("brands", ()): if not isinstance(brand, dict): continue label = str(brand.get("label") or "") brand_rows.append( f'' ) range_error = str(filters.get("range_error") or "") error_markup = ( f'' if range_error else "" ) no_results = "" if not cards: no_results = f"""

No deals match these filters

Clear the filters or choose a different price range.

Clear all filters
""" theme_hidden = ( f'' if filters.get("theme") else "" ) body = f"""

{escape(theme_label if filters.get('theme') else "Today's Deals")}

{result_count} deals in this selection

Today's Deals results

Showing {result_count} of {all_count} offers

{cards}
{no_results}
""" return layout( "Amazon.com - Today's Deals", body, cart_count, body_class="deals-page", account_name=account_name, ) def pdp_recommendation_rail(products: Iterable[dict[str, Any]]) -> str: unique: list[dict[str, Any]] = [] seen: set[str] = set() for product in products: asin = str(product.get("asin") or "") if not asin or asin in seen: continue unique.append(product) seen.add(asin) if len(unique) == 6: break if not unique: return "" cards = [] for product in unique: asin = str(product["asin"]) 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)} ★★★★★ ' f'({reviews:,})' if rating and reviews else "" ) cards.append( f"""
{escape(title, quote=True)}

{escape(title)}

{rating_markup} {money(int(product['price_minor']), str(product['currency']))} {generic_add_to_cart_form(product, quantity_id=f'recommendation-quantity-{asin.lower()}')}
""" ) return f"""

Products related to this item

{len(cards)} items
{''.join(cards)}
""" def unified_product_page( product: dict[str, Any], cart_count: int, account_name: str | None = None, reviews_html: str = "", *, flow_ready: bool = False, ) -> str: """Render the shared shopping-decision PDP skeleton for every ASIN.""" detail = product["pdp"] quote_data_attributes = _quote_data_attributes(product) title = escape(product["title"]) brand = escape(product["brand"]) brand_attr = escape(product["brand"], quote=True) price_whole, price_cents = divmod(product["price_minor"], 100) currency_symbol = "$" if product["currency"] == "USD" else escape(product["currency"]) gallery_paths = [escape(path, quote=True) for path in detail["gallery"]] full_view_trigger, full_view_dialog = pdp_full_view_controls( str(detail["gallery"][0]), str(product["title"]) ) thumbnail_paths = [ escape(path, quote=True) for path in detail.get("thumbnail_paths", detail["gallery"]) ] if len(thumbnail_paths) != len(gallery_paths): thumbnail_paths = gallery_paths more_count = int(detail.get("gallery_more_count", 0)) visible_thumbnail_count = max( 1, min(int(detail.get("visible_thumbnail_count", len(gallery_paths))), len(gallery_paths)), ) gallery_buttons: list[str] = [] for index, (gallery_path, thumbnail_path) in enumerate( zip( gallery_paths[:visible_thumbnail_count], thumbnail_paths[:visible_thumbnail_count], ), 1, ): is_more = more_count and index == visible_thumbnail_count classes = "pdp-thumbnail gallery-more" if is_more else "pdp-thumbnail" label = ( f"View {more_count} more product images" if is_more else f"View product image {index}" ) overlay = f"{more_count}+" if is_more else "" current = ' aria-current="true"' if index == 1 else "" gallery_buttons.append( f'' ) gallery_images = escape("|".join(gallery_paths), quote=True) video_count = int(detail.get("video_count", 0)) video_thumbnail = escape(detail.get("video_thumbnail", gallery_paths[0]), quote=True) brand_logo = escape(detail.get("brand_logo", ""), quote=True) specs = "".join( f"
{escape(str(label))}
{escape(str(value))}
" for label, value in detail.get("specs", []) ) about_items = "".join( f"
  • {escape(str(item))}
  • " for item in detail.get("about", []) ) specs_block = ( f'
    {specs}
    ' if specs else "" ) if about_items: about_block = f'

    About this item

    ' else: about_block = ( '

    About this item

    ' '

    Review the product information and selected buying options for this item.

    ' ) primary_option_label = str(detail.get("primary_option_label", "Digital Storage Capacity")) primary_option_value = str(detail.get("primary_option_value", product["capacity"])) selected_options = { str(group["label"]): str(group["default"]) for group in option_groups_from_detail(detail, product) } embedded_defaults = product.get("default_selected_options") if isinstance(embedded_defaults, dict): selected_options = { str(label): str(value) for label, value in embedded_defaults.items() } primary_options = detail.get( "primary_options", detail.get("capacity_options", [primary_option_value]), ) capacity_buttons = "".join( f'" for value in primary_options ) secondary_option_label = str(detail.get("secondary_option_label", "Color")) secondary_option_value = str(detail.get("secondary_option_value", product["color"])) color_card_parts: list[str] = [] for option in detail.get("color_options", []): selected = option["name"] == product["color"] offer_text = option.get("offer_copy") or money( option.get("price_minor"), product["currency"] ) classes = "swatch-card selected" if selected else "swatch-card" color_card_parts.append( f'' ) color_cards = "".join(color_card_parts) secondary_option_block = ( f'

    {escape(secondary_option_label)}: ' f'{escape(secondary_option_value)}

    ' + (f'
    {color_cards}
    ' if color_cards else "") if secondary_option_value else "" ) primary_option_block = ( f'

    {escape(primary_option_label)}: ' f'{escape(primary_option_value)}

    ' + (f'
    {capacity_buttons}
    ' 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'

    {escape(group_label)}: ' f'{escape(group_value)}

    ' f'{"".join(group_buttons)}
    ' ) option_blocks = choice_groups_markup or (secondary_option_block + primary_option_block) retention_note = "" video_slot = ( '
    {video_count} VIDEOS
    ' if video_count else "" ) badge_class = "best-seller-badge" if detail.get("badge_style") == "best-seller" else "choice-badge" badge = ( f'{escape(product["badge"])}' if product.get("badge") else "" ) deal_badge = ( f'{escape(str(detail["deal_badge"]))}' if detail.get("deal_badge") else "" ) discount = ( f'-{int(detail["discount_percent"])}% ' if detail.get("discount_percent") else "" ) unit_price = ( f'{escape(str(detail["unit_price_copy"]))}' if detail.get("unit_price_copy") else "" ) list_price = ( f'

    List Price: {money(product["list_price_minor"], product["currency"])}

    ' if product.get("list_price_minor") is not None else "" ) breadcrumb_labels = detail.get( "breadcrumb", ["Electronics", "Computers & Accessories", "Data Storage", "External Solid State Drives"], ) breadcrumb_links = "›".join( f'{escape(str(label))}' for label in breadcrumb_labels ) raw_byline = detail.get("byline") if raw_byline is None: raw_byline = f"Visit the {product['brand']} Store" byline = escape(str(raw_byline)) compact_brand_logo = bool(detail.get("compact_brand_logo")) brand_logo_class = "samsung-brand compact-brand-logo" if compact_brand_logo else "samsung-brand" brand_logo_width = 36 if compact_brand_logo else 158 brand_logo_height = 36 if compact_brand_logo else 18 brand_href = escape( shopping_browse_href(str(product["brand"]), str(detail.get("page_category", "Electronics"))), quote=True, ) brand_logo_markup = ( f'' f'{brand_attr}' if brand_logo else "" ) byline_markup = ( f'
    {byline}
    ' 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'
    {source_rating} ' f'★★★★★ ' f'({source_reviews:,})
    ' ) 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'

    {escape(str(source_review_copy))} ' f'Customer reviews

    ' if isinstance(source_review_copy, str) and source_review_copy else ( f'' "Customer reviews" ) ) bought_markup = ( f'

    {escape(str(detail["bought"]))}

    ' if detail.get("bought") else "" ) if detail.get("title_first"): identity_header = ( f'

    {title}

    {byline_markup}{rating_markup}' f'{badge}{bought_markup}
    ' ) else: identity_header = ( f'{brand_logo_markup}{byline_markup}

    {title}

    ' f'{rating_markup}{badge}{bought_markup}
    ' ) fulfillment_rows: list[str] = [] for key, label in (("shipper", "Ships from"), ("seller", "Sold by")): if detail.get(key): fulfillment_rows.append( f"
    {label}
    {escape(str(detail[key]))}
    " ) for key, label in ( ("returns", "Returns"), ("support", "Support"), ("payment", "Payment"), ("gift_options", "Gift options"), ): if detail.get(key): copy = escape(str(detail[key])) if key == "returns": action = f'{copy}' elif key == "support": action = f'{copy}' elif key == "payment": action = ( '' ) else: action = f'{copy}' fulfillment_rows.append(f"
    {label}
    {action}
    ") seller_certification = ( f'

    Seller Certifications: ' f'{escape(str(detail["seller_certification"]))}

    ' if detail.get("seller_certification") else "" ) fulfillment = ( f"
    {''.join(fulfillment_rows)}
    {seller_certification}" if fulfillment_rows or seller_certification else "" ) secure_transaction_trigger = ( "" if detail.get("payment") else ( '' ) ) page_category = str(detail.get("page_category", "Electronics")) product_summary = escape( str( detail.get( "product_summary", f"{product['brand']} portable storage · {product['capacity']} · {product['color']}", ) ) ) video_description = escape( str(detail.get("video_description", f"{product['brand']} product overview")) ) category_subnav_markup = "" category_subnav = detail.get("category_subnav", []) if category_subnav: category_subnav_links = "".join( ( f'{escape(str(label))}' if index == 0 else f'{escape(str(label))}' ) for index, label in enumerate(category_subnav) ) category_subnav_markup = ( f'" ) top_promo_image = escape( str( detail.get( "top_promo_image", "/static/assets/source-current/2026-07-21/pdp-t7/international-promo.png", ) ), quote=True, ) top_promo_alt = escape( str(detail.get("top_promo_alt", "Shop top categories that ship internationally")), quote=True, ) top_promo_markup = ( f'' f'{top_promo_alt}' ) other_sellers_note = "" if detail.get("show_other_sellers_note") is True: other_sellers_note = ( '

    Available at a lower price from other sellers that may not offer ' "free Prime shipping.

    " ) fastest_delivery = ( f'

    {escape(str(detail["fastest_delivery_copy"]))}

    ' if detail.get("fastest_delivery_copy") else "" ) raw_other_sellers_copy = detail.get("other_sellers_copy") other_sellers_copy = ( escape(str(raw_other_sellers_copy)) if isinstance(raw_other_sellers_copy, str) and raw_other_sellers_copy.strip() else "" ) other_sellers_box = ( '

    Other sellers on Amazon

    ' f'

    {other_sellers_copy}

    ' if detail.get("show_other_sellers_box") is True and other_sellers_copy else "" ) important_information = detail.get("important_information", {}) important_information_markup = "" if important_information: warning = escape(str(important_information.get("warning", ""))) safety = escape(str(important_information.get("safety_information", ""))) warning_markup = f'

    WARNING: {warning}

    ' if warning else "" safety_markup = f'

    Safety Information

    {safety}

    ' if safety else "" important_information_markup = ( f'

    Important information

    ' f"{warning_markup}{safety_markup}
    " ) gallery_layout_class = "" if detail.get("wide_gallery"): gallery_layout_class = " wide-gallery-pdp-main" elif detail.get("large_gallery"): gallery_layout_class = " large-gallery-pdp-main" elif detail.get("classic_gallery"): gallery_layout_class = " classic-gallery-pdp-main" international_returns = ( f'FREE International Returns⌄' if detail.get("show_international_returns", True) else "" ) quantity_max = max(1, min(int(detail.get("quantity_max", 3)), 30)) compare_form = compare_add_form(product) if flow_ready and product["asin"] == TARGET_ASIN: cart_form = ( f'
    ' f'' '' '
    ' ) else: cart_form = generic_add_to_cart_form( product, quantity_max=quantity_max, quantity_id="detail-quantity", button_class="detailed-add-to-cart", selected_options=selected_options, ) detail_rows = "".join( f"{escape(str(label))}{escape(str(value))}" for label, value in detail.get("specs", []) ) detail_table = ( f'{detail_rows}
    ' if detail_rows else "" ) recommendations = pdp_recommendation_rail( product.get("recommendations", []) if isinstance(product.get("recommendations"), list) else [] ) mobile_identity_header = identity_header.replace( 'id="productTitle"', 'id="mobileProductTitle"', 1 ) body = f"""
    {category_subnav_markup} {top_promo_markup}
    {mobile_identity_header}
    {identity_header}
    {deal_badge}
    {discount}{currency_symbol}{price_whole:,}{price_cents:02d}{unit_price}
    {list_price} {international_returns}

    {escape(detail.get('shipping_copy', 'Ships to Singapore'))} Details⌄

    Sales taxes may apply at checkout

    {other_sellers_note} {option_blocks} {retention_note} {specs_block} {about_block}
    {full_view_dialog} {secure_transaction_dialog()}

    Videos for this product

    {brand_attr} product video still

    {video_description}

    Product information

    {product_summary}

    {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"""

    Shopping Cart

    {items}

    Subtotal ({cart_count} items): {money(subtotal, currency)}

    """ else: empty_actions = ( '
    Continue shopping
    ' if account_name else '
    Sign in to your accountSign up now
    ' ) active_content = f"""

    Your Amazon Cart is empty

    Shop today's deals{empty_actions}
    """ 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.

    {recommendations}
    """ return layout("Amazon.com Shopping Cart", body, cart_count, body_class="cart-page", account_name=account_name) def cart_added_page( product: dict[str, Any], lines: list[dict[str, Any]], cart_count: int, account_name: str | None = None, recommendation_products: Iterable[dict[str, Any]] = (), ) -> str: """Render the common Amazon-style Add to Cart confirmation state.""" subtotal = sum( int(line["price_minor"]) * int(line["quantity"]) for line in lines ) currency = str(product.get("currency") or "USD") options = selected_options_markup( product, css_class="cart-added-product-options" ) product_path = product_href(product) recommendations = list(recommendation_products)[:6] desktop_recommendations = cart_recommendations( recommendations, id_prefix="cart-added-desktop" ) mobile_recommendations = cart_recommendations( recommendations, id_prefix="cart-added-mobile" ) body = f"""
    {escape(str(product['title']), quote=True)}

    Added to Cart

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

    {options}

    In Stock

    Continue shopping
    ×

    Added to your cart

    Discover additional products

    {mobile_recommendations}
    """ return layout( "Amazon.com: Added to Cart", body, cart_count, body_class="cart-page cart-added-page", account_name=account_name, ) def cart_recommendations( products: Iterable[dict[str, Any]], *, id_prefix: str = "cart" ) -> str: unique: list[dict[str, Any]] = [] seen: set[str] = set() for product in products: asin = str(product.get("asin") or "") if not asin or asin in seen: continue unique.append(product) seen.add(asin) if len(unique) == 6: break if not unique: return "" cards: list[str] = [] for product in unique: asin = str(product["asin"]) title = str(product["title"]) href = product_href(product) rating = str(product.get("rating") or "").strip() reviews = int(product.get("reviews") or 0) rating_markup = ( f'
    ★★★★★ ' f'{reviews:,}
    ' if rating and reviews else "" ) cards.append( f"""
    {escape(title, quote=True)} {escape(title)} {rating_markup} {money(int(product['price_minor']), str(product['currency']))}
    Delivery and shipping shown at checkout
    """ ) cards_markup = "".join(cards) return f"""

    Customers Who Bought Items in Your Recent History Also Bought

    Page 1 of 1
    {cards_markup}
    """ def selected_options_markup( payload: dict[str, Any], *, css_class: str = "selected-product-options" ) -> str: raw_options = payload.get("selected_options") if not isinstance(raw_options, dict) or not raw_options: return "" pairs = "".join( f'
    {escape(str(label))}:
    {escape(str(value))}
    ' for label, value in raw_options.items() if isinstance(label, str) and isinstance(value, str) ) return f'
    {pairs}
    ' if pairs else "" def cart_line(line: dict[str, Any], *, saved: bool = False) -> str: asin = escape(str(line["asin"]), quote=True) raw_line_id = str(line["line_id"]) line_id = escape(raw_line_id, quote=True) title = escape(str(line["title"])) title_attr = escape(str(line["title"]), quote=True) image_path = escape(str(line["image_path"]), quote=True) href = escape(product_href(line), quote=True) quantity = max(1, min(int(line.get("quantity", 1)), 30)) currency = str(line.get("currency", "USD")) if saved: controls = f""" Quantity: {quantity}
    """ else: quantity_options = "".join( f'' for value in range(1, 31) ) quantity_id = escape(f"cart-quantity-{raw_line_id}", quote=True) controls = f"""
    """ state_class = " saved-cart-line" if saved else "" stock_copy = "Saved for later" if saved else "In Stock" options_markup = selected_options_markup(line, css_class="cart-line-options") return f"""
    {title_attr}

    {title}

    {options_markup}

    {stock_copy}

    FREE International Returns

    {controls}
    {money(int(line["price_minor"]), currency)}
    """ def signin_page(cart_count: int, destination: str = "Your Account") -> str: body = f"""

    Sign in or create account

    By continuing, you agree to Amazon's Conditions of Use and Privacy Notice.

    Need help?Forgot your password?
    """ return layout("Amazon Sign-In", body, cart_count, body_class="signin-page") def boundary_page( title: str, copy: str, cart_count: int, account_name: str | None = None, ) -> str: body = f"""

    {escape(title)}

    {escape(copy)}

    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""" {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.

    Review delivery location

    Where to find an order's delivery status

    After placing an order, its selected delivery method, shipment status, carrier, and tracking reference appear in Your Orders.

    Open Your Orders
    View your cartBack to Customer Service
    """ 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.

    Continue shoppingBack to Customer Service
    """ 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.

    Continue shoppingRead the Conditions of Use
    """ 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. 1
      Open Your Orders

      Sign in and locate the order that contains the item.

    2. 2
      Wait for simulated delivery

      The Return items action appears on eligible order details after the local shipment reaches Delivered.

    3. 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.

    {order_action}Search return help
    """ 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.
    {account_action}Open account tools Gift Card helpSearch Customer Service Today's DealsBrowse current offers

    Shop gifts by department

    {department_cards}

    Questions about Gift Cards?

    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)}

    """ 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.

    """ return layout( "Amazon.com - Choose your delivery location", body, cart_count, body_class="boundary-page navigation-landing-page", account_name=account_name, ) def account_page(account: dict[str, Any], cart_count: int) -> str: display_name = str(account.get("display_name", "Customer")) body = f"""

    Hello, {escape(display_name)}

    You are signed in to your local Amazon account.

    """ return layout( "Amazon.com - Your Account", body, cart_count, body_class="boundary-page account-page", account_name=display_name, ) def _address_country_options(address: dict[str, Any]) -> str: country_code = str(address.get("country_code") or "SG").upper() options = "".join( f'' for code, label in SUPPORTED_DELIVERY_COUNTRIES ) if country_code not in {code for code, _ in SUPPORTED_DELIVERY_COUNTRIES}: options = ( f'' + options ) return options def _address_input_fields( address: dict[str, Any], account_name: str | None, *, id_prefix: str ) -> str: full_name = str(address.get("full_name") or account_name or "") prefix = escape(id_prefix, quote=True) return f""" """ def address_book_page( addresses: list[dict[str, Any]], cart_count: int, account_name: str, *, status: str | None = None, error: str | None = None, ) -> str: status_messages = { "added": "Address added.", "updated": "Address updated.", "deleted": "Address removed from your address book.", "default": "Default address updated.", } notice = ( f'
    {escape(status_messages[status])}
    ' if status in status_messages else "" ) error_markup = ( f'' if error else "" ) cards: list[str] = [ 'Add address' ] for address in addresses: address_id = int(address["address_id"]) revision = int(address["revision"]) default_badge = ( '
    Default
    ' if address.get("is_default") else "" ) set_default = ( "" if address.get("is_default") else f"""
    """ ) cards.append( f"""
    {default_badge} {_address_markup(address)}
    Edit {set_default}
    """ ) body = f"""

    Your Addresses

    Choose the default used first during checkout.

    {notice}{error_markup}
    {"".join(cards)}
    """ return layout( "Amazon.com - Your Addresses", body, cart_count, body_class="address-book-page", account_name=account_name, ) def address_form_page( address: dict[str, Any] | None, cart_count: int, account_name: str, ) -> str: current = address if isinstance(address, dict) else {} editing = bool(current) title = "Edit address" if editing else "Add a new address" action = "/a/addresses/update" if editing else "/a/addresses/create" hidden = "" if editing: hidden = ( f'' f'' ) default_control = ( '

    ' 'Default addressTo change it, set another saved address as default.

    ' if editing and current.get("is_default") else '' ) body = f"""

    {escape(title)}

    {hidden} {_address_input_fields(current, account_name, id_prefix="address-book")} {default_control}
    """ return layout( f"Amazon.com - {title}", body, cart_count, body_class="address-form-page", account_name=account_name, ) def _minor_value(value: Any, default: int = 0) -> int: try: return int(value) except (TypeError, ValueError): return default def _checkout_items(checkout: dict[str, Any]) -> list[dict[str, Any]]: raw_items = checkout.get("items", []) if not isinstance(raw_items, list): return [] return [item for item in raw_items if isinstance(item, dict)] def _checkout_address(checkout: dict[str, Any]) -> dict[str, Any]: address = checkout.get("address") return address if isinstance(address, dict) else {} def _checkout_layout( title: str, body: str, cart_count: int, account_name: str | None, *, body_class: str, ) -> str: short_name = account_name.strip().split()[0] if account_name and account_name.strip() else "" greeting = f"Hello, {escape(short_name)}" if short_name else "Secure checkout" item_label = "item" if cart_count == 1 else "items" return f""" {escape(title)}

    Checkout ({cart_count} {item_label})

    {greeting}Local secure checkout
    {body} """ def _checkout_steps(current: str) -> str: steps = ( ("address", "Shipping address"), ("delivery", "Delivery options"), ("payment", "Payment"), ("review", "Review items"), ) positions = {name: index for index, (name, _) in enumerate(steps)} current_position = positions.get(current, len(steps)) items = [] for index, (name, label) in enumerate(steps): state = "current" if index == current_position else "complete" if index < current_position else "upcoming" marker = "✓" if state == "complete" else str(index + 1) current_attribute = ' aria-current="step"' if state == "current" else "" items.append( f'
  • {marker}{escape(label)}
  • ' ) return f'' def _checkout_item_rows(checkout: dict[str, Any]) -> str: rows: list[str] = [] currency = str(checkout.get("currency") or "USD") for item in _checkout_items(checkout): asin = escape(str(item.get("asin", "")), quote=True) title = escape(str(item.get("title", "Item"))) title_attr = escape(str(item.get("title", "Item")), quote=True) image_path = escape(str(item.get("image_path", "")), quote=True) quantity = max(1, _minor_value(item.get("quantity"), 1)) item_currency = str(item.get("currency") or currency) unit_price = _minor_value(item.get("price_minor")) line_total = _minor_value(item.get("line_total_minor"), unit_price * quantity) href = f"/dp/{asin}" if asin else "/" options_markup = selected_options_markup( item, css_class="checkout-item-options" ) image = ( f'{title_attr}' if image_path else '' ) rows.append( f'
    {image}
    {title}{options_markup}Quantity: {quantity}
    {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 ( '' ) if notice == "payment-declined": return ( '' ) 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 ( '' ) 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"""

    Your addresses

    Manage addresses
    {"".join(choices)}
    or add a new address
    """ body = f"""
    {_checkout_steps("address")}

    Choose a shipping address

    {_checkout_reconciliation_notice(checkout)} {saved_markup}

    Add a new address

    {_address_input_fields({}, account_name, id_prefix="checkout-new-address")}
    {_checkout_summary(checkout)}
    """ return _checkout_layout("Amazon Checkout - Shipping address", body, cart_count, account_name, body_class="checkout-address-page") def checkout_delivery_page( checkout: dict[str, Any], cart_count: int, account_name: str | None ) -> str: selected = str(checkout.get("delivery_method") or "standard").lower() body = f"""
    {_checkout_steps("delivery")}

    Choose your delivery option

    Delivering to

    {_address_markup(_checkout_address(checkout))}
    {_checkout_summary(checkout)}
    """ return _checkout_layout("Amazon Checkout - Delivery options", body, cart_count, account_name, body_class="checkout-delivery-page") def checkout_payment_page( checkout: dict[str, Any], cart_count: int, account_name: str | None, *, payment_mode: str = "local-sandbox", ) -> str: if payment_mode == PAYMENT_MODE_STRIPE_TEST: body = f"""
    {_checkout_steps("payment")}

    Select a payment method

    {_checkout_reconciliation_notice(checkout)}
    Stripe test environment

    Card and Link details are entered only on Stripe's hosted test Checkout page. No live key, real charge, Amazon order, or real fulfillment is used.

    {_checkout_summary(checkout)}
    """ return _checkout_layout( "Amazon Checkout - Payment", body, cart_count, account_name, body_class="checkout-payment-page", ) payment_choices = "".join( '' for method in public_payment_methods() ) body = f"""
    {_checkout_steps("payment")}

    Select a payment method

    {_checkout_reconciliation_notice(checkout)}
    {payment_choices}
    {_checkout_summary(checkout)}
    """ return _checkout_layout("Amazon Checkout - Payment", body, cart_count, account_name, body_class="checkout-payment-page") def checkout_review_page( checkout: dict[str, Any], cart_count: int, account_name: str | None, *, payment_mode: str = "local-sandbox", ) -> str: idempotency_key = escape(str(checkout.get("idempotency_key") or checkout.get("idempotencyKey") or ""), quote=True) delivery = _delivery_label(checkout.get("delivery_method")) buy_now_notice = ( '
    Buy Now checkout' '

    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")}

    Review your order

    {_simulation_notice(checkout)} {buy_now_notice}

    Shipping address

    {_address_markup(_checkout_address(checkout))}

    Delivery option

    {escape(delivery)}

    Payment method

    {_payment_markup(payment)}

    Items

    {_checkout_item_rows(checkout)}

    {escape(place_copy)}

    {_checkout_summary(checkout)}
    """ 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 = ( '
    ' f'' '
    " 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")}

    {escape(heading)}

    Stripe test environment

    {escape(detail)}

    Refresh payment status

    {cancel_form}
    {_checkout_summary(checkout)}
    """ 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( '
    ' f'' f'' f'' '' 'Available before this simulated shipment advances. A completed local refund record will be created.' "
    " ) 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.
    ' ) return_request = order.get("return_request") if isinstance(return_request, dict): raw_return_id = str(return_request.get("return_request_id") or "") href = "/gp/your-account/returns/details?returnID=" + quote_plus( raw_return_id ) actions.append( '
    ' f'View return details' f'{escape(_order_status_label(return_request.get("status")))}
    ' ) if not actions: return "" return ( '

    Order actions

    ' f'
    {"".join(actions)}
    ' ) def _local_email_markup(order: dict[str, Any]) -> str: email = order.get("email") nested_status = email.get("status") if isinstance(email, dict) else None status = str( nested_status or order.get("email_status") or order.get("email_notification_status") or "Queued in local email outbox" ) if status == "LOCAL_ONLY": heading = "Local email notification" detail = "Stored only in the protected local outbox; no external email was sent." elif status == "SMTP_SENT": heading = "Email notification" detail = "The configured SMTP service accepted the order confirmation." elif status == "SMTP_FAILED": heading = "Email notification" heading = "Email notification needs attention" detail = "The SMTP attempt failed. Provider details are not exposed on this page." else: heading = "Email notification" detail = "Queued for the configured SMTP service; refresh to check again." raw_order_id = str(order.get("order_id") or "") detail_href = "/gp/your-account/order-details?" + urlencode( {"orderID": raw_order_id} ) actions: list[str] = [] if status == "SMTP_PENDING": actions.append( f'Refresh email status' ) if ( status == "SMTP_FAILED" and isinstance(email, dict) and bool(email.get("can_retry")) ): actions.append( '
    ' f'' '' '
    ' ) action_markup = ( f'{"".join(actions)}' if actions else "" ) return ( '
    ' f'{heading}{escape(status)} · {escape(detail)}' f'{action_markup}
    ' ) def order_confirmation_page( order: dict[str, Any], cart_count: int, account_name: str | None ) -> str: order_id = escape(str(order.get("order_id") or "Pending")) raw_status = str(order.get("status") or "PREPARING") status = escape(_order_status_label(raw_status)) created_at = escape(str(order.get("created_at") or "Just now")) currency = str(order.get("currency") or "USD") order_total = money(_minor_value(order.get("total_minor")), currency) heading = ( "Order placed, thank you!" if raw_status == "PREPARING" else _order_status_label(raw_status) ) success_mark = "✓" if raw_status not in {"CANCELLED"} else "×" body = f"""
    {_checkout_steps("confirmation")}

    {escape(heading)}

    Order {order_id} · {created_at}

    {status}
    {_simulation_notice(order)}

    Shipping to

    {_address_markup(_checkout_address(order))}

    Shipment

    {_shipment_markup(order)}

    Order items

    {_checkout_item_rows(order)}

    Payment

    {_payment_markup(order.get("payment"))}

    Order total: {order_total}

    {_order_actions_markup(order)} {_refunds_markup(order)}
    {_local_email_markup(order)}
    View your ordersContinue shopping
    """ return _checkout_layout("Amazon.com - Order placed", body, cart_count, account_name, body_class="order-confirmation-page") def order_history_page( orders: list[dict[str, Any]], cart_count: int, account_name: str | None ) -> str: order_cards: list[str] = [] for order in orders: if not isinstance(order, dict): continue raw_order_id = str(order.get("order_id") or "Pending") order_id = escape(raw_order_id) details_href = f"/gp/your-account/order-details?orderID={quote_plus(raw_order_id)}" status = escape(_order_status_label(order.get("status"))) created_at = escape(str(order.get("created_at") or "Recently")) currency = str(order.get("currency") or "USD") total = money(_minor_value(order.get("total_minor")), currency) order_cards.append( f"""
    Order placed
    {created_at}
    Total
    {total}
    Ship to
    {escape(str(_checkout_address(order).get('full_name') or account_name or 'Customer'))}

    Order # {order_id}View order details

    {status}

    {_delivery_label(order.get('delivery_method'))}
    {_checkout_item_rows(order)}

    Shipment

    {_shipment_markup(order)}
    {_order_actions_markup(order)}{_refunds_markup(order)}
    {_local_email_markup(order)}
    """ ) if order_cards: content = "".join(order_cards) else: content = '

    No orders yet

    Orders placed through the local simulated checkout will appear here.

    Start shopping
    ' body = f"""

    Your Orders

    Local simulated order history

    Your Account
    {content}
    """ return layout( "Amazon.com - Your Orders", body, cart_count, body_class="orders-page", account_name=account_name, ) def return_request_page( order: dict[str, Any], cart_count: int, account_name: str | None ) -> str: raw_order_id = str(order.get("order_id") or "") 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 {} reason_options = ( ("DAMAGED", "Item or package arrived damaged"), ("DEFECTIVE", "Item is defective or does not work"), ("NOT_AS_DESCRIBED", "Item was not as described"), ("WRONG_ITEM", "Wrong item was received"), ("NO_LONGER_NEEDED", "No longer needed"), ) options = "".join( f'' for code, label in reason_options ) body = f"""

    Return items

    Local return simulationThis workflow records states only. It does not create a real return label, pickup, shipment, or refund.

    Items in this return

    The current clone returns the entire simulated order together.

    {_checkout_item_rows(order)}
    """ return _checkout_layout( "Amazon Returns Center - Return items", body, cart_count, account_name, body_class="return-request-page", ) def return_details_page( order: dict[str, Any], cart_count: int, account_name: str | None ) -> str: request = order.get("return_request") if not isinstance(request, dict): return error_page("That return request is unavailable.", cart_count, 404) request_id = escape(str(request.get("return_request_id") or "")) order_id = escape(str(order.get("order_id") or "")) reason_labels = { "DAMAGED": "Item or package arrived damaged", "DEFECTIVE": "Item is defective or does not work", "NOT_AS_DESCRIBED": "Item was not as described", "WRONG_ITEM": "Wrong item was received", "NO_LONGER_NEEDED": "No longer needed", } item_rows = [] for item in request.get("items", []): if not isinstance(item, dict): continue item_rows.append( '
  • ' f"{escape(str(item.get('title') or item.get('asin') or 'Order item'))}" f"Qty: {escape(str(item.get('quantity') or 1))}
  • " ) note = str(request.get("customer_note") or "").strip() note_markup = ( f'

    Your comments

    {escape(note)}

    ' if note else "" ) body = f"""

    {escape(_order_status_label(request.get('status')))}

    Return {request_id} for order {order_id}

    Local simulation

    No real return or refundThis page tracks only the clone's simulated state. No label, carrier, warehouse, bank, or card network is connected.

    Return summary

    Status
    {escape(_order_status_label(request.get('status')))}
    Reason
    {escape(reason_labels.get(str(request.get('reason_code')), str(request.get('reason_code') or 'Not specified')))}
    Requested
    {escape(str(request.get('created_at') or ''))}
    Updated
    {escape(str(request.get('updated_at') or ''))}

    Items

      {''.join(item_rows)}
    {note_markup} {_refunds_markup(order)}
    View order detailsYour Orders
    """ return _checkout_layout( "Amazon Returns Center - Return details", body, cart_count, account_name, body_class="return-details-page", ) def _compare_detail(product: dict[str, Any]) -> dict[str, Any]: detail = product.get("pdp") return detail if isinstance(detail, dict) else {} def _compare_overlay(product: dict[str, Any]) -> dict[str, Any]: compare = product.get("compare") return compare if isinstance(compare, dict) else {} def _compare_fact(product: dict[str, Any], *names: str) -> Any: for source in (_compare_overlay(product), product, _compare_detail(product)): for name in names: if name not in source: continue value = source[name] if value is not None and value != "": return value return None def _compare_display(value: Any) -> str: if value is None or value == "": return "—" if isinstance(value, (list, tuple)): clean_values = [str(item) for item in value if item is not None and item != ""] return ", ".join(clean_values) if clean_values else "—" if isinstance(value, dict): return "—" return str(value) def _compare_specs(product: dict[str, Any]) -> dict[str, tuple[str, str]]: specs: dict[str, tuple[str, str]] = {} raw_sources = ( _compare_overlay(product).get("specs"), product.get("specs"), _compare_detail(product).get("specs"), ) for raw_specs in raw_sources: entries: list[tuple[Any, Any]] = [] if isinstance(raw_specs, dict): entries.extend(raw_specs.items()) elif isinstance(raw_specs, list): for entry in raw_specs: if isinstance(entry, (list, tuple)) and len(entry) >= 2: entries.append((entry[0], entry[1])) elif isinstance(entry, dict): name = entry.get("name") or entry.get("label") or entry.get("key") if name is not None and "value" in entry: entries.append((name, entry.get("value"))) for raw_name, raw_value in entries: name = str(raw_name).strip() value = _compare_display(raw_value) if not name or value == "—": continue normalized = " ".join(name.casefold().split()) specs.setdefault(normalized, (name, value)) return specs def _compare_common_rows(products: list[dict[str, Any]]) -> list[tuple[str, list[str]]]: def price(product: dict[str, Any]) -> str: price_minor = _compare_fact(product, "price_minor") if not isinstance(price_minor, int): return "—" currency = _compare_display(_compare_fact(product, "currency")) return money(price_minor, currency if currency != "—" else "USD") def reviews(product: dict[str, Any]) -> str: value = _compare_fact(product, "reviews", "review_count") return f"{value:,}" if isinstance(value, int) else _compare_display(value) def selected_options(product: dict[str, Any]) -> str: raw_options = _compare_fact(product, "selected_options") if not isinstance(raw_options, dict) or not raw_options: return "Default offer" return " · ".join( f"{label}: {value}" for label, value in raw_options.items() ) facts: tuple[tuple[str, Any], ...] = ( ("ASIN", lambda product: _compare_display(_compare_fact(product, "asin"))), ("Selected options", selected_options), ("Price", price), ("Currency", lambda product: _compare_display(_compare_fact(product, "currency"))), ("Rating", lambda product: _compare_display(_compare_fact(product, "rating"))), ("Customer reviews", reviews), ("Brand", lambda product: _compare_display(_compare_fact(product, "brand"))), ("Category", lambda product: _compare_display(_compare_fact(product, "category", "page_category"))), ("Product family", lambda product: _compare_display(_compare_fact(product, "family"))), ("Availability", lambda product: _compare_display(_compare_fact(product, "display_availability", "availability", "stock"))), ("Ships from", lambda product: _compare_display(_compare_fact(product, "ships_from", "shipper"))), ("Sold by", lambda product: _compare_display(_compare_fact(product, "sold_by", "seller"))), ("Delivery", lambda product: _compare_display(_compare_fact(product, "delivery", "delivery_copy"))), ("Shipping", lambda product: _compare_display(_compare_fact(product, "shipping", "shipping_copy"))), ("Returns", lambda product: _compare_display(_compare_fact(product, "returns", "returns_copy"))), ) return [(label, [getter(product) for product in products]) for label, getter in facts] def compare_page( products: list[dict[str, Any]], cart_count: int, account_name: str | None = None, error: str | None = None, ) -> str: selected = [ product for product in products if isinstance(product, dict) and isinstance(product.get("compare_line_id"), str) ][:4] count = len(selected) error_markup = ( f'' if error else "" ) guidance = ( f'
    Add at least 2 products to compare.

    {count} of 4 comparison slots selected. Eligible products can be added from their product or search pages.

    ' if count < 2 else '

    Compare product details below. Unavailable values are shown as —.

    ' ) clear_form = ( '
    ' if count else "" ) table_markup = "" if count >= 2: product_headers: list[str] = [] product_specs: list[dict[str, tuple[str, str]]] = [] spec_union: dict[str, str] = {} for product in selected: asin = str(product.get("asin") or "") compare_line_id = escape( str(product.get("compare_line_id") or ""), quote=True ) title = escape(str(product.get("title") or asin)) title_attr = escape(str(product.get("title") or asin), quote=True) href = escape(product_href(product), quote=True) image_path = _compare_fact(product, "image_path", "main_image") image_markup = ( f'{title_attr}' if image_path else 'No image' ) product_headers.append( f'
    {image_markup}{title}
    ' ) 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'{escape(label)}{cells}' ) spec_rows = ( f'Specifications' + "".join(rendered_spec_rows) ) table_markup = f"""
    {"".join(product_headers)}{common_rows}{spec_rows}
    Feature
    Product details
    """ elif count == 1: product = selected[0] asin = str(product.get("asin") or "") safe_asin = escape(asin, quote=True) compare_line_id = escape( str(product.get("compare_line_id") or ""), quote=True ) title = escape(str(product.get("title") or asin)) title_attr = escape(str(product.get("title") or asin), quote=True) href = escape(product_href(product), quote=True) image_path = _compare_fact(product, "image_path", "main_image") image_markup = ( f'{title_attr}' if image_path else 'No image' ) table_markup = f"""

    Selected product

    {image_markup}
    {title}

    ASIN: {safe_asin}

    {escape(_compare_common_rows([product])[1][1][0])}

    """ else: table_markup = '

    Your comparison is empty

    Browse a product and choose Compare.

    Browse comparable products
    ' body = f"""

    Compare products

    Current prices, selected variants, and product attributes.

    {clear_form}
    {error_markup} {guidance} {table_markup}
    """ return layout( "Amazon.com - Compare products", body, cart_count, body_class="compare-page", account_name=account_name, ) def not_found_page(cart_count: int) -> str: body = """

    Sorry, we couldn't find that page

    Try searching or go to Amazon's home page.

    Go to Amazon home
    """ return layout("Page Not Found", body, cart_count, body_class="not-found-page") def error_page(message: str, cart_count: int, status: int = 409) -> str: body = f"""

    There was a problem

    {escape(message)}

    Return to the item
    """ return layout(f"Amazon.com - Error {status}", body, cart_count, body_class="error-page")