""" 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'' ) label_html = f'{img_html}{title}' 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='', ) 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'' f' {product_count} item{s}' ) if calendar_count > 0: s = "s" if calendar_count != 1 else "" badges.append( f'' f' {calendar_count} booking{s}' ) if ticket_count > 0: s = "s" if ticket_count != 1 else "" badges.append( f'' f' {ticket_count} ticket{s}' ) badges_html = '
' + "".join(badges) + '
' 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'{title}' else: img = '
' 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'

{title}

' display_title = mp_name or title return ( f'' f'
{img}' f'

{display_title}

{mp_sub}{badges_html}
' f'
£{total:.2f}
' f'
View cart →
' ) else: # Orphan items badges_html_amber = badges_html.replace("bg-stone-100", "bg-amber-100") return ( f'
' f'
' f'
' f'
' f'

Other items

{badges_html_amber}
' f'
£{total:.2f}
' ) def _overview_main_panel_html(page_groups: list, ctx: dict) -> str: """Cart overview main panel.""" if not page_groups: return ( '
' '
' '
' '
' '

Your cart is empty

' ) 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 ( '
' '
' '
' '
' '

Your cart is empty

' ) return '
' + "".join(cards) + '
' # --------------------------------------------------------------------------- # 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'{p.title}' else: img = '
No image
' price_html = "" if unit_price: price_html = f'

{symbol}{unit_price:.2f}

' if p.special_price and p.special_price != p.regular_price: price_html += f'

{symbol}{p.regular_price:.2f}

' else: price_html = '

No price

' deleted_html = "" if getattr(item, "is_deleted", False): deleted_html = ( '

' '' ' This item is no longer available or price has changed

' ) brand_html = f'

{p.brand}

' if getattr(p, "brand", None) else "" line_total_html = "" if unit_price: lt = unit_price * item.quantity line_total_html = f'

Line total: {symbol}{lt:.2f}

' return ( f'
' f'
{img}
' f'
' f'
' f'

' f'{p.title}

{brand_html}{deleted_html}
' f'
{price_html}
' f'
' f'
' f'Quantity' f'
' f'' f'
' f'{item.quantity}' f'
' f'' f'
' f'
{line_total_html}
' ) 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'
  • ' f'
    {name}
    ' f'
    {start}{end_html}
    ' f'
    \u00a3{cost:.2f}
  • ' ) return ( '
    ' '

    Calendar bookings

    ' f'
    ' ) 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 = ['
    ', '

    Event tickets

    ', '
    '] 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'

    {tt_name}

    ' if tt_name else "" tt_hidden = f'' if tt_id else "" parts.append( f'
    ' f'
    ' f'
    ' f'

    {name}

    {tt_name_html}' f'

    {date_str}

    ' f'

    \u00a3{price or 0:.2f}

    ' f'
    ' f'
    ' f'Quantity' f'
    ' f'{tt_hidden}' f'' f'
    ' f'{quantity}' f'
    ' f'{tt_hidden}' f'' f'
    ' f'
    ' f'

    Line total: \u00a3{line_total:.2f}

    ' ) parts.append('
    ') 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'
    ' f'' f'
    ' ) else: href = login_url(request.url) checkout_html = ( f'
    ' f'sign in or register to checkout
    ' ) return ( f'' ) 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 ( '
    ' '
    ' '
    ' '
    ' '

    Your cart is empty

    ' ) 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'
    ' f'
    {items_html}{cal_html}{tickets_html}
    ' f'{summary_html}
    ' ) # --------------------------------------------------------------------------- # 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'' f'#{order.id}' f'{created}' f'{order.description or ""}' f'{total}' f'{status}' f'View' f'
    ' f'
    #{order.id}' f'{status}
    ' f'
    {created}
    ' f'
    {total}
    ' f'View
    ' ) 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('End of results') return "".join(parts) def _orders_main_panel_html(orders: list, rows_html: str) -> str: """Main panel for orders list.""" if not orders: return ( '
    ' '
    ' 'No orders yet.
    ' ) return ( '
    ' '
    ' '' '' '' '' '' '' '' '' f'{rows_html}
    OrderCreatedDescriptionTotalStatus
    ' ) def _orders_summary_html(ctx: dict) -> str: """Filter section for orders list.""" return ( '
    ' '

    Recent orders placed via the checkout.

    ' f'
    {search_mobile_html(ctx)}
    ' '
    ' ) # --------------------------------------------------------------------------- # 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'{item.product_title or ' if item.product_image else '
    No image
    ' ) items.append( f'
  • ' f'
    {img}
    ' f'
    ' f'

    {item.product_title or "Unknown product"}

    ' f'

    Product ID: {item.product_id}

    ' f'

    Qty: {item.quantity}

    ' f'

    {item.currency or order.currency or "GBP"} {item.unit_price or 0:.2f}

    ' f'
  • ' ) return ( '
    ' '

    Items

    ' f'
    ' ) 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'
  • ' f'
    {e.name}' f'' f'{st.capitalize()}
    ' f'
    {ds}
    ' f'
    \u00a3{e.cost or 0:.2f}
  • ' ) return ( '
    ' '

    Calendar bookings in this order

    ' f'
    ' ) def _order_main_html(order: Any, calendar_entries: list | None) -> str: """Main panel for single order detail.""" summary = _order_summary_html(order) return f'
    {summary}{_order_items_html(order)}{_order_calendar_items_html(calendar_entries)}
    ' 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'' f'Open payment page' ) if status != "paid" else "" return ( '
    ' f'

    Placed {created} · Status: {status}

    ' '
    ' f'All orders' f'
    ' f'
    ' f'{pay}
    ' ) # --------------------------------------------------------------------------- # 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)