Files
rose-ash/orders/sexp/sexp_components.py
giles 22802bd36b
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 5m35s
Send all responses as sexp wire format with client-side rendering
- Server sends sexp source text, client (sexp.js) renders everything
- SexpExpr marker class for nested sexp composition in serialize()
- sexp_page() HTML shell with data-mount="body" for full page loads
- sexp_response() returns text/sexp for OOB/partial responses
- ~app-body layout component replaces ~app-layout (no raw!)
- ~rich-text is the only component using raw! (for CMS HTML content)
- Fragment endpoints return text/sexp, auto-wrapped in SexpExpr
- All _*_html() helpers converted to _*_sexp() returning sexp source
- Head auto-hoist: sexp.js moves meta/title/link/script[ld+json]
  from rendered body to document.head automatically
- Unknown components render warning box instead of crashing page
- Component kwargs preserve AST for lazy rendering (fixes <> in kwargs)
- Fix unterminated paren in events/sexp/tickets.sexpr

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 09:45:07 +00:00

394 lines
15 KiB
Python

"""
Orders service s-expression page components.
Each function renders a complete page section (full page, OOB, or pagination)
using shared s-expression components. Called from route handlers in place
of ``render_template()``.
"""
from __future__ import annotations
import os
from typing import Any
from shared.sexp.jinja_bridge import load_service_components
from shared.sexp.helpers import (
call_url, root_header_sexp,
full_page_sexp, header_child_sexp, oob_page_sexp,
sexp_call, SexpExpr,
search_mobile_sexp, search_desktop_sexp,
)
from shared.infrastructure.urls import market_product_url, cart_url
# Load orders-specific .sexpr components at import time
load_service_components(os.path.dirname(os.path.dirname(__file__)))
# ---------------------------------------------------------------------------
# Header helpers (shared auth + orders-specific) — sexp-native
# ---------------------------------------------------------------------------
def _auth_nav_sexp(ctx: dict) -> str:
"""Auth section desktop nav items as sexp."""
parts = [
sexp_call("nav-link",
href=call_url(ctx, "account_url", "/newsletters/"),
label="newsletters",
select_colours=ctx.get("select_colours", ""),
),
]
account_nav = ctx.get("account_nav")
if account_nav:
parts.append(str(account_nav))
return "(<> " + " ".join(parts) + ")"
def _auth_header_sexp(ctx: dict, *, oob: bool = False) -> str:
"""Build the account section header row as sexp."""
return sexp_call(
"menu-row-sx",
id="auth-row", level=1, colour="sky",
link_href=call_url(ctx, "account_url", "/"),
link_label="account", icon="fa-solid fa-user",
nav=SexpExpr(_auth_nav_sexp(ctx)),
child_id="auth-header-child", oob=oob,
)
def _orders_header_sexp(ctx: dict, list_url: str) -> str:
"""Build the orders section header row as sexp."""
return sexp_call(
"menu-row-sx",
id="orders-row", level=2, colour="sky",
link_href=list_url, link_label="Orders", icon="fa fa-gbp",
child_id="orders-header-child",
)
# ---------------------------------------------------------------------------
# Orders list rendering
# ---------------------------------------------------------------------------
def _status_pill_cls(status: str) -> str:
"""Return Tailwind classes for order status pill."""
sl = status.lower()
if sl == "paid":
return "border-emerald-300 bg-emerald-50 text-emerald-700"
if sl in ("failed", "cancelled"):
return "border-rose-300 bg-rose-50 text-rose-700"
return "border-stone-300 bg-stone-50 text-stone-700"
def _order_row_data(order: Any, detail_url: str) -> dict:
"""Extract display data from an order model object."""
status = order.status or "pending"
pill = _status_pill_cls(status)
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 dict(
oid=f"#{order.id}", created=created,
desc=order.description or "", total=total,
pill_desktop=f"inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] sm:text-xs {pill}",
pill_mobile=f"inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] {pill}",
status=status, url=detail_url,
)
def _orders_rows_sexp(orders: list, page: int, total_pages: int,
url_for_fn: Any, qs_fn: Any) -> str:
"""S-expression wire format for order rows (client renders)."""
from shared.utils import route_prefix
pfx = route_prefix()
parts = []
for o in orders:
d = _order_row_data(o, pfx + url_for_fn("orders.order.order_detail", order_id=o.id))
parts.append(sexp_call("orders-row-desktop",
oid=d["oid"], created=d["created"],
desc=d["desc"], total=d["total"],
pill=d["pill_desktop"], status=d["status"],
url=d["url"]))
parts.append(sexp_call("orders-row-mobile",
oid=d["oid"], created=d["created"],
total=d["total"], pill=d["pill_mobile"],
status=d["status"], url=d["url"]))
if page < total_pages:
next_url = pfx + url_for_fn("orders.list_orders") + qs_fn(page=page + 1)
parts.append(sexp_call("infinite-scroll",
url=next_url, page=page,
total_pages=total_pages,
id_prefix="orders", colspan=5))
else:
parts.append(sexp_call("orders-end-row"))
return "(<> " + " ".join(parts) + ")"
def _orders_main_panel_sexp(orders: list, rows_sexp: str) -> str:
"""Main panel with table or empty state (sexp)."""
if not orders:
return sexp_call("orders-empty-state")
return sexp_call("orders-table", rows=SexpExpr(rows_sexp))
def _orders_summary_sexp(ctx: dict) -> str:
"""Filter section for orders list (sexp)."""
return sexp_call("orders-summary", search_mobile=SexpExpr(search_mobile_sexp(ctx)))
# ---------------------------------------------------------------------------
# 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 (sexp wire format)."""
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_sexp(orders, page, total_pages, url_for_fn, qs_fn)
main = _orders_main_panel_sexp(orders, rows)
hdr = root_header_sexp(ctx)
inner = "(<> " + _auth_header_sexp(ctx) + " " + _orders_header_sexp(ctx, list_url) + ")"
hdr = "(<> " + hdr + " " + header_child_sexp(inner) + ")"
return full_page_sexp(ctx, header_rows=hdr,
filter=_orders_summary_sexp(ctx),
aside=search_desktop_sexp(ctx),
content=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 (sexp wire format)."""
return _orders_rows_sexp(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 HTMX navigation to orders list (sexp)."""
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_sexp(orders, page, total_pages, url_for_fn, qs_fn)
main = _orders_main_panel_sexp(orders, rows)
auth_hdr = _auth_header_sexp(ctx, oob=True)
auth_child_oob = sexp_call("orders-auth-header-child-oob",
inner=SexpExpr(_orders_header_sexp(ctx, list_url)))
root_hdr = root_header_sexp(ctx, oob=True)
oobs = "(<> " + auth_hdr + " " + auth_child_oob + " " + root_hdr + ")"
return oob_page_sexp(oobs=oobs,
filter=_orders_summary_sexp(ctx),
aside=search_desktop_sexp(ctx),
content=main)
# ---------------------------------------------------------------------------
# Single order detail
# ---------------------------------------------------------------------------
def _order_items_sexp(order: Any) -> str:
"""Render order items list as sexp."""
if not order or not order.items:
return ""
items = []
for item in order.items:
prod_url = market_product_url(item.product_slug)
if item.product_image:
img = sexp_call(
"orders-item-image",
src=item.product_image, alt=item.product_title or "Product image",
)
else:
img = sexp_call("orders-item-no-image")
items.append(sexp_call(
"orders-item-row",
href=prod_url, img=SexpExpr(img),
title=item.product_title or "Unknown product",
pid=str(item.product_id),
qty=str(item.quantity),
price=f"{item.currency or order.currency or 'GBP'} {item.unit_price or 0:.2f}",
))
items_sexp = "(<> " + " ".join(items) + ")"
return sexp_call("orders-items-section", items=SexpExpr(items_sexp))
def _calendar_items_sexp(calendar_entries: list | None) -> str:
"""Render calendar bookings for an order as sexp."""
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(sexp_call(
"orders-calendar-item",
name=e.name,
pill=f"inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium {pill}",
state=st.capitalize(), ds=ds,
cost=f"\u00a3{e.cost or 0:.2f}",
))
items_sexp = "(<> " + " ".join(items) + ")"
return sexp_call("orders-calendar-section", items=SexpExpr(items_sexp))
def _order_main_sexp(order: Any, calendar_entries: list | None) -> str:
"""Main panel for single order detail (sexp)."""
summary = sexp_call(
"order-summary-card",
order_id=order.id,
created_at=order.created_at.strftime("%-d %b %Y, %H:%M") if order.created_at else None,
description=order.description, status=order.status, currency=order.currency,
total_amount=f"{order.total_amount:.2f}" if order.total_amount else None,
)
items = _order_items_sexp(order)
calendar = _calendar_items_sexp(calendar_entries)
return sexp_call(
"orders-detail-panel",
summary=SexpExpr(summary),
items=SexpExpr(items) if items else None,
calendar=SexpExpr(calendar) if calendar else None,
)
def _order_filter_sexp(order: Any, list_url: str, recheck_url: str,
pay_url: str, csrf_token: str) -> str:
"""Filter section for single order detail (sexp)."""
created = order.created_at.strftime("%-d %b %Y, %H:%M") if order.created_at else "\u2014"
status = order.status or "pending"
pay = ""
if status != "paid":
pay = sexp_call("orders-checkout-error-pay-btn", url=pay_url)
return sexp_call(
"orders-detail-filter",
created=created, status=status,
list_url=list_url, recheck_url=recheck_url,
csrf=csrf_token,
pay=SexpExpr(pay) if pay else None,
)
async def render_order_page(ctx: dict, order: Any,
calendar_entries: list | None,
url_for_fn: Any) -> str:
"""Full page: single order detail (sexp wire format)."""
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_sexp(order, calendar_entries)
filt = _order_filter_sexp(order, list_url, recheck_url, pay_url, generate_csrf_token())
# Header stack: root -> auth -> orders -> order
hdr = root_header_sexp(ctx)
order_row = sexp_call(
"menu-row-sx",
id="order-row", level=3, colour="sky", link_href=detail_url,
link_label="Order", icon="fa fa-gbp",
)
detail_header = sexp_call(
"orders-detail-header-stack",
auth=SexpExpr(_auth_header_sexp(ctx)),
orders=SexpExpr(_orders_header_sexp(ctx, list_url)),
order=SexpExpr(order_row),
)
hdr = "(<> " + hdr + " " + detail_header + ")"
return full_page_sexp(ctx, header_rows=hdr, filter=filt, content=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 (sexp)."""
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_sexp(order, calendar_entries)
filt = _order_filter_sexp(order, list_url, recheck_url, pay_url, generate_csrf_token())
order_row_oob = sexp_call(
"menu-row-sx",
id="order-row", level=3, colour="sky", link_href=detail_url,
link_label="Order", icon="fa fa-gbp", oob=True,
)
header_child_oob = sexp_call("orders-header-child-oob",
inner=SexpExpr(order_row_oob))
root_hdr = root_header_sexp(ctx, oob=True)
oobs = "(<> " + header_child_oob + " " + root_hdr + ")"
return oob_page_sexp(oobs=oobs, filter=filt, content=main)
# ---------------------------------------------------------------------------
# Public API: Checkout error
# ---------------------------------------------------------------------------
def _checkout_error_filter_sexp() -> str:
return sexp_call("orders-checkout-error-header")
def _checkout_error_content_sexp(error: str | None, order: Any | None) -> str:
err_msg = error or "Unexpected error while creating the hosted checkout session."
order_sexp = ""
if order:
order_sexp = sexp_call("orders-checkout-error-order-id", oid=f"#{order.id}")
back_url = cart_url("/")
return sexp_call(
"orders-checkout-error-content",
msg=err_msg,
order=SexpExpr(order_sexp) if order_sexp else None,
back_url=back_url,
)
async def render_checkout_error_page(ctx: dict, error: str | None = None, order: Any | None = None) -> str:
"""Full page: checkout error (sexp wire format)."""
hdr = root_header_sexp(ctx)
inner = _auth_header_sexp(ctx)
hdr = "(<> " + hdr + " " + header_child_sexp(inner) + ")"
filt = _checkout_error_filter_sexp()
content = _checkout_error_content_sexp(error, order)
return full_page_sexp(ctx, header_rows=hdr, filter=filt, content=content)