"""Columbia Sportswear offline clone. Serves the source-observed route families over the locally captured catalog and a deterministic SQLite-backed cart. No request ever leaves this process. """ from __future__ import annotations import sys from pathlib import Path SITE_DIR = Path(__file__).resolve().parent / "site" if str(SITE_DIR) not in sys.path: sys.path.insert(0, str(SITE_DIR)) from fastapi import FastAPI, Form, Request # noqa: E402 from fastapi.responses import HTMLResponse, RedirectResponse # noqa: E402 from fastapi.staticfiles import StaticFiles # noqa: E402 from fastapi.templating import Jinja2Templates # noqa: E402 import grid # noqa: E402 import json # noqa: E402 import render # noqa: E402 from catalog import SORT_OPTIONS, get_catalog # noqa: E402 from session import CartService, session_id_for # noqa: E402 SITE_ID = "columbia" DISPLAY_NAME = "Columbia Sportswear" ROOT = Path(__file__).resolve().parent app = FastAPI(title=DISPLAY_NAME) app.mount("/static", StaticFiles(directory=ROOT / "static"), name="static") templates = Jinja2Templates(directory=str(ROOT / "templates")) templates.env.globals["min"] = min class _LazyCatalog: """Build the captured catalog on first use rather than at import. The index is a pure function of ``data/*.json`` and every read path reaches it through attribute access, so deferring construction changes no response. It keeps the ~0.3 s parse out of the runtime's start-to-health window, which a lifecycle restart pays inside a fixed harness budget. """ __slots__ = ("_catalog",) def __init__(self) -> None: self._catalog = None def _resolve(self): if self._catalog is None: self._catalog = get_catalog() return self._catalog def __getattr__(self, name: str): return getattr(self._resolve(), name) catalog = _LazyCatalog() carts = CartService(catalog) # Source-observed category carousel on the Women grid, with the CMS artwork the # source itself serves for each tile. _VISNAV_PATH = ROOT / "data" / "plp-visnav.json" def _visnav_tiles(rows): tiles = [] for row in rows: asset = ROOT / "static" / "assets" / "cms" / f"{row['asset']}.webp" tiles.append( { "label": row["label"], "url": row["href"], "image": f"/static/assets/cms/{row['asset']}.webp" if asset.exists() else None, } ) return tiles VISNAV = ( { category_id: _visnav_tiles(rows) for category_id, rows in json.loads(_VISNAV_PATH.read_text()).items() } if _VISNAV_PATH.exists() else {} ) # One of the source's rotating Amplience campaign strings, captured from the # promotional bar above the header. PROMO_BAR = "Want Extra Savings On Sale Styles?" # Stylesheet fingerprint so an edited sheet is never served from a stale cache. ASSET_VERSION = str( max( int(path.stat().st_mtime) for path in (ROOT / "static" / "css").glob("*.css") ) ) def _shell(request: Request) -> dict[str, object]: session_id = session_id_for(request) return { "request": request, "cart_count": carts.item_count(session_id), "session_id": session_id, "promo_bar": PROMO_BAR, "asset_version": ASSET_VERSION, # The source pins the header differently by page family: category and # search grids use a sticky header under a 56px promotional bar, while # the home page and PDP use a fixed header offset 72px from the top. "header_mode": "fixed", } def _with_cookie(response, request: Request, session_id: str): if request.cookies.get(CartService.COOKIE) != session_id: response.set_cookie( CartService.COOKIE, session_id, httponly=True, samesite="lax", path="/" ) return response @app.get("/healthz") def healthz() -> dict[str, object]: return {"ok": True, "site_id": SITE_ID, "products": len(catalog.products)} @app.get("/", response_class=HTMLResponse) def home(request: Request): context = _shell(request) featured = catalog.products_in("newArrivals") or catalog.products_in("women") context.update( page_title="Outerwear, Sportswear & Footwear | Columbia Sportswear", heading="New & Trending", tiles=_tiles(featured[:12]), promo_tiles=_home_tiles(), hero=HERO, banner_before=BANNERS[0], banner_after=BANNERS[1], cards=[dict(card, image=_cms(card["asset"])) for card in CARDS], ) response = templates.TemplateResponse(request, "home.html", context) return _with_cookie(response, request, context["session_id"]) def _tiles(products, enable_compare: bool = False, promo_label: str | None = None): rows = [] for position, product in enumerate(products, start=1): variant = product.variants[0] if product.variants else None primary, hover = render.tile_images(product, variant) rows.append( { "product": product, "variant": variant, "primary": primary, "hover": hover, "price": render.price_block(product), "position": position, "enable_compare": enable_compare, "promo_label": promo_label if product.is_sale else None, } ) return rows def _cms(asset: str, ext: str = "webp") -> str | None: path = ROOT / "static" / "assets" / "cms" / f"{asset}.{ext}" return f"/static/assets/cms/{asset}.{ext}" if path.exists() else None # Source-observed homepage content. Copy is transcribed from the captured page; # artwork is the CMS asset the source itself serves for each slot. HERO = { "image": _cms("Q3_2026_WeHeart_Toolkit_Hero"), "lockup": _cms("SummerSale_Icon_Final_v2", "svg"), "heading": "MEMBERS NOW GET EXTRA 30%", "subheading": ( "We can\u2019t make summer longer, but can give you extra savings on gear " "up to 50% off. Terms apply." ), "cta": "Shop Sale", "url": "/c/sale/", } BANNERS = [ { "image": _cms("9-08_COL_US_S26_HP_Back_to_School_MomentsBan_Youth_V6"), "heading": "BACK TO SCHOOL", "body": "Get ready for next semester with new styles that pass the vibe check.", "cta": "Shop Now", "url": "/c/back-to-school/", }, { "image": _cms("8-10_ROC_MomensBan_DG"), "heading": "THE ROC\u2122 PANT", "body": ( "Elevate your everyday comfort with our versatile and rugged " "bestselling ROC\u2122 pants." ), "cta": "Shop Men", "url": "/c/roc/", }, ] CARDS = [ {"asset": "8-10_2686468_COL_US_HP_AmazeSweats_Subhero", "heading": "Sweat Sets", "body": "Soft, comfortable, effortless. Everything you could want in a sweat set.", "url": "/c/sweatsets/"}, {"asset": "8-27_COL_US_HP_We_Heart_LukeCombs_Subhero", "heading": "Luke Combs Stage Edition Bahama\u2122 Shirt", "body": "Get a custom version of our iconic PFG shirt.", "url": "/p/mens-pfg-bahama-ii-luke-combs-short-sleeve-shirt-2194741.html"}, {"asset": "8-10_2686468_COL_US_HP_FallNA_DG_Subhero", "heading": "New Arrivals", "body": "More drops all season.", "url": "/c/new-arrivals/"}, {"asset": "7-30_COL_CA_S26_HP_Run_Subhero", "heading": "All Gas, Great Brakes", "body": "Go further faster with the Konos Speed Trail ATR\u2019s trail-ready " "cushioning and traction.", "url": "/c/trailrunning/"}, {"asset": "6-30_COL_US_S26_HP_SummerTech_M_Subhero", "heading": "Cool & UV Protected", "body": "Get gear with built-in cooling and sun protection built to beat the heat.", "url": "/c/sun-protection/"}, {"asset": "8-27_COL_US_HP_We_Heart_AmazePuff_Style_Subhero_v2", "heading": "Amaze Puff\u2122 Is Back", "body": "The bestseller, now in new colors.", "url": "/c/amaze-collection/"}, ] # Source-observed promotional cell injected into the category grid after the # third product tile. GRID_PROMO = { "image": _cms("Q3_WeHeart_CA_Toolkit_Main_Gridbanner_LO"), "heading": "MEMBERS GET EXTRA 30%", "body": "On our Annual Summer Sale.", "cta": "Shop Now", "url": "/c/sale/", } def _home_tiles(): # Source-observed homepage visual-nav tiles. return [ {"label": "Men", "url": "/c/mens/"}, {"label": "Women", "url": "/c/womens/"}, {"label": "Kids", "url": "/c/kids/"}, {"label": "Shoes", "url": "/c/footwear/"}, {"label": "Accessories", "url": "/c/accessories/"}, {"label": "Bags & Gear", "url": "/c/equipment/"}, {"label": "Sale", "url": "/c/sale/"}, ] def _breadcrumb(category): trail = [] current = category seen = set() while current is not None and current.id not in seen: seen.add(current.id) trail.append(current) parent_id = current.parent current = catalog.categories.get(parent_id) if parent_id else None if current is not None and current.id == "root": break trail.reverse() crumbs = [{"name": "Home", "url": "/"}] for node in trail: if node.id == "root" or not node.name: continue is_last = node is trail[-1] crumbs.append({"name": node.name, "url": None if is_last else node.url}) return crumbs def _siblings(category): """The source shows a category's own children when it has any, and falls back to its siblings on a leaf grid (observed on /c/womens/ vs /c/fleece-jackets/).""" own = _menu_children(category) if own: return own parent = catalog.categories.get(category.parent) if category.parent else None if parent is None: return [] out = [] for child_id in parent.children: child = catalog.categories.get(child_id) if not child or not child.show_in_menu or not child.url: continue out.append({"name": child.name, "url": child.url, "current": child.id == category.id}) return out if len(out) > 1 else [] def _menu_children(category): out = [] for child_id in category.children: child = catalog.categories.get(child_id) if not child or not child.show_in_menu or not child.url: continue # `alturl_*` entries are navigation aliases of a sibling that is already # in this row, so the source's pill row does not repeat them. if child.id.startswith("alturl_"): continue out.append({"name": child.name, "url": child.url, "current": False}) return out @app.get("/c/{slug:path}", response_class=HTMLResponse) def category_page(slug: str, request: Request): url = f"/c/{slug}" if not url.endswith("/"): url += "/" category = catalog.category_by_url(url) if category is None: return _not_found(request) params = request.query_params selected = grid.parse_refine(params.getlist("refine")) sort_id = params.get("sort", "featured-new") try: page_size = max(int(params.get("pagesize", grid.PAGE_SIZE)), 1) except ValueError: page_size = grid.PAGE_SIZE result = grid.build(catalog.products_in(category.id), selected, sort_id, page_size) context = _shell(request) heading = _category_heading(category) context.update( page_title=category.page_title or f"{category.name} | Columbia Sportswear", meta_description=category.description, heading=heading, breadcrumb=_breadcrumb(category), # The source omits the breadcrumb on a top-level grid such as # /c/womens/ and shows it on a leaf grid such as /c/fleece-jackets/. show_breadcrumb=category.depth > 1, siblings=_siblings(category), visnav=VISNAV.get(category.id), result=result, tiles=_tiles(result.products, category.enable_compare, "Extra 30% Off Applied"), sort_options=SORT_OPTIONS, header_mode="sticky", grid_promo=GRID_PROMO, base_path=url, selected_any=any(selected.values()), q=None, more_url=_page_url(url, params, result.next_page_size), all_url=_page_url(url, params, result.total), ) response = templates.TemplateResponse(request, "grid.html", context) return _with_cookie(response, request, context["session_id"]) # Headings observed directly on the source category pages. Everywhere else the # source derives the h1 from its SEO page title minus the brand suffix, which # matched every page checked (for example /c/fleece-jackets/ -> "Fleece Jackets"). OBSERVED_HEADINGS = {"women": "Shop All Women\u2019s"} BRAND_SUFFIX = " | Columbia Sportswear" def _category_heading(category) -> str: observed = OBSERVED_HEADINGS.get(category.id) if observed: return observed title = category.page_title or "" if title.endswith(BRAND_SUFFIX): return title[: -len(BRAND_SUFFIX)] return category.name or "" def _page_url(base: str, params, page_size: int) -> str: pairs = [(key, value) for key, value in params.multi_items() if key != "pagesize"] pairs.append(("pagesize", str(page_size))) from urllib.parse import urlencode return f"{base}?{urlencode(pairs)}" @app.get("/search/", response_class=HTMLResponse) @app.get("/search", response_class=HTMLResponse) def search_page(request: Request): params = request.query_params query = (params.get("q") or "").strip() matches = catalog.search(query) if query else [] # The source redirects a query that names a category straight to that grid. if query: target = _category_for_query(query) if target is not None: return RedirectResponse(target.url, status_code=302) selected = grid.parse_refine(params.getlist("refine")) sort_id = params.get("sort", "featured-new") try: page_size = max(int(params.get("pagesize", grid.PAGE_SIZE)), 1) except ValueError: page_size = grid.PAGE_SIZE result = grid.build(matches, selected, sort_id, page_size) context = _shell(request) context.update( page_title=f"{query} | Columbia Sportswear" if query else "Search | Columbia Sportswear", heading=query, breadcrumb=None, show_breadcrumb=False, siblings=None, visnav=None, result=result, tiles=_tiles(result.products, False, "Extra 30% Off Applied"), sort_options=SORT_OPTIONS, header_mode="sticky", grid_promo=GRID_PROMO, base_path="/search/", selected_any=any(selected.values()), q=query, more_url=_page_url("/search/", params, result.next_page_size), all_url=_page_url("/search/", params, result.total), ) response = templates.TemplateResponse(request, "grid.html", context) return _with_cookie(response, request, context["session_id"]) def _category_for_query(query: str): from catalog import _normalize wanted = _normalize(query) for category in catalog.categories.values(): if not category.url or not catalog.category_products.get(category.id): continue names = {category.name or "", _category_heading(category)} if any(_normalize(name) == wanted for name in names if name): return category return None @app.get("/p/{slug}", response_class=HTMLResponse) def product_page(slug: str, request: Request): url = f"/p/{slug}" product = catalog.by_url.get(url) if product is None: # The source resolves a PDP by its trailing product id and treats the # slug as cosmetic, so recover the product that way before 404ing. import re match = re.search(r"-(\d+)\.html$", url) product = catalog.products.get(match.group(1)) if match else None if product is None: return _not_found(request) return RedirectResponse(product.url, status_code=302) params = request.query_params color_code = params.get("color") variant = product.variant_for_color(color_code) if variant is not None and color_code != (variant.color_code or ""): target = f"{product.url}?color={variant.color_code}" if params.get("size"): target += f"&size={params['size']}" return RedirectResponse(target, status_code=302) selected_size = params.get("size") if variant and selected_size and selected_size not in variant.sizes: selected_size = None gallery = [render.slide(media) for media in (variant.images if variant else [])] gallery = [item for item in gallery if item] swatches = { option.color_code: render.media_url(option.primary_image) for option in product.variants } # The source lists the selected colour first, then the remaining variants. ordered_variants = ( [variant] + [v for v in product.variants if v is not variant] if variant is not None else list(product.variants) ) price = render.price_block(product) unit = product.sale_price if product.sale_price is not None else product.min_price context = _shell(request) context.update( page_title=f"{product.name} | Columbia", meta_description=product.pitch, product=product, variant=variant, selected_size=selected_size, gallery=gallery, poster=next((item["src"] for item in gallery if item["kind"] == "image"), None), swatches=swatches, ordered_variants=ordered_variants, price=price, points=int(unit * 10) if unit else None, collection=_collection_for(product), breadcrumb=_pdp_breadcrumb(product), parent_category=_pdp_parent(product), ) response = templates.TemplateResponse(request, "pdp.html", context) return _with_cookie(response, request, context["session_id"]) def _collection_for(product): for path in product.category_path: leaf = path.split(">")[-1] category = catalog.categories.get(leaf) if category and category.name and "Collection" in category.name: return category.name return None def _pdp_parent(product): """The source's PDP card links back to the product's leaf category.""" crumbs = _pdp_breadcrumb(product) or [] for crumb in reversed(crumbs): if crumb.get("url") and crumb["url"] != "/": return crumb return None def _pdp_breadcrumb(product): best = None for path in product.category_path: parts = path.split(">") if len(parts) < 2: continue leaf = catalog.categories.get(parts[-1]) if leaf and leaf.show_in_menu and leaf.name: if best is None or len(parts) > best[0]: best = (len(parts), parts) if best is None: return None crumbs = [{"name": "Home", "url": "/"}] for part in best[1]: category = catalog.categories.get(part) if category and category.name and category.url: crumbs.append({"name": category.name, "url": category.url}) crumbs.append({"name": product.name, "url": None}) return crumbs @app.get("/cart", response_class=HTMLResponse) def cart_page(request: Request, promo_error: str | None = None): context = _shell(request) view = carts.view(context["session_id"]) context.update(view, promo_error=promo_error) response = templates.TemplateResponse(request, "cart.html", context) return _with_cookie(response, request, context["session_id"]) @app.post("/cart/add") def cart_add( request: Request, product_id: str = Form(...), variant_id: str = Form(None), color_code: str = Form(None), size: str = Form(None), quantity: int = Form(1), ): session_id = session_id_for(request) product = catalog.products.get(product_id) if product is None: return _redirect("/cart", request, session_id) if not size: target = f"{product.url}?color={color_code}&error=size" if color_code else product.url return _redirect(target, request, session_id) carts.add(session_id, product_id, variant_id, color_code, size, max(quantity, 1)) return _redirect("/cart", request, session_id) @app.post("/cart/update") def cart_update(request: Request, line_id: int = Form(...), quantity: int = Form(...)): session_id = session_id_for(request) carts.set_quantity(session_id, line_id, quantity) return _redirect("/cart", request, session_id) @app.post("/cart/remove") def cart_remove(request: Request, line_id: int = Form(...)): session_id = session_id_for(request) carts.remove(session_id, line_id) return _redirect("/cart", request, session_id) @app.post("/cart/save") def cart_save(request: Request, line_id: int = Form(...)): session_id = session_id_for(request) carts.set_saved(session_id, line_id, True) return _redirect("/cart", request, session_id) @app.post("/cart/move") def cart_move(request: Request, line_id: int = Form(...)): session_id = session_id_for(request) carts.set_saved(session_id, line_id, False) return _redirect("/cart", request, session_id) @app.post("/cart/promo") def cart_promo(request: Request, code: str = Form("")): session_id = session_id_for(request) applied = carts.apply_promo(session_id, code) target = "/cart" if applied else "/cart?promo_error=That+promo+code+is+not+valid." return _redirect(target, request, session_id) @app.post("/cart/promo/clear") def cart_promo_clear(request: Request): session_id = session_id_for(request) carts.clear_promo(session_id) return _redirect("/cart", request, session_id) def _redirect(target: str, request: Request, session_id: str): response = RedirectResponse(target, status_code=303) return _with_cookie(response, request, session_id) def _not_found(request: Request): context = _shell(request) context.update(page_title="Page Not Found | Columbia Sportswear", heading="Page Not Found", body=None) response = templates.TemplateResponse(request, "content.html", context, status_code=404) return _with_cookie(response, request, context["session_id"]) # Content routes observed in the source header, footer and mega-menu. Copy for # these pages was not captured, so they render structurally and are reported as # `inferred` rather than presented as source-observed. CONTENT_ROUTES = { "/t/accessibility/": "Accessibility Statement", "/t/product-care/": "Product Care", "/t/tech/": "Product Technology", "/t/responsibility/": "Corporate Responsibility", "/t/drops/": "Special-Edition Collections", "/t/ambassadors/": "Elite Athletes & Ambassadors", "/t/business-partner/": "Wholesale", "/t/giftcards/": "Gift Cards", "/t/coupons/": "Special Deals", "/t/discount-programs/": "ID.me Verification", "/t/size-fit/": "Size Guides", "/t/legal/terms-of-use/": "Terms of Use", "/t/legal/terms-of-sale/": "Terms of Sale", "/t/legal/privacy-policy/": "Privacy Policy", "/t/legal/cgr-terms/": "Rewards Terms and Conditions", "/t/legal/ugc-terms/": "User Generated Content Terms of Use", "/t/legal/do-not-sell-my-information/": "Do Not Sell or Share My Information", "/our-story/": "Our Story", "/careers/": "Careers", "/warranty/": "Warranty", "/order-returns/": "Returns", "/stores/": "Find a Store", "/rewardsprogram/": "Columbia Greater Rewards", "/outdoor-guide.html": "Tough Mother Outdoor Guide", "/pro": "Pro Program", "/pfg/": "PFG Fishing", "/featured/": "Explore", "/on/demandware.store/Sites-Columbia_US-Site/en_US/Login-Show": "Log In or Join For Free", } @app.get("/t/{path:path}", response_class=HTMLResponse) def content_route(path: str, request: Request): return _content(f"/t/{path}" if path.endswith("/") else f"/t/{path}/", request) for _route in list(CONTENT_ROUTES): if _route.startswith("/t/"): continue def _make(route: str): def handler(request: Request): return _content(route, request) return handler app.add_api_route(_route, _make(_route), methods=["GET"], response_class=HTMLResponse) def _content(route: str, request: Request): heading = CONTENT_ROUTES.get(route) if heading is None: return _not_found(request) context = _shell(request) context.update( page_title=f"{heading} | Columbia Sportswear", heading=heading, body=None ) response = templates.TemplateResponse(request, "content.html", context) return _with_cookie(response, request, context["session_id"]) @app.get("/account", response_class=HTMLResponse) @app.get("/account/orders", response_class=HTMLResponse) def account(request: Request): """Account surfaces were blocked by the source's bot protection during capture, so they are structural-only and reported as `inferred`.""" context = _shell(request) context.update( page_title="My Account | Columbia Sportswear", heading="My Account", body=None ) response = templates.TemplateResponse(request, "content.html", context) return _with_cookie(response, request, context["session_id"]) @app.post("/checkout") def checkout(request: Request): """Checkout terminates in the local sandbox; no payment path exists here.""" session_id = session_id_for(request) return _redirect("/cart", request, session_id)