Phase 6: Replace render_template() with s-expression rendering in all GET routes

Migrate ~52 GET route handlers across all 7 services from Jinja
render_template() to s-expression component rendering. Each service
gets a sexp_components.py with page/oob/cards render functions.

- Add per-service sexp_components.py (account, blog, cart, events,
  federation, market, orders) with full page, OOB, and pagination
  card rendering
- Add shared/sexp/helpers.py with call_url, root_header_html,
  full_page, oob_page utilities
- Update all GET routes to use get_template_context() + render fns
- Fix get_template_context() to inject Jinja globals (URL helpers)
- Add qs_filter to base_context for sexp filter URL building
- Mount sexp_components.py in docker-compose.dev.yml for all services
- Import sexp_components in app.py for Hypercorn --reload watching
- Fix route_prefix import (shared.utils not shared.infrastructure.urls)
- Fix federation choose-username missing actor in context
- Fix market page_markets missing post in context

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-27 23:19:33 +00:00
parent 8013317b41
commit d53b9648a9
53 changed files with 8690 additions and 463 deletions

View File

@@ -1,5 +1,6 @@
from __future__ import annotations
import path_setup # noqa: F401 # adds shared/ to sys.path
import sexp_components # noqa: F401 # ensure Hypercorn --reload watches this file
from decimal import Decimal
from pathlib import Path

View File

@@ -14,18 +14,16 @@ def register(url_prefix: str) -> Blueprint:
@bp.get("/")
async def overview():
from quart import g
from shared.sexp.page import get_template_context
from sexp_components import render_overview_page, render_overview_oob
page_groups = await get_cart_grouped_by_page(g.s)
ctx = await get_template_context()
if not is_htmx_request():
html = await render_template(
"_types/cart/overview/index.html",
page_groups=page_groups,
)
html = await render_overview_page(ctx, page_groups)
else:
html = await render_template(
"_types/cart/overview/_oob_elements.html",
page_groups=page_groups,
)
html = await render_overview_oob(ctx, page_groups)
return await make_response(html)
return bp

View File

@@ -40,10 +40,20 @@ def register(url_prefix: str) -> Blueprint:
ticket_total=ticket_total,
)
from shared.sexp.page import get_template_context
from sexp_components import render_page_cart_page, render_page_cart_oob
ctx = await get_template_context()
if not is_htmx_request():
html = await render_template("_types/cart/page/index.html", **tpl_ctx)
html = await render_page_cart_page(
ctx, post, cart, cal_entries, page_tickets,
ticket_groups, total, calendar_total, ticket_total,
)
else:
html = await render_template("_types/cart/page/_oob_elements.html", **tpl_ctx)
html = await render_page_cart_oob(
ctx, post, cart, cal_entries, page_tickets,
ticket_groups, total, calendar_total, ticket_total,
)
return await make_response(html)
@bp.post("/checkout/")

View File

@@ -55,12 +55,16 @@ def register() -> Blueprint:
order = result.scalar_one_or_none()
if not order:
return await make_response("Order not found", 404)
from shared.sexp.page import get_template_context
from sexp_components import render_order_page, render_order_oob
ctx = await get_template_context()
calendar_entries = ctx.get("calendar_entries")
if not is_htmx_request():
# Normal browser request: full page with layout
html = await render_template("_types/order/index.html", order=order,)
html = await render_order_page(ctx, order, calendar_entries, url_for)
else:
# HTMX navigation (page 1): main panel + OOB elements
html = await render_template("_types/order/_oob_elements.html", order=order,)
html = await render_order_oob(ctx, order, calendar_entries, url_for)
return await make_response(html)

View File

@@ -136,24 +136,30 @@ def register(url_prefix: str) -> Blueprint:
result = await g.s.execute(stmt)
orders = result.scalars().all()
context = {
"orders": orders,
"page": page,
"total_pages": total_pages,
"search": search,
"search_count": total_count, # For search display
}
from shared.sexp.page import get_template_context
from sexp_components import (
render_orders_page,
render_orders_rows,
render_orders_oob,
)
ctx = await get_template_context()
qs_fn = makeqs_factory()
# Determine which template to use based on request type and pagination
if not is_htmx_request():
# Normal browser request: full page with layout
html = await render_template("_types/orders/index.html", **context)
html = await render_orders_page(
ctx, orders, page, total_pages, search, total_count,
url_for, qs_fn,
)
elif page > 1:
# HTMX pagination: just table rows + sentinel
html = await render_template("_types/orders/_rows.html", **context)
html = await render_orders_rows(
ctx, orders, page, total_pages, url_for, qs_fn,
)
else:
# HTMX navigation (page 1): main panel + OOB elements
html = await render_template("_types/orders/_oob_elements.html", **context)
html = await render_orders_oob(
ctx, orders, page, total_pages, search, total_count,
url_for, qs_fn,
)
resp = await make_response(html)
resp.headers["Hx-Push-Url"] = _current_url_without_page()

805
cart/sexp_components.py Normal file
View File

@@ -0,0 +1,805 @@
"""
Cart service s-expression page components.
Renders cart overview, page cart, orders list, and single order detail.
Called from route handlers in place of ``render_template()``.
"""
from __future__ import annotations
from typing import Any
from shared.sexp.jinja_bridge import sexp
from shared.sexp.helpers import (
call_url, root_header_html, search_desktop_html,
search_mobile_html, full_page, oob_page,
)
from shared.infrastructure.urls import market_product_url
# ---------------------------------------------------------------------------
# Header helpers
# ---------------------------------------------------------------------------
def _cart_header_html(ctx: dict, *, oob: bool = False) -> str:
"""Build the cart section header row."""
return sexp(
'(~menu-row :id "cart-row" :level 1 :colour "sky"'
' :link-href lh :link-label "cart" :icon "fa fa-shopping-cart"'
' :child-id "cart-header-child" :oob oob)',
lh=call_url(ctx, "cart_url", "/"),
oob=oob,
)
def _page_cart_header_html(ctx: dict, page_post: Any, *, oob: bool = False) -> str:
"""Build the per-page cart header row."""
slug = page_post.slug if page_post else ""
title = (page_post.title or "")[:160]
img_html = ""
if page_post and page_post.feature_image:
img_html = (
f'<img src="{page_post.feature_image}"'
f' class="h-8 w-8 rounded-full object-cover border border-stone-300 flex-shrink-0">'
)
label_html = f'{img_html}<span>{title}</span>'
nav_html = sexp(
'(a :href h :class "inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-full border border-stone-300 bg-white hover:bg-stone-50 transition"'
' (raw! i) "All carts")',
h=call_url(ctx, "cart_url", "/"),
i='<i class="fa fa-arrow-left text-xs" aria-hidden="true"></i>',
)
return sexp(
'(~menu-row :id "page-cart-row" :level 2 :colour "sky"'
' :link-href lh :link-label-html llh :nav-html nh :oob oob)',
lh=call_url(ctx, "cart_url", f"/{slug}/"),
llh=label_html,
nh=nav_html,
oob=oob,
)
def _auth_header_html(ctx: dict, *, oob: bool = False) -> str:
"""Build the account section header row (for orders)."""
return sexp(
'(~menu-row :id "auth-row" :level 1 :colour "sky"'
' :link-href lh :link-label "account" :icon "fa-solid fa-user"'
' :child-id "auth-header-child" :oob oob)',
lh=call_url(ctx, "account_url", "/"),
oob=oob,
)
def _orders_header_html(ctx: dict, list_url: str) -> str:
"""Build the orders section header row."""
return sexp(
'(~menu-row :id "orders-row" :level 2 :colour "sky"'
' :link-href lh :link-label "Orders" :icon "fa fa-gbp"'
' :child-id "orders-header-child")',
lh=list_url,
)
# ---------------------------------------------------------------------------
# Cart overview
# ---------------------------------------------------------------------------
def _page_group_card_html(grp: Any, ctx: dict) -> str:
"""Render a single page group card for cart overview."""
post = grp.get("post") if isinstance(grp, dict) else getattr(grp, "post", None)
cart_items = grp.get("cart_items", []) if isinstance(grp, dict) else getattr(grp, "cart_items", [])
cal_entries = grp.get("calendar_entries", []) if isinstance(grp, dict) else getattr(grp, "calendar_entries", [])
tickets = grp.get("tickets", []) if isinstance(grp, dict) else getattr(grp, "tickets", [])
product_count = grp.get("product_count", 0) if isinstance(grp, dict) else getattr(grp, "product_count", 0)
calendar_count = grp.get("calendar_count", 0) if isinstance(grp, dict) else getattr(grp, "calendar_count", 0)
ticket_count = grp.get("ticket_count", 0) if isinstance(grp, dict) else getattr(grp, "ticket_count", 0)
total = grp.get("total", 0) if isinstance(grp, dict) else getattr(grp, "total", 0)
market_place = grp.get("market_place") if isinstance(grp, dict) else getattr(grp, "market_place", None)
if not cart_items and not cal_entries and not tickets:
return ""
# Count badges
badges = []
if product_count > 0:
s = "s" if product_count != 1 else ""
badges.append(
f'<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-stone-100">'
f'<i class="fa fa-box-open" aria-hidden="true"></i> {product_count} item{s}</span>'
)
if calendar_count > 0:
s = "s" if calendar_count != 1 else ""
badges.append(
f'<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-stone-100">'
f'<i class="fa fa-calendar" aria-hidden="true"></i> {calendar_count} booking{s}</span>'
)
if ticket_count > 0:
s = "s" if ticket_count != 1 else ""
badges.append(
f'<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-stone-100">'
f'<i class="fa fa-ticket" aria-hidden="true"></i> {ticket_count} ticket{s}</span>'
)
badges_html = '<div class="mt-1 flex flex-wrap gap-2 text-xs text-stone-600">' + "".join(badges) + '</div>'
if post:
slug = post.slug if hasattr(post, "slug") else post.get("slug", "")
title = post.title if hasattr(post, "title") else post.get("title", "")
feature_image = post.feature_image if hasattr(post, "feature_image") else post.get("feature_image")
cart_url = call_url(ctx, "cart_url", f"/{slug}/")
if feature_image:
img = f'<img src="{feature_image}" alt="{title}" class="h-16 w-16 rounded-xl object-cover border border-stone-200 flex-shrink-0">'
else:
img = '<div class="h-16 w-16 rounded-xl bg-stone-100 flex items-center justify-center flex-shrink-0"><i class="fa fa-store text-stone-400 text-xl" aria-hidden="true"></i></div>'
mp_name = ""
mp_sub = ""
if market_place:
mp_name = market_place.name if hasattr(market_place, "name") else market_place.get("name", "")
mp_sub = f'<p class="text-xs text-stone-500 truncate">{title}</p>'
display_title = mp_name or title
return (
f'<a href="{cart_url}" class="block rounded-2xl border border-stone-200 bg-white shadow-sm hover:shadow-md hover:border-stone-300 transition p-4 sm:p-5">'
f'<div class="flex items-start gap-4">{img}'
f'<div class="flex-1 min-w-0"><h3 class="text-base sm:text-lg font-semibold text-stone-900 truncate">{display_title}</h3>{mp_sub}{badges_html}</div>'
f'<div class="text-right flex-shrink-0"><div class="text-lg font-bold text-stone-900">&pound;{total:.2f}</div>'
f'<div class="mt-1 text-xs text-emerald-700 font-medium">View cart &rarr;</div></div></div></a>'
)
else:
# Orphan items
badges_html_amber = badges_html.replace("bg-stone-100", "bg-amber-100")
return (
f'<div class="rounded-2xl border border-dashed border-amber-300 bg-amber-50/60 p-4 sm:p-5">'
f'<div class="flex items-start gap-4">'
f'<div class="h-16 w-16 rounded-xl bg-amber-100 flex items-center justify-center flex-shrink-0">'
f'<i class="fa fa-shopping-cart text-amber-500 text-xl" aria-hidden="true"></i></div>'
f'<div class="flex-1 min-w-0"><h3 class="text-base sm:text-lg font-semibold text-stone-900">Other items</h3>{badges_html_amber}</div>'
f'<div class="text-right flex-shrink-0"><div class="text-lg font-bold text-stone-900">&pound;{total:.2f}</div></div></div></div>'
)
def _overview_main_panel_html(page_groups: list, ctx: dict) -> str:
"""Cart overview main panel."""
if not page_groups:
return (
'<div class="max-w-full px-3 py-3 space-y-3">'
'<div class="rounded-2xl border border-dashed border-stone-300 bg-white/80 p-6 sm:p-8 text-center">'
'<div class="inline-flex h-10 w-10 sm:h-12 sm:w-12 items-center justify-center rounded-full bg-stone-100 mb-3">'
'<i class="fa fa-shopping-cart text-stone-500 text-sm sm:text-base" aria-hidden="true"></i></div>'
'<p class="text-base sm:text-lg font-medium text-stone-800">Your cart is empty</p></div></div>'
)
cards = [_page_group_card_html(grp, ctx) for grp in page_groups]
has_items = any(c for c in cards)
if not has_items:
return (
'<div class="max-w-full px-3 py-3 space-y-3">'
'<div class="rounded-2xl border border-dashed border-stone-300 bg-white/80 p-6 sm:p-8 text-center">'
'<div class="inline-flex h-10 w-10 sm:h-12 sm:w-12 items-center justify-center rounded-full bg-stone-100 mb-3">'
'<i class="fa fa-shopping-cart text-stone-500 text-sm sm:text-base" aria-hidden="true"></i></div>'
'<p class="text-base sm:text-lg font-medium text-stone-800">Your cart is empty</p></div></div>'
)
return '<div class="max-w-full px-3 py-3 space-y-3"><div class="space-y-4">' + "".join(cards) + '</div></div>'
# ---------------------------------------------------------------------------
# Page cart
# ---------------------------------------------------------------------------
def _cart_item_html(item: Any, ctx: dict) -> str:
"""Render a single product cart item."""
from shared.browser.app.csrf import generate_csrf_token
from quart import url_for
p = item.product if hasattr(item, "product") else item
slug = p.slug if hasattr(p, "slug") else ""
unit_price = getattr(p, "special_price", None) or getattr(p, "regular_price", None)
currency = getattr(p, "regular_price_currency", "GBP") or "GBP"
symbol = "\u00a3" if currency == "GBP" else currency
csrf = generate_csrf_token()
qty_url = url_for("cart_global.update_quantity", product_id=p.id)
prod_url = market_product_url(slug)
if p.image:
img = f'<img src="{p.image}" alt="{p.title}" class="w-24 h-24 sm:w-32 sm:h-28 object-cover rounded-xl border border-stone-100" loading="lazy">'
else:
img = '<div class="w-24 h-24 sm:w-32 sm:h-28 rounded-xl border border-dashed border-stone-300 flex items-center justify-center text-xs text-stone-400">No image</div>'
price_html = ""
if unit_price:
price_html = f'<p class="text-sm sm:text-base font-semibold text-stone-900">{symbol}{unit_price:.2f}</p>'
if p.special_price and p.special_price != p.regular_price:
price_html += f'<p class="text-xs text-stone-400 line-through">{symbol}{p.regular_price:.2f}</p>'
else:
price_html = '<p class="text-xs text-stone-500">No price</p>'
deleted_html = ""
if getattr(item, "is_deleted", False):
deleted_html = (
'<p class="mt-2 inline-flex items-center gap-1 text-[0.65rem] sm:text-xs font-medium text-amber-700 bg-amber-50 border border-amber-200 rounded-full px-2 py-0.5">'
'<i class="fa-solid fa-triangle-exclamation text-[0.6rem]" aria-hidden="true"></i>'
' This item is no longer available or price has changed</p>'
)
brand_html = f'<p class="mt-0.5 text-[0.7rem] sm:text-xs text-stone-500">{p.brand}</p>' if getattr(p, "brand", None) else ""
line_total_html = ""
if unit_price:
lt = unit_price * item.quantity
line_total_html = f'<p class="text-sm sm:text-base font-semibold text-stone-900">Line total: {symbol}{lt:.2f}</p>'
return (
f'<article id="cart-item-{slug}" class="flex flex-col sm:flex-row gap-3 sm:gap-4 rounded-2xl bg-white shadow-sm border border-stone-200 p-3 sm:p-4 md:p-5">'
f'<div class="w-full sm:w-32 shrink-0 flex justify-center sm:block">{img}</div>'
f'<div class="flex-1 min-w-0">'
f'<div class="flex flex-col sm:flex-row sm:items-start justify-between gap-2 sm:gap-3">'
f'<div class="min-w-0"><h2 class="text-sm sm:text-base md:text-lg font-semibold text-stone-900">'
f'<a href="{prod_url}" class="hover:text-emerald-700">{p.title}</a></h2>{brand_html}{deleted_html}</div>'
f'<div class="text-left sm:text-right">{price_html}</div></div>'
f'<div class="mt-3 flex flex-col sm:flex-row sm:items-center justify-between gap-2 sm:gap-4">'
f'<div class="flex items-center gap-2 text-xs sm:text-sm text-stone-700">'
f'<span class="text-[0.65rem] sm:text-xs uppercase tracking-wide text-stone-500">Quantity</span>'
f'<form action="{qty_url}" method="post" hx-post="{qty_url}" hx-swap="none">'
f'<input type="hidden" name="csrf_token" value="{csrf}"><input type="hidden" name="count" value="{item.quantity - 1}">'
f'<button type="submit" class="inline-flex items-center justify-center w-8 h-8 text-sm font-medium rounded-full border border-emerald-600 text-emerald-700 hover:bg-emerald-50 text-xl">-</button></form>'
f'<span class="inline-flex items-center justify-center px-2 py-1 rounded-full bg-stone-100 text-[0.7rem] sm:text-xs font-medium">{item.quantity}</span>'
f'<form action="{qty_url}" method="post" hx-post="{qty_url}" hx-swap="none">'
f'<input type="hidden" name="csrf_token" value="{csrf}"><input type="hidden" name="count" value="{item.quantity + 1}">'
f'<button type="submit" class="inline-flex items-center justify-center w-8 h-8 text-sm font-medium rounded-full border border-emerald-600 text-emerald-700 hover:bg-emerald-50 text-xl">+</button></form></div>'
f'<div class="flex items-center justify-between sm:justify-end gap-3">{line_total_html}</div></div></div></article>'
)
def _calendar_entries_html(entries: list) -> str:
"""Render calendar booking entries in cart."""
if not entries:
return ""
items = []
for e in entries:
name = getattr(e, "name", None) or getattr(e, "calendar_name", "")
start = e.start_at if hasattr(e, "start_at") else ""
end = getattr(e, "end_at", None)
cost = getattr(e, "cost", 0) or 0
end_html = f" \u2013 {end}" if end else ""
items.append(
f'<li class="flex items-start justify-between text-sm">'
f'<div><div class="font-medium">{name}</div>'
f'<div class="text-xs text-stone-500">{start}{end_html}</div></div>'
f'<div class="ml-4 font-medium">\u00a3{cost:.2f}</div></li>'
)
return (
'<div class="mt-6 border-t border-stone-200 pt-4">'
'<h2 class="text-base font-semibold mb-2">Calendar bookings</h2>'
f'<ul class="space-y-2">{"".join(items)}</ul></div>'
)
def _ticket_groups_html(ticket_groups: list, ctx: dict) -> str:
"""Render ticket groups in cart."""
if not ticket_groups:
return ""
from shared.browser.app.csrf import generate_csrf_token
from quart import url_for
csrf = generate_csrf_token()
qty_url = url_for("cart_global.update_ticket_quantity")
parts = ['<div class="mt-6 border-t border-stone-200 pt-4">',
'<h2 class="text-base font-semibold mb-2"><i class="fa fa-ticket mr-1" aria-hidden="true"></i> Event tickets</h2>',
'<div class="space-y-3">']
for tg in ticket_groups:
name = tg.entry_name if hasattr(tg, "entry_name") else tg.get("entry_name", "")
tt_name = tg.ticket_type_name if hasattr(tg, "ticket_type_name") else tg.get("ticket_type_name", "")
price = tg.price if hasattr(tg, "price") else tg.get("price", 0)
quantity = tg.quantity if hasattr(tg, "quantity") else tg.get("quantity", 0)
line_total = tg.line_total if hasattr(tg, "line_total") else tg.get("line_total", 0)
entry_id = tg.entry_id if hasattr(tg, "entry_id") else tg.get("entry_id", "")
tt_id = tg.ticket_type_id if hasattr(tg, "ticket_type_id") else tg.get("ticket_type_id", "")
start_at = tg.entry_start_at if hasattr(tg, "entry_start_at") else tg.get("entry_start_at")
end_at = tg.entry_end_at if hasattr(tg, "entry_end_at") else tg.get("entry_end_at")
date_str = start_at.strftime("%-d %b %Y, %H:%M") if start_at else ""
if end_at:
date_str += f" \u2013 {end_at.strftime('%-d %b %Y, %H:%M')}"
tt_name_html = f'<p class="mt-0.5 text-[0.7rem] sm:text-xs text-stone-500">{tt_name}</p>' if tt_name else ""
tt_hidden = f'<input type="hidden" name="ticket_type_id" value="{tt_id}">' if tt_id else ""
parts.append(
f'<article class="flex flex-col sm:flex-row gap-3 sm:gap-4 rounded-2xl bg-white shadow-sm border border-stone-200 p-3 sm:p-4">'
f'<div class="flex-1 min-w-0">'
f'<div class="flex flex-col sm:flex-row sm:items-start justify-between gap-2 sm:gap-3">'
f'<div class="min-w-0"><h3 class="text-sm sm:text-base font-semibold text-stone-900">{name}</h3>{tt_name_html}'
f'<p class="mt-0.5 text-[0.7rem] sm:text-xs text-stone-500">{date_str}</p></div>'
f'<div class="text-left sm:text-right"><p class="text-sm sm:text-base font-semibold text-stone-900">\u00a3{price or 0:.2f}</p></div></div>'
f'<div class="mt-3 flex flex-col sm:flex-row sm:items-center justify-between gap-2 sm:gap-4">'
f'<div class="flex items-center gap-2 text-xs sm:text-sm text-stone-700">'
f'<span class="text-[0.65rem] sm:text-xs uppercase tracking-wide text-stone-500">Quantity</span>'
f'<form action="{qty_url}" method="post" hx-post="{qty_url}" hx-swap="none">'
f'<input type="hidden" name="csrf_token" value="{csrf}"><input type="hidden" name="entry_id" value="{entry_id}">{tt_hidden}'
f'<input type="hidden" name="count" value="{max(quantity - 1, 0)}">'
f'<button type="submit" class="inline-flex items-center justify-center w-8 h-8 text-sm font-medium rounded-full border border-emerald-600 text-emerald-700 hover:bg-emerald-50 text-xl">-</button></form>'
f'<span class="inline-flex items-center justify-center px-2 py-1 rounded-full bg-stone-100 text-[0.7rem] sm:text-xs font-medium">{quantity}</span>'
f'<form action="{qty_url}" method="post" hx-post="{qty_url}" hx-swap="none">'
f'<input type="hidden" name="csrf_token" value="{csrf}"><input type="hidden" name="entry_id" value="{entry_id}">{tt_hidden}'
f'<input type="hidden" name="count" value="{quantity + 1}">'
f'<button type="submit" class="inline-flex items-center justify-center w-8 h-8 text-sm font-medium rounded-full border border-emerald-600 text-emerald-700 hover:bg-emerald-50 text-xl">+</button></form></div>'
f'<div class="flex items-center justify-between sm:justify-end gap-3">'
f'<p class="text-sm sm:text-base font-semibold text-stone-900">Line total: \u00a3{line_total:.2f}</p></div></div></div></article>'
)
parts.append('</div></div>')
return "".join(parts)
def _cart_summary_html(ctx: dict, cart: list, cal_entries: list, tickets: list,
total_fn: Any, cal_total_fn: Any, ticket_total_fn: Any) -> str:
"""Render the order summary sidebar."""
from shared.browser.app.csrf import generate_csrf_token
from quart import g, url_for, request
from shared.infrastructure.urls import login_url
csrf = generate_csrf_token()
product_qty = sum(ci.quantity for ci in cart) if cart else 0
ticket_qty = len(tickets) if tickets else 0
item_count = product_qty + ticket_qty
product_total = total_fn(cart) or 0
cal_total = cal_total_fn(cal_entries) or 0
tk_total = ticket_total_fn(tickets) or 0
grand = float(product_total) + float(cal_total) + float(tk_total)
symbol = "\u00a3"
if cart and hasattr(cart[0], "product") and getattr(cart[0].product, "regular_price_currency", None):
cur = cart[0].product.regular_price_currency
symbol = "\u00a3" if cur == "GBP" else cur
user = getattr(g, "user", None)
page_post = ctx.get("page_post")
if user:
if page_post:
action = url_for("page_cart.page_checkout")
else:
action = url_for("cart_global.checkout")
from shared.utils import route_prefix
action = route_prefix() + action
checkout_html = (
f'<form method="post" action="{action}" class="w-full">'
f'<input type="hidden" name="csrf_token" value="{csrf}">'
f'<button type="submit" class="w-full inline-flex items-center justify-center px-4 py-2 text-xs sm:text-sm rounded-full border border-emerald-600 bg-emerald-600 text-white hover:bg-emerald-700 transition">'
f'<i class="fa-solid fa-credit-card mr-2" aria-hidden="true"></i> Checkout as {user.email}</button></form>'
)
else:
href = login_url(request.url)
checkout_html = (
f'<div class="w-full flex"><a href="{href}" class="w-full cursor-pointer flex flex-row items-center justify-center p-3 gap-2 rounded bg-stone-200 text-black hover:bg-stone-300 transition">'
f'<i class="fa-solid fa-key"></i><span>sign in or register to checkout</span></a></div>'
)
return (
f'<aside id="cart-summary" class="lg:pl-2"><div class="rounded-2xl bg-white shadow-sm border border-stone-200 p-4 sm:p-5">'
f'<h2 class="text-sm sm:text-base font-semibold text-stone-900 mb-3 sm:mb-4">Order summary</h2>'
f'<dl class="space-y-2 text-xs sm:text-sm">'
f'<div class="flex items-center justify-between"><dt class="text-stone-600">Items</dt><dd class="text-stone-900">{item_count}</dd></div>'
f'<div class="flex items-center justify-between"><dt class="text-stone-600">Subtotal</dt><dd class="text-stone-900">{symbol}{grand:.2f}</dd></div></dl>'
f'<div class="flex flex-col items-center w-full"><h1 class="text-5xl mt-2">This is a test - it will not take actual money</h1>'
f'<div>use dummy card number: 5555 5555 5555 4444</div></div>'
f'<div class="mt-4 sm:mt-5">{checkout_html}</div></div></aside>'
)
def _page_cart_main_panel_html(ctx: dict, cart: list, cal_entries: list,
tickets: list, ticket_groups: list,
total_fn: Any, cal_total_fn: Any,
ticket_total_fn: Any) -> str:
"""Page cart main panel."""
if not cart and not cal_entries and not tickets:
return (
'<div class="max-w-full px-3 py-3 space-y-3">'
'<div id="cart"><div class="rounded-2xl border border-dashed border-stone-300 bg-white/80 p-6 sm:p-8 text-center">'
'<div class="inline-flex h-10 w-10 sm:h-12 sm:w-12 items-center justify-center rounded-full bg-stone-100 mb-3">'
'<i class="fa fa-shopping-cart text-stone-500 text-sm sm:text-base" aria-hidden="true"></i></div>'
'<p class="text-base sm:text-lg font-medium text-stone-800">Your cart is empty</p></div></div></div>'
)
items_html = "".join(_cart_item_html(item, ctx) for item in cart)
cal_html = _calendar_entries_html(cal_entries)
tickets_html = _ticket_groups_html(ticket_groups, ctx)
summary_html = _cart_summary_html(ctx, cart, cal_entries, tickets, total_fn, cal_total_fn, ticket_total_fn)
return (
f'<div class="max-w-full px-3 py-3 space-y-3"><div id="cart">'
f'<div><section class="space-y-3 sm:space-y-4">{items_html}{cal_html}{tickets_html}</section>'
f'{summary_html}</div></div></div>'
)
# ---------------------------------------------------------------------------
# Orders list (same pattern as orders service)
# ---------------------------------------------------------------------------
def _order_row_html(order: Any, detail_url: str) -> str:
"""Render a single order as desktop table row + mobile card."""
status = order.status or "pending"
sl = status.lower()
pill = (
"border-emerald-300 bg-emerald-50 text-emerald-700" if sl == "paid"
else "border-rose-300 bg-rose-50 text-rose-700" if sl in ("failed", "cancelled")
else "border-stone-300 bg-stone-50 text-stone-700"
)
created = order.created_at.strftime("%-d %b %Y, %H:%M") if order.created_at else "\u2014"
total = f"{order.currency or 'GBP'} {order.total_amount or 0:.2f}"
return (
f'<tr class="hidden sm:table-row border-t border-stone-100 hover:bg-stone-50/60">'
f'<td class="px-3 py-2 align-top"><span class="font-mono text-[11px] sm:text-xs">#{order.id}</span></td>'
f'<td class="px-3 py-2 align-top text-stone-700 text-xs sm:text-sm">{created}</td>'
f'<td class="px-3 py-2 align-top text-stone-700 text-xs sm:text-sm">{order.description or ""}</td>'
f'<td class="px-3 py-2 align-top text-stone-700 text-xs sm:text-sm">{total}</td>'
f'<td class="px-3 py-2 align-top"><span class="inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] sm:text-xs {pill}">{status}</span></td>'
f'<td class="px-3 py-0.5 align-top text-right"><a href="{detail_url}" class="inline-flex items-center px-3 py-1.5 text-xs sm:text-sm rounded-full border border-stone-300 bg-white hover:bg-stone-50 transition">View</a></td></tr>'
f'<tr class="sm:hidden border-t border-stone-100"><td colspan="5" class="px-3 py-3"><div class="flex flex-col gap-2 text-xs">'
f'<div class="flex items-center justify-between gap-2"><span class="font-mono text-[11px] text-stone-700">#{order.id}</span>'
f'<span class="inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] {pill}">{status}</span></div>'
f'<div class="text-[11px] text-stone-500 break-words">{created}</div>'
f'<div class="flex items-center justify-between gap-2"><div class="font-medium text-stone-800">{total}</div>'
f'<a href="{detail_url}" class="inline-flex items-center px-2 py-1 text-[11px] rounded-full border border-stone-300 bg-white hover:bg-stone-50 transition shrink-0">View</a></div></div></td></tr>'
)
def _orders_rows_html(orders: list, page: int, total_pages: int,
url_for_fn: Any, qs_fn: Any) -> str:
"""Render order rows + infinite scroll sentinel."""
from shared.utils import route_prefix
pfx = route_prefix()
parts = [
_order_row_html(o, pfx + url_for_fn("orders.order.order_detail", order_id=o.id))
for o in orders
]
if page < total_pages:
next_url = pfx + url_for_fn("orders.list_orders") + qs_fn(page=page + 1)
parts.append(sexp(
'(~infinite-scroll :url u :page p :total-pages tp :id-prefix "orders" :colspan 5)',
u=next_url, p=page, **{"total-pages": total_pages},
))
else:
parts.append('<tr><td colspan="5" class="px-3 py-4 text-center text-xs text-stone-400">End of results</td></tr>')
return "".join(parts)
def _orders_main_panel_html(orders: list, rows_html: str) -> str:
"""Main panel for orders list."""
if not orders:
return (
'<div class="max-w-full px-3 py-3 space-y-3">'
'<div class="rounded-2xl border border-dashed border-stone-300 bg-white/80 p-4 sm:p-6 text-sm text-stone-700">'
'No orders yet.</div></div>'
)
return (
'<div class="max-w-full px-3 py-3 space-y-3">'
'<div class="overflow-x-auto rounded-2xl border border-stone-200 bg-white/80">'
'<table class="min-w-full text-xs sm:text-sm">'
'<thead class="bg-stone-50 border-b border-stone-200 text-stone-600"><tr>'
'<th class="px-3 py-2 text-left font-medium">Order</th>'
'<th class="px-3 py-2 text-left font-medium">Created</th>'
'<th class="px-3 py-2 text-left font-medium">Description</th>'
'<th class="px-3 py-2 text-left font-medium">Total</th>'
'<th class="px-3 py-2 text-left font-medium">Status</th>'
'<th class="px-3 py-2 text-left font-medium"></th>'
f'</tr></thead><tbody>{rows_html}</tbody></table></div></div>'
)
def _orders_summary_html(ctx: dict) -> str:
"""Filter section for orders list."""
return (
'<header class="mb-6 sm:mb-8 flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4">'
'<div class="space-y-1"><p class="text-xs sm:text-sm text-stone-600">Recent orders placed via the checkout.</p></div>'
f'<div class="md:hidden">{search_mobile_html(ctx)}</div>'
'</header>'
)
# ---------------------------------------------------------------------------
# Single order detail
# ---------------------------------------------------------------------------
def _order_items_html(order: Any) -> str:
"""Render order items list."""
if not order or not order.items:
return ""
items = []
for item in order.items:
prod_url = market_product_url(item.product_slug)
img = (
f'<img src="{item.product_image}" alt="{item.product_title or "Product image"}"'
f' class="w-full h-full object-contain object-center" loading="lazy" decoding="async">'
if item.product_image else
'<div class="w-full h-full flex items-center justify-center text-[9px] text-stone-400">No image</div>'
)
items.append(
f'<li><a class="w-full py-2 flex gap-3" href="{prod_url}">'
f'<div class="w-12 h-12 sm:w-14 sm:h-14 rounded-md bg-stone-100 flex-shrink-0 overflow-hidden">{img}</div>'
f'<div class="flex-1 flex justify-between gap-3">'
f'<div><p class="font-medium">{item.product_title or "Unknown product"}</p>'
f'<p class="text-[11px] text-stone-500">Product ID: {item.product_id}</p></div>'
f'<div class="text-right whitespace-nowrap"><p>Qty: {item.quantity}</p>'
f'<p>{item.currency or order.currency or "GBP"} {item.unit_price or 0:.2f}</p>'
f'</div></div></a></li>'
)
return (
'<div class="rounded-2xl border border-stone-200 bg-white/80 p-4 sm:p-6">'
'<h2 class="text-sm sm:text-base font-semibold mb-3">Items</h2>'
f'<ul class="divide-y divide-stone-100 text-xs sm:text-sm">{"".join(items)}</ul></div>'
)
def _order_summary_html(order: Any) -> str:
"""Order summary card."""
return sexp(
'(~order-summary-card :order-id oid :created-at ca :description d :status s :currency c :total-amount ta)',
oid=order.id,
ca=order.created_at.strftime("%-d %b %Y, %H:%M") if order.created_at else None,
d=order.description, s=order.status, c=order.currency,
ta=f"{order.total_amount:.2f}" if order.total_amount else None,
)
def _order_calendar_items_html(calendar_entries: list | None) -> str:
"""Render calendar bookings for an order."""
if not calendar_entries:
return ""
items = []
for e in calendar_entries:
st = e.state or ""
pill = (
"bg-emerald-100 text-emerald-800" if st == "confirmed"
else "bg-amber-100 text-amber-800" if st == "provisional"
else "bg-blue-100 text-blue-800" if st == "ordered"
else "bg-stone-100 text-stone-700"
)
ds = e.start_at.strftime("%-d %b %Y, %H:%M") if e.start_at else ""
if e.end_at:
ds += f" \u2013 {e.end_at.strftime('%-d %b %Y, %H:%M')}"
items.append(
f'<li class="px-4 py-3 flex items-start justify-between text-sm">'
f'<div><div class="font-medium flex items-center gap-2">{e.name}'
f'<span class="inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium {pill}">'
f'{st.capitalize()}</span></div>'
f'<div class="text-xs text-stone-500">{ds}</div></div>'
f'<div class="ml-4 font-medium">\u00a3{e.cost or 0:.2f}</div></li>'
)
return (
'<section class="mt-6 space-y-3">'
'<h2 class="text-base sm:text-lg font-semibold">Calendar bookings in this order</h2>'
f'<ul class="divide-y divide-stone-200 rounded-2xl border border-stone-200 bg-white/80">{"".join(items)}</ul></section>'
)
def _order_main_html(order: Any, calendar_entries: list | None) -> str:
"""Main panel for single order detail."""
summary = _order_summary_html(order)
return f'<div class="max-w-full px-3 py-3 space-y-4">{summary}{_order_items_html(order)}{_order_calendar_items_html(calendar_entries)}</div>'
def _order_filter_html(order: Any, list_url: str, recheck_url: str,
pay_url: str, csrf_token: str) -> str:
"""Filter section for single order detail."""
created = order.created_at.strftime("%-d %b %Y, %H:%M") if order.created_at else "\u2014"
status = order.status or "pending"
pay = (
f'<a href="{pay_url}" class="inline-flex items-center px-3 py-2 text-xs sm:text-sm '
f'rounded-full border border-emerald-600 bg-emerald-600 text-white hover:bg-emerald-700 transition">'
f'<i class="fa fa-credit-card mr-2" aria-hidden="true"></i>Open payment page</a>'
) if status != "paid" else ""
return (
'<header class="mb-6 sm:mb-8 flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4">'
f'<div class="space-y-1"><p class="text-xs sm:text-sm text-stone-600">Placed {created} &middot; Status: {status}</p></div>'
'<div class="flex w-full sm:w-auto justify-start sm:justify-end gap-2">'
f'<a href="{list_url}" class="inline-flex items-center px-3 py-2 text-xs sm:text-sm rounded-full border border-stone-300 bg-white hover:bg-stone-50 transition"><i class="fa-solid fa-list mr-2" aria-hidden="true"></i>All orders</a>'
f'<form method="post" action="{recheck_url}" class="inline"><input type="hidden" name="csrf_token" value="{csrf_token}">'
f'<button type="submit" class="inline-flex items-center px-3 py-2 text-xs sm:text-sm rounded-full border border-stone-300 bg-white hover:bg-stone-50 transition"><i class="fa-solid fa-rotate mr-2" aria-hidden="true"></i>Re-check status</button></form>'
f'{pay}</div></header>'
)
# ---------------------------------------------------------------------------
# Public API: Cart overview
# ---------------------------------------------------------------------------
async def render_overview_page(ctx: dict, page_groups: list) -> str:
"""Full page: cart overview."""
main = _overview_main_panel_html(page_groups, ctx)
hdr = root_header_html(ctx)
hdr += sexp(
'(div :id "root-header-child" :class "flex flex-col w-full items-center" (raw! c))',
c=_cart_header_html(ctx),
)
return full_page(ctx, header_rows_html=hdr, content_html=main)
async def render_overview_oob(ctx: dict, page_groups: list) -> str:
"""OOB response for cart overview."""
main = _overview_main_panel_html(page_groups, ctx)
oobs = (
_cart_header_html(ctx, oob=True)
+ root_header_html(ctx, oob=True)
)
return oob_page(ctx, oobs_html=oobs, content_html=main)
# ---------------------------------------------------------------------------
# Public API: Page cart
# ---------------------------------------------------------------------------
async def render_page_cart_page(ctx: dict, page_post: Any,
cart: list, cal_entries: list, tickets: list,
ticket_groups: list, total_fn: Any,
cal_total_fn: Any, ticket_total_fn: Any) -> str:
"""Full page: page-specific cart."""
main = _page_cart_main_panel_html(ctx, cart, cal_entries, tickets, ticket_groups,
total_fn, cal_total_fn, ticket_total_fn)
hdr = root_header_html(ctx)
child = _cart_header_html(ctx)
page_hdr = _page_cart_header_html(ctx, page_post)
hdr += sexp(
'(div :id "root-header-child" :class "flex flex-col w-full items-center" (raw! c)'
' (div :id "cart-header-child" :class "flex flex-col w-full items-center" (raw! p)))',
c=child, p=page_hdr,
)
return full_page(ctx, header_rows_html=hdr, content_html=main)
async def render_page_cart_oob(ctx: dict, page_post: Any,
cart: list, cal_entries: list, tickets: list,
ticket_groups: list, total_fn: Any,
cal_total_fn: Any, ticket_total_fn: Any) -> str:
"""OOB response for page cart."""
main = _page_cart_main_panel_html(ctx, cart, cal_entries, tickets, ticket_groups,
total_fn, cal_total_fn, ticket_total_fn)
oobs = (
sexp('(div :id "cart-header-child" :hx-swap-oob "outerHTML" :class "flex flex-col w-full items-center" (raw! p))',
p=_page_cart_header_html(ctx, page_post))
+ _cart_header_html(ctx, oob=True)
+ root_header_html(ctx, oob=True)
)
return oob_page(ctx, oobs_html=oobs, content_html=main)
# ---------------------------------------------------------------------------
# Public API: Orders list
# ---------------------------------------------------------------------------
async def render_orders_page(ctx: dict, orders: list, page: int,
total_pages: int, search: str | None,
search_count: int, url_for_fn: Any,
qs_fn: Any) -> str:
"""Full page: orders list."""
from shared.utils import route_prefix
ctx["search"] = search
ctx["search_count"] = search_count
list_url = route_prefix() + url_for_fn("orders.list_orders")
rows = _orders_rows_html(orders, page, total_pages, url_for_fn, qs_fn)
main = _orders_main_panel_html(orders, rows)
hdr = root_header_html(ctx)
hdr += sexp(
'(div :id "root-header-child" :class "flex flex-col w-full items-center" (raw! a)'
' (div :id "auth-header-child" :class "flex flex-col w-full items-center" (raw! o)))',
a=_auth_header_html(ctx), o=_orders_header_html(ctx, list_url),
)
return full_page(ctx, header_rows_html=hdr,
filter_html=_orders_summary_html(ctx),
aside_html=search_desktop_html(ctx),
content_html=main)
async def render_orders_rows(ctx: dict, orders: list, page: int,
total_pages: int, url_for_fn: Any,
qs_fn: Any) -> str:
"""Pagination: just the table rows."""
return _orders_rows_html(orders, page, total_pages, url_for_fn, qs_fn)
async def render_orders_oob(ctx: dict, orders: list, page: int,
total_pages: int, search: str | None,
search_count: int, url_for_fn: Any,
qs_fn: Any) -> str:
"""OOB response for orders list."""
from shared.utils import route_prefix
ctx["search"] = search
ctx["search_count"] = search_count
list_url = route_prefix() + url_for_fn("orders.list_orders")
rows = _orders_rows_html(orders, page, total_pages, url_for_fn, qs_fn)
main = _orders_main_panel_html(orders, rows)
oobs = (
_auth_header_html(ctx, oob=True)
+ sexp(
'(div :id "auth-header-child" :hx-swap-oob "outerHTML"'
' :class "flex flex-col w-full items-center" (raw! o))',
o=_orders_header_html(ctx, list_url),
)
+ root_header_html(ctx, oob=True)
)
return oob_page(ctx, oobs_html=oobs,
filter_html=_orders_summary_html(ctx),
aside_html=search_desktop_html(ctx),
content_html=main)
# ---------------------------------------------------------------------------
# Public API: Single order detail
# ---------------------------------------------------------------------------
async def render_order_page(ctx: dict, order: Any,
calendar_entries: list | None,
url_for_fn: Any) -> str:
"""Full page: single order detail."""
from shared.utils import route_prefix
from shared.browser.app.csrf import generate_csrf_token
pfx = route_prefix()
detail_url = pfx + url_for_fn("orders.order.order_detail", order_id=order.id)
list_url = pfx + url_for_fn("orders.list_orders")
recheck_url = pfx + url_for_fn("orders.order.order_recheck", order_id=order.id)
pay_url = pfx + url_for_fn("orders.order.order_pay", order_id=order.id)
main = _order_main_html(order, calendar_entries)
filt = _order_filter_html(order, list_url, recheck_url, pay_url, generate_csrf_token())
hdr = root_header_html(ctx)
order_row = sexp(
'(~menu-row :id "order-row" :level 3 :colour "sky" :link-href lh :link-label ll :icon "fa fa-gbp")',
lh=detail_url, ll=f"Order {order.id}",
)
hdr += sexp(
'(div :id "root-header-child" :class "flex flex-col w-full items-center" (raw! a)'
' (div :id "auth-header-child" :class "flex flex-col w-full items-center" (raw! b)'
' (div :id "orders-header-child" :class "flex flex-col w-full items-center" (raw! c))))',
a=_auth_header_html(ctx),
b=_orders_header_html(ctx, list_url),
c=order_row,
)
return full_page(ctx, header_rows_html=hdr, filter_html=filt, content_html=main)
async def render_order_oob(ctx: dict, order: Any,
calendar_entries: list | None,
url_for_fn: Any) -> str:
"""OOB response for single order detail."""
from shared.utils import route_prefix
from shared.browser.app.csrf import generate_csrf_token
pfx = route_prefix()
detail_url = pfx + url_for_fn("orders.order.order_detail", order_id=order.id)
list_url = pfx + url_for_fn("orders.list_orders")
recheck_url = pfx + url_for_fn("orders.order.order_recheck", order_id=order.id)
pay_url = pfx + url_for_fn("orders.order.order_pay", order_id=order.id)
main = _order_main_html(order, calendar_entries)
filt = _order_filter_html(order, list_url, recheck_url, pay_url, generate_csrf_token())
order_row_oob = sexp(
'(~menu-row :id "order-row" :level 3 :colour "sky" :link-href lh :link-label ll :icon "fa fa-gbp" :oob true)',
lh=detail_url, ll=f"Order {order.id}",
)
oobs = (
sexp('(div :id "orders-header-child" :hx-swap-oob "outerHTML" :class "flex flex-col w-full items-center" (raw! o))', o=order_row_oob)
+ root_header_html(ctx, oob=True)
)
return oob_page(ctx, oobs_html=oobs, filter_html=filt, content_html=main)