All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 1m43s
- Remove old raw! layout components (~app-head, ~app-layout, ~oob-response, ~header-row, ~menu-row, ~oob-header, ~header-child) from layout.sexp - Convert nav-tree fragment from Jinja HTML to sexp source, fixing the "Unexpected character: ." parse error caused by HTML leaking into sexp - Add _as_sexp() helper to safely coerce HTML fragments to ~rich-text - Fix federation/sexp/search.sexpr extra closing paren - Remove dead _html() wrappers from blog and account sexp_components - Remove stale render import from cart sexp_components - Add dev_watcher.py to auto-reload on .sexp/.sexpr/.js/.css changes - Add test_parse_all.py to parse-check all 59 sexpr/sexp files - Fix test assertions for sx- attribute prefix (was hx-) - Add sexp.js version logging for cache debugging Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
878 lines
35 KiB
Python
878 lines
35 KiB
Python
"""
|
|
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
|
|
|
|
import os
|
|
from typing import Any
|
|
from markupsafe import escape
|
|
|
|
from shared.sexp.jinja_bridge import load_service_components
|
|
from shared.sexp.helpers import (
|
|
call_url, root_header_sexp, post_admin_header_sexp,
|
|
post_header_sexp as _shared_post_header_sexp,
|
|
search_desktop_sexp, search_mobile_sexp,
|
|
full_page_sexp, oob_page_sexp, header_child_sexp,
|
|
sexp_call, SexpExpr,
|
|
)
|
|
from shared.infrastructure.urls import market_product_url, cart_url
|
|
|
|
# Load cart-specific .sexpr components at import time
|
|
load_service_components(os.path.dirname(os.path.dirname(__file__)))
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Header helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _ensure_post_ctx(ctx: dict, page_post: Any) -> dict:
|
|
"""Ensure ctx has a 'post' dict from page_post DTO (for shared post_header_sexp)."""
|
|
if ctx.get("post") or not page_post:
|
|
return ctx
|
|
ctx = {**ctx, "post": {
|
|
"id": getattr(page_post, "id", None),
|
|
"slug": getattr(page_post, "slug", ""),
|
|
"title": getattr(page_post, "title", ""),
|
|
"feature_image": getattr(page_post, "feature_image", None),
|
|
}}
|
|
return ctx
|
|
|
|
|
|
async def _ensure_container_nav(ctx: dict) -> dict:
|
|
"""Fetch container_nav if not already present (for post header row)."""
|
|
if ctx.get("container_nav"):
|
|
return ctx
|
|
post = ctx.get("post") or {}
|
|
post_id = post.get("id")
|
|
slug = post.get("slug", "")
|
|
if not post_id:
|
|
return ctx
|
|
from shared.infrastructure.fragments import fetch_fragments
|
|
nav_params = {
|
|
"container_type": "page",
|
|
"container_id": str(post_id),
|
|
"post_slug": slug,
|
|
}
|
|
events_nav, market_nav = await fetch_fragments([
|
|
("events", "container-nav", nav_params),
|
|
("market", "container-nav", nav_params),
|
|
], required=False)
|
|
return {**ctx, "container_nav": events_nav + market_nav}
|
|
|
|
|
|
async def _post_header_sexp(ctx: dict, page_post: Any, *, oob: bool = False) -> str:
|
|
"""Build post-level header row from page_post DTO, using shared helper."""
|
|
ctx = _ensure_post_ctx(ctx, page_post)
|
|
ctx = await _ensure_container_nav(ctx)
|
|
return _shared_post_header_sexp(ctx, oob=oob)
|
|
|
|
|
|
def _cart_header_sexp(ctx: dict, *, oob: bool = False) -> str:
|
|
"""Build the cart section header row."""
|
|
return sexp_call(
|
|
"menu-row-sx",
|
|
id="cart-row", level=1, colour="sky",
|
|
link_href=call_url(ctx, "cart_url", "/"),
|
|
link_label="cart", icon="fa fa-shopping-cart",
|
|
child_id="cart-header-child", oob=oob,
|
|
)
|
|
|
|
|
|
def _page_cart_header_sexp(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 if page_post else None) or "")[:160]
|
|
label_parts = []
|
|
if page_post and page_post.feature_image:
|
|
label_parts.append(sexp_call("cart-page-label-img", src=page_post.feature_image))
|
|
label_parts.append(f'(span "{escape(title)}")')
|
|
label_sexp = "(<> " + " ".join(label_parts) + ")"
|
|
nav_sexp = sexp_call("cart-all-carts-link", href=call_url(ctx, "cart_url", "/"))
|
|
return sexp_call(
|
|
"menu-row-sx",
|
|
id="page-cart-row", level=2, colour="sky",
|
|
link_href=call_url(ctx, "cart_url", f"/{slug}/"),
|
|
link_label_content=SexpExpr(label_sexp),
|
|
nav=SexpExpr(nav_sexp), oob=oob,
|
|
)
|
|
|
|
|
|
def _auth_header_sexp(ctx: dict, *, oob: bool = False) -> str:
|
|
"""Build the account section header row (for orders)."""
|
|
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",
|
|
child_id="auth-header-child", oob=oob,
|
|
)
|
|
|
|
|
|
def _orders_header_sexp(ctx: dict, list_url: str) -> str:
|
|
"""Build the orders section header row."""
|
|
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",
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Cart overview
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _badge_sexp(icon: str, count: int, label: str) -> str:
|
|
"""Render a count badge."""
|
|
s = "s" if count != 1 else ""
|
|
return sexp_call("cart-badge", icon=icon, text=f"{count} {label}{s}")
|
|
|
|
|
|
def _page_group_card_sexp(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
|
|
badge_parts = []
|
|
if product_count > 0:
|
|
badge_parts.append(_badge_sexp("fa fa-box-open", product_count, "item"))
|
|
if calendar_count > 0:
|
|
badge_parts.append(_badge_sexp("fa fa-calendar", calendar_count, "booking"))
|
|
if ticket_count > 0:
|
|
badge_parts.append(_badge_sexp("fa fa-ticket", ticket_count, "ticket"))
|
|
badges_sexp = "(<> " + " ".join(badge_parts) + ")" if badge_parts else '""'
|
|
badges_wrap = sexp_call("cart-badges-wrap", badges=SexpExpr(badges_sexp))
|
|
|
|
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_href = call_url(ctx, "cart_url", f"/{slug}/")
|
|
|
|
if feature_image:
|
|
img = sexp_call("cart-group-card-img", src=feature_image, alt=title)
|
|
else:
|
|
img = sexp_call("cart-group-card-placeholder")
|
|
|
|
mp_sub = ""
|
|
if market_place:
|
|
mp_name = market_place.name if hasattr(market_place, "name") else market_place.get("name", "")
|
|
mp_sub = sexp_call("cart-mp-subtitle", title=title)
|
|
else:
|
|
mp_name = ""
|
|
display_title = mp_name or title
|
|
|
|
return sexp_call(
|
|
"cart-group-card",
|
|
href=cart_href, img=SexpExpr(img), display_title=display_title,
|
|
subtitle=SexpExpr(mp_sub) if mp_sub else None,
|
|
badges=SexpExpr(badges_wrap),
|
|
total=f"\u00a3{total:.2f}",
|
|
)
|
|
else:
|
|
# Orphan items
|
|
return sexp_call(
|
|
"cart-orphan-card",
|
|
badges=SexpExpr(badges_wrap),
|
|
total=f"\u00a3{total:.2f}",
|
|
)
|
|
|
|
|
|
def _empty_cart_sexp() -> str:
|
|
"""Empty cart state."""
|
|
return sexp_call("cart-empty")
|
|
|
|
|
|
def _overview_main_panel_sexp(page_groups: list, ctx: dict) -> str:
|
|
"""Cart overview main panel."""
|
|
if not page_groups:
|
|
return _empty_cart_sexp()
|
|
|
|
cards = [_page_group_card_sexp(grp, ctx) for grp in page_groups]
|
|
has_items = any(c for c in cards)
|
|
if not has_items:
|
|
return _empty_cart_sexp()
|
|
|
|
cards_sexp = "(<> " + " ".join(c for c in cards if c) + ")"
|
|
return sexp_call("cart-overview-panel", cards=SexpExpr(cards_sexp))
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Page cart
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _cart_item_sexp(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 = sexp_call("cart-item-img", src=p.image, alt=p.title)
|
|
else:
|
|
img = sexp_call("cart-item-no-img")
|
|
|
|
price_parts = []
|
|
if unit_price:
|
|
price_parts.append(sexp_call("cart-item-price", text=f"{symbol}{unit_price:.2f}"))
|
|
if p.special_price and p.special_price != p.regular_price:
|
|
price_parts.append(sexp_call("cart-item-price-was", text=f"{symbol}{p.regular_price:.2f}"))
|
|
else:
|
|
price_parts.append(sexp_call("cart-item-no-price"))
|
|
price_sexp = "(<> " + " ".join(price_parts) + ")" if len(price_parts) > 1 else price_parts[0]
|
|
|
|
deleted_sexp = sexp_call("cart-item-deleted") if getattr(item, "is_deleted", False) else None
|
|
|
|
brand_sexp = sexp_call("cart-item-brand", brand=p.brand) if getattr(p, "brand", None) else None
|
|
|
|
line_total_sexp = None
|
|
if unit_price:
|
|
lt = unit_price * item.quantity
|
|
line_total_sexp = sexp_call("cart-item-line-total", text=f"Line total: {symbol}{lt:.2f}")
|
|
|
|
return sexp_call(
|
|
"cart-item",
|
|
id=f"cart-item-{slug}", img=SexpExpr(img), prod_url=prod_url, title=p.title,
|
|
brand=SexpExpr(brand_sexp) if brand_sexp else None,
|
|
deleted=SexpExpr(deleted_sexp) if deleted_sexp else None,
|
|
price=SexpExpr(price_sexp),
|
|
qty_url=qty_url, csrf=csrf, minus=str(item.quantity - 1),
|
|
qty=str(item.quantity), plus=str(item.quantity + 1),
|
|
line_total=SexpExpr(line_total_sexp) if line_total_sexp else None,
|
|
)
|
|
|
|
|
|
def _calendar_entries_sexp(entries: list) -> str:
|
|
"""Render calendar booking entries in cart."""
|
|
if not entries:
|
|
return ""
|
|
parts = []
|
|
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_str = f" \u2013 {end}" if end else ""
|
|
parts.append(sexp_call(
|
|
"cart-cal-entry",
|
|
name=name, date_str=f"{start}{end_str}", cost=f"\u00a3{cost:.2f}",
|
|
))
|
|
items_sexp = "(<> " + " ".join(parts) + ")"
|
|
return sexp_call("cart-cal-section", items=SexpExpr(items_sexp))
|
|
|
|
|
|
def _ticket_groups_sexp(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 = []
|
|
|
|
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_sexp = sexp_call("cart-ticket-type-name", name=tt_name) if tt_name else None
|
|
tt_hidden_sexp = sexp_call("cart-ticket-type-hidden", value=str(tt_id)) if tt_id else None
|
|
|
|
parts.append(sexp_call(
|
|
"cart-ticket-article",
|
|
name=name,
|
|
type_name=SexpExpr(tt_name_sexp) if tt_name_sexp else None,
|
|
date_str=date_str,
|
|
price=f"\u00a3{price or 0:.2f}", qty_url=qty_url, csrf=csrf,
|
|
entry_id=str(entry_id),
|
|
type_hidden=SexpExpr(tt_hidden_sexp) if tt_hidden_sexp else None,
|
|
minus=str(max(quantity - 1, 0)), qty=str(quantity),
|
|
plus=str(quantity + 1), line_total=f"Line total: \u00a3{line_total:.2f}",
|
|
))
|
|
|
|
items_sexp = "(<> " + " ".join(parts) + ")"
|
|
return sexp_call("cart-tickets-section", items=SexpExpr(items_sexp))
|
|
|
|
|
|
def _cart_summary_sexp(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_sexp = sexp_call(
|
|
"cart-checkout-form",
|
|
action=action, csrf=csrf, label=f" Checkout as {user.email}",
|
|
)
|
|
else:
|
|
href = login_url(request.url)
|
|
checkout_sexp = sexp_call("cart-checkout-signin", href=href)
|
|
|
|
return sexp_call(
|
|
"cart-summary-panel",
|
|
item_count=str(item_count), subtotal=f"{symbol}{grand:.2f}",
|
|
checkout=SexpExpr(checkout_sexp),
|
|
)
|
|
|
|
|
|
def _page_cart_main_panel_sexp(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 sexp_call("cart-page-empty")
|
|
|
|
item_parts = [_cart_item_sexp(item, ctx) for item in cart]
|
|
items_sexp = "(<> " + " ".join(item_parts) + ")" if item_parts else '""'
|
|
cal_sexp = _calendar_entries_sexp(cal_entries)
|
|
tickets_sexp = _ticket_groups_sexp(ticket_groups, ctx)
|
|
summary_sexp = _cart_summary_sexp(ctx, cart, cal_entries, tickets, total_fn, cal_total_fn, ticket_total_fn)
|
|
|
|
return sexp_call(
|
|
"cart-page-panel",
|
|
items=SexpExpr(items_sexp),
|
|
cal=SexpExpr(cal_sexp) if cal_sexp else None,
|
|
tickets=SexpExpr(tickets_sexp) if tickets_sexp else None,
|
|
summary=SexpExpr(summary_sexp),
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Orders list (same pattern as orders service)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _order_row_sexp(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"
|
|
)
|
|
pill_cls = f"inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] sm:text-xs {pill}"
|
|
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}"
|
|
|
|
desktop = sexp_call(
|
|
"cart-order-row-desktop",
|
|
order_id=f"#{order.id}", created=created, desc=order.description or "",
|
|
total=total, pill=pill_cls, status=status, detail_url=detail_url,
|
|
)
|
|
|
|
mobile_pill = f"inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] {pill}"
|
|
mobile = sexp_call(
|
|
"cart-order-row-mobile",
|
|
order_id=f"#{order.id}", pill=mobile_pill, status=status,
|
|
created=created, total=total, detail_url=detail_url,
|
|
)
|
|
|
|
return "(<> " + desktop + " " + mobile + ")"
|
|
|
|
|
|
def _orders_rows_sexp(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_sexp(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_call(
|
|
"infinite-scroll",
|
|
url=next_url, page=page, total_pages=total_pages,
|
|
id_prefix="orders", colspan=5,
|
|
))
|
|
else:
|
|
parts.append(sexp_call("cart-orders-end"))
|
|
|
|
return "(<> " + " ".join(parts) + ")"
|
|
|
|
|
|
def _orders_main_panel_sexp(orders: list, rows_sexp: str) -> str:
|
|
"""Main panel for orders list."""
|
|
if not orders:
|
|
return sexp_call("cart-orders-empty")
|
|
return sexp_call("cart-orders-table", rows=SexpExpr(rows_sexp))
|
|
|
|
|
|
def _orders_summary_sexp(ctx: dict) -> str:
|
|
"""Filter section for orders list."""
|
|
return sexp_call("cart-orders-filter", search_mobile=SexpExpr(search_mobile_sexp(ctx)))
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Single order detail
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _order_items_sexp(order: Any) -> str:
|
|
"""Render order items list."""
|
|
if not order or not order.items:
|
|
return ""
|
|
parts = []
|
|
for item in order.items:
|
|
prod_url = market_product_url(item.product_slug)
|
|
if item.product_image:
|
|
img = sexp_call(
|
|
"cart-order-item-img",
|
|
src=item.product_image, alt=item.product_title or "Product image",
|
|
)
|
|
else:
|
|
img = sexp_call("cart-order-item-no-img")
|
|
parts.append(sexp_call(
|
|
"cart-order-item",
|
|
prod_url=prod_url, img=SexpExpr(img),
|
|
title=item.product_title or "Unknown product",
|
|
product_id=f"Product ID: {item.product_id}",
|
|
qty=f"Qty: {item.quantity}",
|
|
price=f"{item.currency or order.currency or 'GBP'} {item.unit_price or 0:.2f}",
|
|
))
|
|
items_sexp = "(<> " + " ".join(parts) + ")"
|
|
return sexp_call("cart-order-items-panel", items=SexpExpr(items_sexp))
|
|
|
|
|
|
def _order_summary_sexp(order: Any) -> str:
|
|
"""Order summary card."""
|
|
return 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,
|
|
)
|
|
|
|
|
|
def _order_calendar_items_sexp(calendar_entries: list | None) -> str:
|
|
"""Render calendar bookings for an order."""
|
|
if not calendar_entries:
|
|
return ""
|
|
parts = []
|
|
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"
|
|
)
|
|
pill_cls = f"inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium {pill}"
|
|
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')}"
|
|
parts.append(sexp_call(
|
|
"cart-order-cal-entry",
|
|
name=e.name, pill=pill_cls, status=st.capitalize(),
|
|
date_str=ds, cost=f"\u00a3{e.cost or 0:.2f}",
|
|
))
|
|
items_sexp = "(<> " + " ".join(parts) + ")"
|
|
return sexp_call("cart-order-cal-section", items=SexpExpr(items_sexp))
|
|
|
|
|
|
def _order_main_sexp(order: Any, calendar_entries: list | None) -> str:
|
|
"""Main panel for single order detail."""
|
|
summary = _order_summary_sexp(order)
|
|
items = _order_items_sexp(order)
|
|
cal = _order_calendar_items_sexp(calendar_entries)
|
|
return sexp_call(
|
|
"cart-order-main",
|
|
summary=SexpExpr(summary),
|
|
items=SexpExpr(items) if items else None,
|
|
cal=SexpExpr(cal) if cal 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."""
|
|
created = order.created_at.strftime("%-d %b %Y, %H:%M") if order.created_at else "\u2014"
|
|
status = order.status or "pending"
|
|
|
|
pay_sexp = None
|
|
if status != "paid":
|
|
pay_sexp = sexp_call("cart-order-pay-btn", url=pay_url)
|
|
|
|
return sexp_call(
|
|
"cart-order-filter",
|
|
info=f"Placed {created} \u00b7 Status: {status}",
|
|
list_url=list_url, recheck_url=recheck_url, csrf=csrf_token,
|
|
pay=SexpExpr(pay_sexp) if pay_sexp else None,
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Public API: Cart overview
|
|
# ---------------------------------------------------------------------------
|
|
|
|
async def render_overview_page(ctx: dict, page_groups: list) -> str:
|
|
"""Full page: cart overview."""
|
|
main = _overview_main_panel_sexp(page_groups, ctx)
|
|
hdr = root_header_sexp(ctx)
|
|
return full_page_sexp(ctx, header_rows=hdr, content=main)
|
|
|
|
|
|
async def render_overview_oob(ctx: dict, page_groups: list) -> str:
|
|
"""OOB response for cart overview."""
|
|
main = _overview_main_panel_sexp(page_groups, ctx)
|
|
oobs = root_header_sexp(ctx, oob=True)
|
|
return oob_page_sexp(oobs=oobs, content=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_sexp(ctx, cart, cal_entries, tickets, ticket_groups,
|
|
total_fn, cal_total_fn, ticket_total_fn)
|
|
hdr = root_header_sexp(ctx)
|
|
child = _cart_header_sexp(ctx)
|
|
page_hdr = _page_cart_header_sexp(ctx, page_post)
|
|
nested = sexp_call(
|
|
"cart-header-child-nested",
|
|
outer=SexpExpr(child), inner=SexpExpr(page_hdr),
|
|
)
|
|
header_rows = "(<> " + hdr + " " + nested + ")"
|
|
return full_page_sexp(ctx, header_rows=header_rows, content=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_sexp(ctx, cart, cal_entries, tickets, ticket_groups,
|
|
total_fn, cal_total_fn, ticket_total_fn)
|
|
child_oob = sexp_call("cart-header-child-oob",
|
|
inner=SexpExpr(_page_cart_header_sexp(ctx, page_post)))
|
|
cart_hdr_oob = _cart_header_sexp(ctx, oob=True)
|
|
root_hdr_oob = root_header_sexp(ctx, oob=True)
|
|
oobs = "(<> " + child_oob + " " + cart_hdr_oob + " " + root_hdr_oob + ")"
|
|
return oob_page_sexp(oobs=oobs, content=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_sexp(orders, page, total_pages, url_for_fn, qs_fn)
|
|
main = _orders_main_panel_sexp(orders, rows)
|
|
|
|
hdr = root_header_sexp(ctx)
|
|
auth = _auth_header_sexp(ctx)
|
|
orders_hdr = _orders_header_sexp(ctx, list_url)
|
|
auth_child = sexp_call(
|
|
"cart-auth-header-child",
|
|
auth=SexpExpr(auth), orders=SexpExpr(orders_hdr),
|
|
)
|
|
header_rows = "(<> " + hdr + " " + auth_child + ")"
|
|
|
|
return full_page_sexp(ctx, header_rows=header_rows,
|
|
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."""
|
|
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 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_sexp(orders, page, total_pages, url_for_fn, qs_fn)
|
|
main = _orders_main_panel_sexp(orders, rows)
|
|
|
|
auth_oob = _auth_header_sexp(ctx, oob=True)
|
|
auth_child_oob = sexp_call(
|
|
"cart-auth-header-child-oob",
|
|
inner=SexpExpr(_orders_header_sexp(ctx, list_url)),
|
|
)
|
|
root_oob = root_header_sexp(ctx, oob=True)
|
|
oobs = "(<> " + auth_oob + " " + auth_child_oob + " " + root_oob + ")"
|
|
|
|
return oob_page_sexp(oobs=oobs,
|
|
filter=_orders_summary_sexp(ctx),
|
|
aside=search_desktop_sexp(ctx),
|
|
content=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_sexp(order, calendar_entries)
|
|
filt = _order_filter_sexp(order, list_url, recheck_url, pay_url, generate_csrf_token())
|
|
|
|
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=f"Order {order.id}", icon="fa fa-gbp",
|
|
)
|
|
order_child = sexp_call(
|
|
"cart-order-header-child",
|
|
auth=SexpExpr(_auth_header_sexp(ctx)),
|
|
orders=SexpExpr(_orders_header_sexp(ctx, list_url)),
|
|
order=SexpExpr(order_row),
|
|
)
|
|
header_rows = "(<> " + hdr + " " + order_child + ")"
|
|
|
|
return full_page_sexp(ctx, header_rows=header_rows, 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."""
|
|
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=f"Order {order.id}", icon="fa fa-gbp",
|
|
oob=True,
|
|
)
|
|
orders_child_oob = sexp_call("cart-orders-header-child-oob",
|
|
inner=SexpExpr(order_row_oob))
|
|
root_oob = root_header_sexp(ctx, oob=True)
|
|
oobs = "(<> " + orders_child_oob + " " + root_oob + ")"
|
|
|
|
return oob_page_sexp(oobs=oobs, filter=filt, content=main)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Public API: Checkout error
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _checkout_error_filter_sexp() -> str:
|
|
return sexp_call("cart-checkout-error-filter")
|
|
|
|
|
|
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 = None
|
|
if order:
|
|
order_sexp = sexp_call("cart-checkout-error-order-id", order_id=f"#{order.id}")
|
|
back_url = cart_url("/")
|
|
return sexp_call(
|
|
"cart-checkout-error-content",
|
|
error_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."""
|
|
hdr = root_header_sexp(ctx)
|
|
filt = _checkout_error_filter_sexp()
|
|
content = _checkout_error_content_sexp(error, order)
|
|
return full_page_sexp(ctx, header_rows=hdr, filter=filt, content=content)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Page admin (/<page_slug>/admin/)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _cart_page_admin_header_sexp(ctx: dict, page_post: Any, *, oob: bool = False,
|
|
selected: str = "") -> str:
|
|
"""Build the page-level admin header row -- delegates to shared helper."""
|
|
slug = page_post.slug if page_post else ""
|
|
ctx = _ensure_post_ctx(ctx, page_post)
|
|
return post_admin_header_sexp(ctx, slug, oob=oob, selected=selected)
|
|
|
|
|
|
def _cart_admin_main_panel_sexp(ctx: dict) -> str:
|
|
"""Admin overview panel -- links to sub-admin pages."""
|
|
from quart import url_for
|
|
payments_href = url_for("page_admin.payments")
|
|
return (
|
|
'(div :id "main-panel"'
|
|
' (div :class "flex items-center justify-between p-3 border-b"'
|
|
' (span :class "font-medium" (i :class "fa fa-credit-card text-purple-600 mr-1") " Payments")'
|
|
f' (a :href "{payments_href}" :class "text-sm underline" "configure")))'
|
|
)
|
|
|
|
|
|
def _cart_payments_main_panel_sexp(ctx: dict) -> str:
|
|
"""Render SumUp payment config form."""
|
|
from quart import url_for
|
|
csrf_token = ctx.get("csrf_token")
|
|
csrf = csrf_token() if callable(csrf_token) else (csrf_token or "")
|
|
page_config = ctx.get("page_config")
|
|
sumup_configured = bool(page_config and getattr(page_config, "sumup_api_key", None))
|
|
merchant_code = (getattr(page_config, "sumup_merchant_code", None) or "") if page_config else ""
|
|
checkout_prefix = (getattr(page_config, "sumup_checkout_prefix", None) or "") if page_config else ""
|
|
update_url = url_for("page_admin.update_sumup")
|
|
|
|
placeholder = "--------" if sumup_configured else "sup_sk_..."
|
|
input_cls = "w-full px-3 py-1.5 text-sm border border-stone-300 rounded focus:ring-purple-500 focus:border-purple-500"
|
|
|
|
return sexp_call("cart-payments-panel",
|
|
update_url=update_url, csrf=csrf,
|
|
merchant_code=merchant_code, placeholder=placeholder,
|
|
input_cls=input_cls, sumup_configured=sumup_configured,
|
|
checkout_prefix=checkout_prefix)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Public API: Cart page admin
|
|
# ---------------------------------------------------------------------------
|
|
|
|
async def render_cart_admin_page(ctx: dict, page_post: Any) -> str:
|
|
"""Full page: cart page admin overview."""
|
|
content = _cart_admin_main_panel_sexp(ctx)
|
|
root_hdr = root_header_sexp(ctx)
|
|
post_hdr = await _post_header_sexp(ctx, page_post)
|
|
admin_hdr = _cart_page_admin_header_sexp(ctx, page_post)
|
|
header_rows = "(<> " + root_hdr + " " + post_hdr + " " + admin_hdr + ")"
|
|
return full_page_sexp(ctx, header_rows=header_rows, content=content)
|
|
|
|
|
|
async def render_cart_admin_oob(ctx: dict, page_post: Any) -> str:
|
|
"""OOB response: cart page admin overview."""
|
|
content = _cart_admin_main_panel_sexp(ctx)
|
|
oobs = _cart_page_admin_header_sexp(ctx, page_post, oob=True)
|
|
return oob_page_sexp(oobs=oobs, content=content)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Public API: Cart payments admin
|
|
# ---------------------------------------------------------------------------
|
|
|
|
async def render_cart_payments_page(ctx: dict, page_post: Any) -> str:
|
|
"""Full page: payments config."""
|
|
content = _cart_payments_main_panel_sexp(ctx)
|
|
root_hdr = root_header_sexp(ctx)
|
|
post_hdr = await _post_header_sexp(ctx, page_post)
|
|
admin_hdr = _cart_page_admin_header_sexp(ctx, page_post, selected="payments")
|
|
header_rows = "(<> " + root_hdr + " " + post_hdr + " " + admin_hdr + ")"
|
|
return full_page_sexp(ctx, header_rows=header_rows, content=content)
|
|
|
|
|
|
async def render_cart_payments_oob(ctx: dict, page_post: Any) -> str:
|
|
"""OOB response: payments config."""
|
|
content = _cart_payments_main_panel_sexp(ctx)
|
|
oobs = _cart_page_admin_header_sexp(ctx, page_post, oob=True, selected="payments")
|
|
return oob_page_sexp(oobs=oobs, content=content)
|
|
|
|
|
|
def render_cart_payments_panel(ctx: dict) -> str:
|
|
"""Render the payments config panel for PUT response."""
|
|
return _cart_payments_main_panel_sexp(ctx)
|