""" 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, cart_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 if page_post else None) or "")[:160] label_html = "" if page_post and page_post.feature_image: label_html += sexp( '(img :src fi :class "h-8 w-8 rounded-full object-cover border border-stone-300 flex-shrink-0")', fi=page_post.feature_image, ) label_html += sexp('(span t)', t=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"' ' (i :class "fa fa-arrow-left text-xs" :aria-hidden "true") "All carts")', h=call_url(ctx, "cart_url", "/"), ) 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 _badge_html(icon: str, count: int, label: str) -> str: """Render a count badge.""" s = "s" if count != 1 else "" return sexp( '(span :class "inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-stone-100"' ' (i :class ic :aria-hidden "true") txt)', ic=icon, txt=f"{count} {label}{s}", ) 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: badges += _badge_html("fa fa-box-open", product_count, "item") if calendar_count > 0: badges += _badge_html("fa fa-calendar", calendar_count, "booking") if ticket_count > 0: badges += _badge_html("fa fa-ticket", ticket_count, "ticket") badges_html = sexp( '(div :class "mt-1 flex flex-wrap gap-2 text-xs text-stone-600" (raw! b))', b=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_href = call_url(ctx, "cart_url", f"/{slug}/") if feature_image: img = sexp( '(img :src fi :alt t :class "h-16 w-16 rounded-xl object-cover border border-stone-200 flex-shrink-0")', fi=feature_image, t=title, ) else: img = sexp( '(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"))', ) mp_name = "" mp_sub = "" if market_place: mp_name = market_place.name if hasattr(market_place, "name") else market_place.get("name", "") mp_sub = sexp('(p :class "text-xs text-stone-500 truncate" t)', t=title) display_title = mp_name or title return sexp( '(a :href ch :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"' ' (div :class "flex items-start gap-4"' ' (raw! img)' ' (div :class "flex-1 min-w-0"' ' (h3 :class "text-base sm:text-lg font-semibold text-stone-900 truncate" dt)' ' (raw! ms) (raw! bh))' ' (div :class "text-right flex-shrink-0"' ' (div :class "text-lg font-bold text-stone-900" tt)' ' (div :class "mt-1 text-xs text-emerald-700 font-medium" "View cart \u2192"))))', ch=cart_href, img=img, dt=display_title, ms=mp_sub, bh=badges_html, tt=f"\u00a3{total:.2f}", ) else: # Orphan items — use amber badges badges_amber = badges.replace("bg-stone-100", "bg-amber-100") badges_html_amber = sexp( '(div :class "mt-1 flex flex-wrap gap-2 text-xs text-stone-600" (raw! b))', b=badges_amber, ) return sexp( '(div :class "rounded-2xl border border-dashed border-amber-300 bg-amber-50/60 p-4 sm:p-5"' ' (div :class "flex items-start gap-4"' ' (div :class "h-16 w-16 rounded-xl bg-amber-100 flex items-center justify-center flex-shrink-0"' ' (i :class "fa fa-shopping-cart text-amber-500 text-xl" :aria-hidden "true"))' ' (div :class "flex-1 min-w-0"' ' (h3 :class "text-base sm:text-lg font-semibold text-stone-900" "Other items")' ' (raw! bh))' ' (div :class "text-right flex-shrink-0"' ' (div :class "text-lg font-bold text-stone-900" tt))))', bh=badges_html_amber, tt=f"\u00a3{total:.2f}", ) def _empty_cart_html() -> str: """Empty cart state.""" return sexp( '(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"))' ' (p :class "text-base sm:text-lg font-medium text-stone-800" "Your cart is empty")))', ) def _overview_main_panel_html(page_groups: list, ctx: dict) -> str: """Cart overview main panel.""" if not page_groups: return _empty_cart_html() 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 _empty_cart_html() return sexp( '(div :class "max-w-full px-3 py-3 space-y-3"' ' (div :class "space-y-4" (raw! c)))', c="".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 = sexp( '(img :src im :alt t :class "w-24 h-24 sm:w-32 sm:h-28 object-cover rounded-xl border border-stone-100" :loading "lazy")', im=p.image, t=p.title, ) else: img = sexp( '(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")', ) price_html = "" if unit_price: price_html = sexp( '(p :class "text-sm sm:text-base font-semibold text-stone-900" ps)', ps=f"{symbol}{unit_price:.2f}", ) if p.special_price and p.special_price != p.regular_price: price_html += sexp( '(p :class "text-xs text-stone-400 line-through" ps)', ps=f"{symbol}{p.regular_price:.2f}", ) else: price_html = sexp('(p :class "text-xs text-stone-500" "No price")') deleted_html = "" if getattr(item, "is_deleted", False): deleted_html = sexp( '(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")' ' " This item is no longer available or price has changed")', ) brand_html = "" if getattr(p, "brand", None): brand_html = sexp('(p :class "mt-0.5 text-[0.7rem] sm:text-xs text-stone-500" br)', br=p.brand) line_total_html = "" if unit_price: lt = unit_price * item.quantity line_total_html = sexp( '(p :class "text-sm sm:text-base font-semibold text-stone-900" lt)', lt=f"Line total: {symbol}{lt:.2f}", ) return sexp( '(article :id aid :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"' ' (div :class "w-full sm:w-32 shrink-0 flex justify-center sm:block" (raw! img))' ' (div :class "flex-1 min-w-0"' ' (div :class "flex flex-col sm:flex-row sm:items-start justify-between gap-2 sm:gap-3"' ' (div :class "min-w-0"' ' (h2 :class "text-sm sm:text-base md:text-lg font-semibold text-stone-900"' ' (a :href pu :class "hover:text-emerald-700" pt))' ' (raw! brh) (raw! dh))' ' (div :class "text-left sm:text-right" (raw! ph)))' ' (div :class "mt-3 flex flex-col sm:flex-row sm:items-center justify-between gap-2 sm:gap-4"' ' (div :class "flex items-center gap-2 text-xs sm:text-sm text-stone-700"' ' (span :class "text-[0.65rem] sm:text-xs uppercase tracking-wide text-stone-500" "Quantity")' ' (form :action qu :method "post" :hx-post qu :hx-swap "none"' ' (input :type "hidden" :name "csrf_token" :value csrf)' ' (input :type "hidden" :name "count" :value minus)' ' (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" "-"))' ' (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" qty)' ' (form :action qu :method "post" :hx-post qu :hx-swap "none"' ' (input :type "hidden" :name "csrf_token" :value csrf)' ' (input :type "hidden" :name "count" :value plus)' ' (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" "+")))' ' (div :class "flex items-center justify-between sm:justify-end gap-3" (raw! lth)))))', aid=f"cart-item-{slug}", img=img, pu=prod_url, pt=p.title, brh=brand_html, dh=deleted_html, ph=price_html, qu=qty_url, csrf=csrf, minus=str(item.quantity - 1), qty=str(item.quantity), plus=str(item.quantity + 1), lth=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_str = f" \u2013 {end}" if end else "" items += sexp( '(li :class "flex items-start justify-between text-sm"' ' (div (div :class "font-medium" nm)' ' (div :class "text-xs text-stone-500" ds))' ' (div :class "ml-4 font-medium" cs))', nm=name, ds=f"{start}{end_str}", cs=f"\u00a3{cost:.2f}", ) return sexp( '(div :class "mt-6 border-t border-stone-200 pt-4"' ' (h2 :class "text-base font-semibold mb-2" "Calendar bookings")' ' (ul :class "space-y-2" (raw! items)))', items=items, ) 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") items = "" 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 = sexp('(p :class "mt-0.5 text-[0.7rem] sm:text-xs text-stone-500" tn)', tn=tt_name) if tt_name else "" tt_hidden = sexp('(input :type "hidden" :name "ticket_type_id" :value tid)', tid=str(tt_id)) if tt_id else "" items += sexp( '(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"' ' (div :class "flex-1 min-w-0"' ' (div :class "flex flex-col sm:flex-row sm:items-start justify-between gap-2 sm:gap-3"' ' (div :class "min-w-0"' ' (h3 :class "text-sm sm:text-base font-semibold text-stone-900" nm)' ' (raw! tnh)' ' (p :class "mt-0.5 text-[0.7rem] sm:text-xs text-stone-500" ds))' ' (div :class "text-left sm:text-right"' ' (p :class "text-sm sm:text-base font-semibold text-stone-900" ps)))' ' (div :class "mt-3 flex flex-col sm:flex-row sm:items-center justify-between gap-2 sm:gap-4"' ' (div :class "flex items-center gap-2 text-xs sm:text-sm text-stone-700"' ' (span :class "text-[0.65rem] sm:text-xs uppercase tracking-wide text-stone-500" "Quantity")' ' (form :action qu :method "post" :hx-post qu :hx-swap "none"' ' (input :type "hidden" :name "csrf_token" :value csrf)' ' (input :type "hidden" :name "entry_id" :value eid)' ' (raw! tth)' ' (input :type "hidden" :name "count" :value minus)' ' (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" "-"))' ' (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" qty)' ' (form :action qu :method "post" :hx-post qu :hx-swap "none"' ' (input :type "hidden" :name "csrf_token" :value csrf)' ' (input :type "hidden" :name "entry_id" :value eid)' ' (raw! tth)' ' (input :type "hidden" :name "count" :value plus)' ' (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" "+")))' ' (div :class "flex items-center justify-between sm:justify-end gap-3"' ' (p :class "text-sm sm:text-base font-semibold text-stone-900" lt)))))', nm=name, tnh=tt_name_html, ds=date_str, ps=f"\u00a3{price or 0:.2f}", qu=qty_url, csrf=csrf, eid=str(entry_id), tth=tt_hidden, minus=str(max(quantity - 1, 0)), qty=str(quantity), plus=str(quantity + 1), lt=f"Line total: \u00a3{line_total:.2f}", ) return sexp( '(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") " Event tickets")' ' (div :class "space-y-3" (raw! items)))', items=items, ) 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 = sexp( '(form :method "post" :action act :class "w-full"' ' (input :type "hidden" :name "csrf_token" :value csrf)' ' (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"' ' (i :class "fa-solid fa-credit-card mr-2" :aria-hidden "true") lbl))', act=action, csrf=csrf, lbl=f" Checkout as {user.email}", ) else: href = login_url(request.url) checkout_html = sexp( '(div :class "w-full flex"' ' (a :href h :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"' ' (i :class "fa-solid fa-key") (span "sign in or register to checkout")))', h=href, ) return sexp( '(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"' ' (h2 :class "text-sm sm:text-base font-semibold text-stone-900 mb-3 sm:mb-4" "Order summary")' ' (dl :class "space-y-2 text-xs sm:text-sm"' ' (div :class "flex items-center justify-between"' ' (dt :class "text-stone-600" "Items") (dd :class "text-stone-900" ic))' ' (div :class "flex items-center justify-between"' ' (dt :class "text-stone-600" "Subtotal") (dd :class "text-stone-900" st)))' ' (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")' ' (div "use dummy card number: 5555 5555 5555 4444"))' ' (div :class "mt-4 sm:mt-5" (raw! ch))))', ic=str(item_count), st=f"{symbol}{grand:.2f}", ch=checkout_html, ) 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 sexp( '(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"))' ' (p :class "text-base sm:text-lg font-medium text-stone-800" "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 sexp( '(div :class "max-w-full px-3 py-3 space-y-3"' ' (div :id "cart"' ' (div (section :class "space-y-3 sm:space-y-4" (raw! ih) (raw! ch) (raw! th))' ' (raw! sh))))', ih=items_html, ch=cal_html, th=tickets_html, sh=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}" desktop = sexp( '(tr :class "hidden sm:table-row border-t border-stone-100 hover:bg-stone-50/60"' ' (td :class "px-3 py-2 align-top" (span :class "font-mono text-[11px] sm:text-xs" oid))' ' (td :class "px-3 py-2 align-top text-stone-700 text-xs sm:text-sm" cr)' ' (td :class "px-3 py-2 align-top text-stone-700 text-xs sm:text-sm" desc)' ' (td :class "px-3 py-2 align-top text-stone-700 text-xs sm:text-sm" tot)' ' (td :class "px-3 py-2 align-top" (span :class (str "inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] sm:text-xs " pill) st))' ' (td :class "px-3 py-0.5 align-top text-right"' ' (a :href du :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")))', oid=f"#{order.id}", cr=created, desc=order.description or "", tot=total, pill=pill, st=status, du=detail_url, ) mobile = sexp( '(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"' ' (div :class "flex items-center justify-between gap-2"' ' (span :class "font-mono text-[11px] text-stone-700" oid)' ' (span :class (str "inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] " pill) st))' ' (div :class "text-[11px] text-stone-500 break-words" cr)' ' (div :class "flex items-center justify-between gap-2"' ' (div :class "font-medium text-stone-800" tot)' ' (a :href du :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")))))', oid=f"#{order.id}", pill=pill, st=status, cr=created, tot=total, du=detail_url, ) return desktop + mobile 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(sexp( '(tr (td :colspan "5" :class "px-3 py-4 text-center text-xs text-stone-400" "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 sexp( '(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."))', ) return sexp( '(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 :class "px-3 py-2 text-left font-medium" "Created")' ' (th :class "px-3 py-2 text-left font-medium" "Description")' ' (th :class "px-3 py-2 text-left font-medium" "Total")' ' (th :class "px-3 py-2 text-left font-medium" "Status")' ' (th :class "px-3 py-2 text-left font-medium")))' ' (tbody (raw! rh)))))', rh=rows_html, ) def _orders_summary_html(ctx: dict) -> str: """Filter section for orders list.""" return sexp( '(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."))' ' (div :class "md:hidden" (raw! sm)))', sm=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) if item.product_image: img = sexp( '(img :src pi :alt pt :class "w-full h-full object-contain object-center" :loading "lazy" :decoding "async")', pi=item.product_image, pt=item.product_title or "Product image", ) else: img = sexp( '(div :class "w-full h-full flex items-center justify-center text-[9px] text-stone-400" "No image")', ) items += sexp( '(li (a :class "w-full py-2 flex gap-3" :href pu' ' (div :class "w-12 h-12 sm:w-14 sm:h-14 rounded-md bg-stone-100 flex-shrink-0 overflow-hidden" (raw! img))' ' (div :class "flex-1 flex justify-between gap-3"' ' (div (p :class "font-medium" pt)' ' (p :class "text-[11px] text-stone-500" pid))' ' (div :class "text-right whitespace-nowrap"' ' (p qty) (p pr)))))', pu=prod_url, img=img, pt=item.product_title or "Unknown product", pid=f"Product ID: {item.product_id}", qty=f"Qty: {item.quantity}", pr=f"{item.currency or order.currency or 'GBP'} {item.unit_price or 0:.2f}", ) return sexp( '(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")' ' (ul :class "divide-y divide-stone-100 text-xs sm:text-sm" (raw! items)))', items=items, ) 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 += sexp( '(li :class "px-4 py-3 flex items-start justify-between text-sm"' ' (div (div :class "font-medium flex items-center gap-2"' ' nm (span :class (str "inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium " pill) sc))' ' (div :class "text-xs text-stone-500" ds))' ' (div :class "ml-4 font-medium" cs))', nm=e.name, pill=pill, sc=st.capitalize(), ds=ds, cs=f"\u00a3{e.cost or 0:.2f}", ) return sexp( '(section :class "mt-6 space-y-3"' ' (h2 :class "text-base sm:text-lg font-semibold" "Calendar bookings in this order")' ' (ul :class "divide-y divide-stone-200 rounded-2xl border border-stone-200 bg-white/80" (raw! items)))', items=items, ) def _order_main_html(order: Any, calendar_entries: list | None) -> str: """Main panel for single order detail.""" summary = _order_summary_html(order) return sexp( '(div :class "max-w-full px-3 py-3 space-y-4" (raw! s) (raw! oi) (raw! ci))', s=summary, oi=_order_items_html(order), ci=_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 = "" if status != "paid": pay = sexp( '(a :href pu :class "inline-flex items-center px-3 py-2 text-xs sm:text-sm rounded-full border border-emerald-600 bg-emerald-600 text-white hover:bg-emerald-700 transition"' ' (i :class "fa fa-credit-card mr-2" :aria-hidden "true") "Open payment page")', pu=pay_url, ) return sexp( '(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" info))' ' (div :class "flex w-full sm:w-auto justify-start sm:justify-end gap-2"' ' (a :href lu :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") "All orders")' ' (form :method "post" :action ru :class "inline"' ' (input :type "hidden" :name "csrf_token" :value csrf)' ' (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") "Re-check status"))' ' (raw! pay)))', info=f"Placed {created} \u00b7 Status: {status}", lu=list_url, ru=recheck_url, csrf=csrf_token, pay=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) # --------------------------------------------------------------------------- # Public API: Checkout error # --------------------------------------------------------------------------- def _checkout_error_filter_html() -> str: return sexp( '(header :class "mb-6 sm:mb-8"' ' (h1 :class "text-xl sm:text-2xl md:text-3xl font-semibold tracking-tight" "Checkout error")' ' (p :class "text-xs sm:text-sm text-stone-600"' ' "We tried to start your payment with SumUp but hit a problem."))', ) def _checkout_error_content_html(error: str | None, order: Any | None) -> str: err_msg = error or "Unexpected error while creating the hosted checkout session." order_html = "" if order: order_html = sexp( '(p :class "text-xs text-rose-800/80"' ' "Order ID: " (span :class "font-mono" oid))', oid=f"#{order.id}", ) back_url = cart_url("/") return sexp( '(div :class "max-w-full px-3 py-3 space-y-4"' ' (div :class "rounded-2xl border border-rose-200 bg-rose-50/80 p-4 sm:p-6 text-sm text-rose-900 space-y-2"' ' (p :class "font-medium" "Something went wrong.")' ' (p em)' ' (raw! oh))' ' (div (a :href bu :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 fa-shopping-cart mr-2" :aria-hidden "true") "Back to cart")))', em=err_msg, oh=order_html, bu=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_html(ctx) hdr += sexp( '(div :id "root-header-child" :class "flex flex-col w-full items-center" (raw! c))', c=_cart_header_html(ctx), ) filt = _checkout_error_filter_html() content = _checkout_error_content_html(error, order) return full_page(ctx, header_rows_html=hdr, filter_html=filt, content_html=content)