Move SX construction from Python to .sx defcomps (phases 0-4)
Eliminate Python s-expression string building across account, orders, federation, and cart services. Visual rendering logic now lives entirely in .sx defcomp components; Python files contain only data serialization, header/layout wiring, and thin wrappers that call defcomps. Phase 0: Shared DRY extraction — auth/orders header defcomps, format-decimal/ pluralize/escape/route-prefix primitives. Phase 1: Account — dashboard, newsletters, login/device/check-email content. Phase 2: Orders — order list, detail, filter, checkout return assembled defcomps. Phase 3: Federation — social nav, post cards, timeline, search, actors, notifications, compose, profile assembled defcomps. Phase 4: Cart — overview, page cart items/calendar/tickets/summary, admin, payments assembled defcomps; orders rendering reuses Phase 2 shared defcomps. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
111
cart/sx/items.sx
111
cart/sx/items.sx
@@ -52,3 +52,114 @@
|
||||
(div :id "cart"
|
||||
(div (section :class "space-y-3 sm:space-y-4" items cal tickets)
|
||||
summary))))
|
||||
|
||||
;; Assembled cart item from serialized data — replaces Python _cart_item_sx
|
||||
(defcomp ~cart-item-from-data (&key item)
|
||||
(let* ((slug (or (get item "slug") ""))
|
||||
(title (or (get item "title") ""))
|
||||
(image (get item "image"))
|
||||
(brand (get item "brand"))
|
||||
(is-deleted (get item "is_deleted"))
|
||||
(unit-price (get item "unit_price"))
|
||||
(special-price (get item "special_price"))
|
||||
(regular-price (get item "regular_price"))
|
||||
(currency (or (get item "currency") "GBP"))
|
||||
(symbol (if (= currency "GBP") "\u00a3" currency))
|
||||
(quantity (or (get item "quantity") 1))
|
||||
(product-id (get item "product_id"))
|
||||
(prod-url (or (get item "product_url") ""))
|
||||
(qty-url (or (get item "qty_url") ""))
|
||||
(csrf (csrf-token))
|
||||
(line-total (when unit-price (* unit-price quantity))))
|
||||
(~cart-item
|
||||
:id (str "cart-item-" slug)
|
||||
:img (if image
|
||||
(~cart-item-img :src image :alt title)
|
||||
(~img-or-placeholder :src nil
|
||||
:size-cls "w-24 h-24 sm:w-32 sm:h-28 rounded-xl border border-dashed border-stone-300"
|
||||
:placeholder-text "No image"))
|
||||
:prod-url prod-url
|
||||
:title title
|
||||
:brand (when brand (~cart-item-brand :brand brand))
|
||||
:deleted (when is-deleted (~cart-item-deleted))
|
||||
:price (if unit-price
|
||||
(<>
|
||||
(~cart-item-price :text (str symbol (format-decimal unit-price 2)))
|
||||
(when (and special-price (!= special-price regular-price))
|
||||
(~cart-item-price-was :text (str symbol (format-decimal regular-price 2)))))
|
||||
(~cart-item-no-price))
|
||||
:qty-url qty-url :csrf csrf
|
||||
:minus (str (- quantity 1))
|
||||
:qty (str quantity)
|
||||
:plus (str (+ quantity 1))
|
||||
:line-total (when line-total
|
||||
(~cart-item-line-total :text (str "Line total: " symbol (format-decimal line-total 2)))))))
|
||||
|
||||
;; Assembled calendar entries section — replaces Python _calendar_entries_sx
|
||||
(defcomp ~cart-cal-section-from-data (&key entries)
|
||||
(when (not (empty? entries))
|
||||
(~cart-cal-section
|
||||
:items (map (lambda (e)
|
||||
(let* ((name (or (get e "name") ""))
|
||||
(date-str (or (get e "date_str") "")))
|
||||
(~cart-cal-entry
|
||||
:name name :date-str date-str
|
||||
:cost (str "\u00a3" (format-decimal (or (get e "cost") 0) 2)))))
|
||||
entries))))
|
||||
|
||||
;; Assembled ticket groups section — replaces Python _ticket_groups_sx
|
||||
(defcomp ~cart-tickets-section-from-data (&key ticket-groups)
|
||||
(when (not (empty? ticket-groups))
|
||||
(let* ((csrf (csrf-token))
|
||||
(qty-url (url-for "cart_global.update_ticket_quantity")))
|
||||
(~cart-tickets-section
|
||||
:items (map (lambda (tg)
|
||||
(let* ((name (or (get tg "entry_name") ""))
|
||||
(tt-name (get tg "ticket_type_name"))
|
||||
(price (or (get tg "price") 0))
|
||||
(quantity (or (get tg "quantity") 0))
|
||||
(line-total (or (get tg "line_total") 0))
|
||||
(entry-id (str (or (get tg "entry_id") "")))
|
||||
(tt-id (get tg "ticket_type_id"))
|
||||
(date-str (or (get tg "date_str") "")))
|
||||
(~cart-ticket-article
|
||||
:name name
|
||||
:type-name (when tt-name (~cart-ticket-type-name :name tt-name))
|
||||
:date-str date-str
|
||||
:price (str "\u00a3" (format-decimal price 2))
|
||||
:qty-url qty-url :csrf csrf
|
||||
:entry-id entry-id
|
||||
:type-hidden (when tt-id (~cart-ticket-type-hidden :value (str tt-id)))
|
||||
:minus (str (max (- quantity 1) 0))
|
||||
:qty (str quantity)
|
||||
:plus (str (+ quantity 1))
|
||||
:line-total (str "Line total: \u00a3" (format-decimal line-total 2)))))
|
||||
ticket-groups)))))
|
||||
|
||||
;; Assembled cart summary — replaces Python _cart_summary_sx
|
||||
(defcomp ~cart-summary-from-data (&key item-count grand-total symbol is-logged-in checkout-action login-href user-email)
|
||||
(~cart-summary-panel
|
||||
:item-count (str item-count)
|
||||
:subtotal (str symbol (format-decimal grand-total 2))
|
||||
:checkout (if is-logged-in
|
||||
(~cart-checkout-form
|
||||
:action checkout-action :csrf (csrf-token)
|
||||
:label (str " Checkout as " user-email))
|
||||
(~cart-checkout-signin :href login-href))))
|
||||
|
||||
;; Assembled page cart content — replaces Python _page_cart_main_panel_sx
|
||||
(defcomp ~cart-page-cart-content (&key cart-items cal-entries ticket-groups summary)
|
||||
(if (and (empty? (or cart-items (list)))
|
||||
(empty? (or cal-entries (list)))
|
||||
(empty? (or ticket-groups (list))))
|
||||
(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"
|
||||
(~empty-state :icon "fa fa-shopping-cart" :message "Your cart is empty" :cls "text-center"))))
|
||||
(~cart-page-panel
|
||||
:items (map (lambda (item) (~cart-item-from-data :item item)) (or cart-items (list)))
|
||||
:cal (when (not (empty? (or cal-entries (list))))
|
||||
(~cart-cal-section-from-data :entries cal-entries))
|
||||
:tickets (when (not (empty? (or ticket-groups (list))))
|
||||
(~cart-tickets-section-from-data :ticket-groups ticket-groups))
|
||||
:summary summary)))
|
||||
|
||||
@@ -39,3 +39,56 @@
|
||||
(defcomp ~cart-overview-panel (&key cards)
|
||||
(div :class "max-w-full px-3 py-3 space-y-3"
|
||||
(div :class "space-y-4" cards)))
|
||||
|
||||
(defcomp ~cart-empty ()
|
||||
(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"
|
||||
(~empty-state :icon "fa fa-shopping-cart" :message "Your cart is empty" :cls "text-center"))))
|
||||
|
||||
;; Assembled page group card — replaces Python _page_group_card_sx
|
||||
(defcomp ~cart-page-group-card-from-data (&key grp cart-url-base)
|
||||
(let* ((post (get grp "post"))
|
||||
(product-count (or (get grp "product_count") 0))
|
||||
(calendar-count (or (get grp "calendar_count") 0))
|
||||
(ticket-count (or (get grp "ticket_count") 0))
|
||||
(total (or (get grp "total") 0))
|
||||
(market-place (get grp "market_place"))
|
||||
(badges (<>
|
||||
(when (> product-count 0)
|
||||
(~cart-badge :icon "fa fa-box-open"
|
||||
:text (str product-count " item" (pluralize product-count))))
|
||||
(when (> calendar-count 0)
|
||||
(~cart-badge :icon "fa fa-calendar"
|
||||
:text (str calendar-count " booking" (pluralize calendar-count))))
|
||||
(when (> ticket-count 0)
|
||||
(~cart-badge :icon "fa fa-ticket"
|
||||
:text (str ticket-count " ticket" (pluralize ticket-count)))))))
|
||||
(if post
|
||||
(let* ((slug (or (get post "slug") ""))
|
||||
(title (or (get post "title") ""))
|
||||
(feature-image (get post "feature_image"))
|
||||
(mp-name (if market-place (or (get market-place "name") "") ""))
|
||||
(display-title (if (!= mp-name "") mp-name title)))
|
||||
(~cart-group-card
|
||||
:href (str cart-url-base "/" slug "/")
|
||||
:img (if feature-image
|
||||
(~cart-group-card-img :src feature-image :alt title)
|
||||
(~img-or-placeholder :src nil :size-cls "h-16 w-16 rounded-xl"
|
||||
:placeholder-icon "fa fa-store text-xl"))
|
||||
:display-title display-title
|
||||
:subtitle (when (!= mp-name "")
|
||||
(~cart-mp-subtitle :title title))
|
||||
:badges (~cart-badges-wrap :badges badges)
|
||||
:total (str "\u00a3" (format-decimal total 2))))
|
||||
(~cart-orphan-card
|
||||
:badges (~cart-badges-wrap :badges badges)
|
||||
:total (str "\u00a3" (format-decimal total 2))))))
|
||||
|
||||
;; Assembled cart overview content — replaces Python _overview_main_panel_sx
|
||||
(defcomp ~cart-overview-content (&key page-groups cart-url-base)
|
||||
(if (empty? page-groups)
|
||||
(~cart-empty)
|
||||
(~cart-overview-panel
|
||||
:cards (map (lambda (grp)
|
||||
(~cart-page-group-card-from-data :grp grp :cart-url-base cart-url-base))
|
||||
page-groups))))
|
||||
|
||||
@@ -5,3 +5,27 @@
|
||||
(~sumup-settings-form :update-url update-url :csrf csrf :merchant-code merchant-code
|
||||
:placeholder placeholder :input-cls input-cls :sumup-configured sumup-configured
|
||||
:checkout-prefix checkout-prefix :sx-select "#payments-panel")))
|
||||
|
||||
;; Assembled cart admin overview content
|
||||
(defcomp ~cart-admin-content ()
|
||||
(let* ((payments-href (url-for "defpage_cart_payments")))
|
||||
(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")
|
||||
(a :href payments-href :class "text-sm underline" "configure")))))
|
||||
|
||||
;; Assembled cart payments content
|
||||
(defcomp ~cart-payments-content (&key page-config)
|
||||
(let* ((sumup-configured (and page-config (get page-config "sumup_api_key")))
|
||||
(merchant-code (or (get page-config "sumup_merchant_code") ""))
|
||||
(checkout-prefix (or (get page-config "sumup_checkout_prefix") ""))
|
||||
(placeholder (if sumup-configured "--------" "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"))
|
||||
(~cart-payments-panel
|
||||
:update-url (url-for "page_admin.update_sumup")
|
||||
:csrf (csrf-token)
|
||||
:merchant-code merchant-code
|
||||
:placeholder placeholder
|
||||
:input-cls input-cls
|
||||
:sumup-configured sumup-configured
|
||||
:checkout-prefix checkout-prefix)))
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
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()``.
|
||||
Thin Python wrappers for header/layout helpers and route-level render
|
||||
functions. All visual rendering logic lives in .sx defcomps.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -18,7 +18,8 @@ from shared.sx.helpers import (
|
||||
full_page_sx, oob_page_sx, header_child_sx,
|
||||
sx_call, SxExpr,
|
||||
)
|
||||
from shared.infrastructure.urls import market_product_url, cart_url
|
||||
from shared.sx.parser import serialize
|
||||
from shared.infrastructure.urls import cart_url
|
||||
|
||||
# Load cart-specific .sx components + handlers at import time
|
||||
load_service_components(os.path.dirname(os.path.dirname(__file__)),
|
||||
@@ -26,7 +27,7 @@ load_service_components(os.path.dirname(os.path.dirname(__file__)),
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Header helpers
|
||||
# Header helpers (used by layouts in sxc/pages/__init__.py)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _ensure_post_ctx(ctx: dict, page_post: Any) -> dict:
|
||||
@@ -104,493 +105,74 @@ def _page_cart_header_sx(ctx: dict, page_post: Any, *, oob: bool = False) -> str
|
||||
def _auth_header_sx(ctx: dict, *, oob: bool = False) -> str:
|
||||
"""Build the account section header row (for orders)."""
|
||||
return sx_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,
|
||||
"auth-header-row-simple",
|
||||
account_url=call_url(ctx, "account_url", ""),
|
||||
oob=oob,
|
||||
)
|
||||
|
||||
|
||||
def _orders_header_sx(ctx: dict, list_url: str) -> str:
|
||||
"""Build the orders section header row."""
|
||||
return sx_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",
|
||||
)
|
||||
return sx_call("orders-header-row", list_url=list_url)
|
||||
|
||||
|
||||
def _cart_page_admin_header_sx(ctx: dict, page_post: Any, *, oob: bool = False,
|
||||
selected: str = "") -> str:
|
||||
"""Build the page-level admin header row."""
|
||||
slug = page_post.slug if page_post else ""
|
||||
ctx = _ensure_post_ctx(ctx, page_post)
|
||||
return post_admin_header_sx(ctx, slug, oob=oob, selected=selected)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cart overview
|
||||
# Serialization helpers (shared with sxc/pages/__init__.py)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _badge_sx(icon: str, count: int, label: str) -> str:
|
||||
"""Render a count badge."""
|
||||
s = "s" if count != 1 else ""
|
||||
return sx_call("cart-badge", icon=icon, text=f"{count} {label}{s}")
|
||||
|
||||
|
||||
def _page_group_card_sx(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_sx("fa fa-box-open", product_count, "item"))
|
||||
if calendar_count > 0:
|
||||
badge_parts.append(_badge_sx("fa fa-calendar", calendar_count, "booking"))
|
||||
if ticket_count > 0:
|
||||
badge_parts.append(_badge_sx("fa fa-ticket", ticket_count, "ticket"))
|
||||
badges_sx = "(<> " + " ".join(badge_parts) + ")" if badge_parts else '""'
|
||||
badges_wrap = sx_call("cart-badges-wrap", badges=SxExpr(badges_sx))
|
||||
|
||||
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 = sx_call("cart-group-card-img", src=feature_image, alt=title)
|
||||
else:
|
||||
img = sx_call("img-or-placeholder", src=None,
|
||||
size_cls="h-16 w-16 rounded-xl",
|
||||
placeholder_icon="fa fa-store text-xl")
|
||||
|
||||
mp_sub = ""
|
||||
if market_place:
|
||||
mp_name = market_place.name if hasattr(market_place, "name") else market_place.get("name", "")
|
||||
mp_sub = sx_call("cart-mp-subtitle", title=title)
|
||||
else:
|
||||
mp_name = ""
|
||||
display_title = mp_name or title
|
||||
|
||||
return sx_call(
|
||||
"cart-group-card",
|
||||
href=cart_href, img=SxExpr(img), display_title=display_title,
|
||||
subtitle=SxExpr(mp_sub) if mp_sub else None,
|
||||
badges=SxExpr(badges_wrap),
|
||||
total=f"\u00a3{total:.2f}",
|
||||
)
|
||||
else:
|
||||
# Orphan items
|
||||
return sx_call(
|
||||
"cart-orphan-card",
|
||||
badges=SxExpr(badges_wrap),
|
||||
total=f"\u00a3{total:.2f}",
|
||||
)
|
||||
|
||||
|
||||
def _empty_cart_sx() -> str:
|
||||
"""Empty cart state."""
|
||||
empty = sx_call("empty-state", icon="fa fa-shopping-cart",
|
||||
message="Your cart is empty", cls="text-center")
|
||||
return (
|
||||
'(div :class "max-w-full px-3 py-3 space-y-3"'
|
||||
' (div :class "rounded-2xl border border-dashed border-stone-300 bg-white/80 p-6 sm:p-8 text-center"'
|
||||
f' {empty}))'
|
||||
)
|
||||
|
||||
|
||||
def _overview_main_panel_sx(page_groups: list, ctx: dict) -> str:
|
||||
"""Cart overview main panel."""
|
||||
if not page_groups:
|
||||
return _empty_cart_sx()
|
||||
|
||||
cards = [_page_group_card_sx(grp, ctx) for grp in page_groups]
|
||||
has_items = any(c for c in cards)
|
||||
if not has_items:
|
||||
return _empty_cart_sx()
|
||||
|
||||
cards_sx = "(<> " + " ".join(c for c in cards if c) + ")"
|
||||
return sx_call("cart-overview-panel", cards=SxExpr(cards_sx))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Page cart
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _cart_item_sx(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 = sx_call("cart-item-img", src=p.image, alt=p.title)
|
||||
else:
|
||||
img = sx_call("img-or-placeholder", src=None,
|
||||
size_cls="w-24 h-24 sm:w-32 sm:h-28 rounded-xl border border-dashed border-stone-300",
|
||||
placeholder_text="No image")
|
||||
|
||||
price_parts = []
|
||||
if unit_price:
|
||||
price_parts.append(sx_call("cart-item-price", text=f"{symbol}{unit_price:.2f}"))
|
||||
if p.special_price and p.special_price != p.regular_price:
|
||||
price_parts.append(sx_call("cart-item-price-was", text=f"{symbol}{p.regular_price:.2f}"))
|
||||
else:
|
||||
price_parts.append(sx_call("cart-item-no-price"))
|
||||
price_sx = "(<> " + " ".join(price_parts) + ")" if len(price_parts) > 1 else price_parts[0]
|
||||
|
||||
deleted_sx = sx_call("cart-item-deleted") if getattr(item, "is_deleted", False) else None
|
||||
|
||||
brand_sx = sx_call("cart-item-brand", brand=p.brand) if getattr(p, "brand", None) else None
|
||||
|
||||
line_total_sx = None
|
||||
if unit_price:
|
||||
lt = unit_price * item.quantity
|
||||
line_total_sx = sx_call("cart-item-line-total", text=f"Line total: {symbol}{lt:.2f}")
|
||||
|
||||
return sx_call(
|
||||
"cart-item",
|
||||
id=f"cart-item-{slug}", img=SxExpr(img), prod_url=prod_url, title=p.title,
|
||||
brand=SxExpr(brand_sx) if brand_sx else None,
|
||||
deleted=SxExpr(deleted_sx) if deleted_sx else None,
|
||||
price=SxExpr(price_sx),
|
||||
qty_url=qty_url, csrf=csrf, minus=str(item.quantity - 1),
|
||||
qty=str(item.quantity), plus=str(item.quantity + 1),
|
||||
line_total=SxExpr(line_total_sx) if line_total_sx else None,
|
||||
)
|
||||
|
||||
|
||||
def _calendar_entries_sx(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(sx_call(
|
||||
"cart-cal-entry",
|
||||
name=name, date_str=f"{start}{end_str}", cost=f"\u00a3{cost:.2f}",
|
||||
))
|
||||
items_sx = "(<> " + " ".join(parts) + ")"
|
||||
return sx_call("cart-cal-section", items=SxExpr(items_sx))
|
||||
|
||||
|
||||
def _ticket_groups_sx(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_sx = sx_call("cart-ticket-type-name", name=tt_name) if tt_name else None
|
||||
tt_hidden_sx = sx_call("cart-ticket-type-hidden", value=str(tt_id)) if tt_id else None
|
||||
|
||||
parts.append(sx_call(
|
||||
"cart-ticket-article",
|
||||
name=name,
|
||||
type_name=SxExpr(tt_name_sx) if tt_name_sx 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=SxExpr(tt_hidden_sx) if tt_hidden_sx 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_sx = "(<> " + " ".join(parts) + ")"
|
||||
return sx_call("cart-tickets-section", items=SxExpr(items_sx))
|
||||
|
||||
|
||||
def _cart_summary_sx(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_sx = sx_call(
|
||||
"cart-checkout-form",
|
||||
action=action, csrf=csrf, label=f" Checkout as {user.email}",
|
||||
)
|
||||
else:
|
||||
href = login_url(request.url)
|
||||
checkout_sx = sx_call("cart-checkout-signin", href=href)
|
||||
|
||||
return sx_call(
|
||||
"cart-summary-panel",
|
||||
item_count=str(item_count), subtotal=f"{symbol}{grand:.2f}",
|
||||
checkout=SxExpr(checkout_sx),
|
||||
)
|
||||
|
||||
|
||||
def _page_cart_main_panel_sx(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:
|
||||
empty = sx_call("empty-state", icon="fa fa-shopping-cart",
|
||||
message="Your cart is empty", cls="text-center")
|
||||
return (
|
||||
'(div :class "max-w-full px-3 py-3 space-y-3"'
|
||||
' (div :id "cart"'
|
||||
' (div :class "rounded-2xl border border-dashed border-stone-300 bg-white/80 p-6 sm:p-8 text-center"'
|
||||
f' {empty})))'
|
||||
)
|
||||
|
||||
item_parts = [_cart_item_sx(item, ctx) for item in cart]
|
||||
items_sx = "(<> " + " ".join(item_parts) + ")" if item_parts else '""'
|
||||
cal_sx = _calendar_entries_sx(cal_entries)
|
||||
tickets_sx = _ticket_groups_sx(ticket_groups, ctx)
|
||||
summary_sx = _cart_summary_sx(ctx, cart, cal_entries, tickets, total_fn, cal_total_fn, ticket_total_fn)
|
||||
|
||||
return sx_call(
|
||||
"cart-page-panel",
|
||||
items=SxExpr(items_sx),
|
||||
cal=SxExpr(cal_sx) if cal_sx else None,
|
||||
tickets=SxExpr(tickets_sx) if tickets_sx else None,
|
||||
summary=SxExpr(summary_sx),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Orders list (same pattern as orders service)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _order_row_sx(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}"
|
||||
def _serialize_order(order: Any) -> dict:
|
||||
"""Serialize an order for SX defcomps."""
|
||||
from shared.infrastructure.urls import market_product_url
|
||||
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 = sx_call(
|
||||
"order-row-desktop",
|
||||
oid=f"#{order.id}", created=created, desc=order.description or "",
|
||||
total=total, pill=pill_cls, status=status, url=detail_url,
|
||||
)
|
||||
|
||||
mobile_pill = f"inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] {pill}"
|
||||
mobile = sx_call(
|
||||
"order-row-mobile",
|
||||
oid=f"#{order.id}", pill=mobile_pill, status=status,
|
||||
created=created, total=total, url=detail_url,
|
||||
)
|
||||
|
||||
return "(<> " + desktop + " " + mobile + ")"
|
||||
items = []
|
||||
if order.items:
|
||||
for item in order.items:
|
||||
items.append({
|
||||
"product_image": item.product_image,
|
||||
"product_title": item.product_title or "Unknown product",
|
||||
"product_id": item.product_id,
|
||||
"product_slug": item.product_slug,
|
||||
"product_url": market_product_url(item.product_slug),
|
||||
"quantity": item.quantity,
|
||||
"unit_price_formatted": f"{item.unit_price or 0:.2f}",
|
||||
"currency": item.currency or order.currency or "GBP",
|
||||
})
|
||||
return {
|
||||
"id": order.id,
|
||||
"status": order.status or "pending",
|
||||
"created_at_formatted": created,
|
||||
"description": order.description or "",
|
||||
"total_formatted": f"{order.total_amount or 0:.2f}",
|
||||
"total_amount": float(order.total_amount or 0),
|
||||
"currency": order.currency or "GBP",
|
||||
"items": items,
|
||||
}
|
||||
|
||||
|
||||
def _orders_rows_sx(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_sx(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(sx_call(
|
||||
"infinite-scroll",
|
||||
url=next_url, page=page, total_pages=total_pages,
|
||||
id_prefix="orders", colspan=5,
|
||||
))
|
||||
else:
|
||||
parts.append(sx_call("order-end-row"))
|
||||
|
||||
return "(<> " + " ".join(parts) + ")"
|
||||
|
||||
|
||||
def _orders_main_panel_sx(orders: list, rows_sx: str) -> str:
|
||||
"""Main panel for orders list."""
|
||||
if not orders:
|
||||
return sx_call("order-empty-state")
|
||||
return sx_call("order-table", rows=SxExpr(rows_sx))
|
||||
|
||||
|
||||
def _orders_summary_sx(ctx: dict) -> str:
|
||||
"""Filter section for orders list."""
|
||||
return sx_call("order-list-header", search_mobile=SxExpr(search_mobile_sx(ctx)))
|
||||
def _serialize_calendar_entry(e: Any) -> dict:
|
||||
"""Serialize an order calendar entry for SX defcomps."""
|
||||
st = e.state or ""
|
||||
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')}"
|
||||
return {
|
||||
"name": e.name,
|
||||
"state": st,
|
||||
"date_str": ds,
|
||||
"cost_formatted": f"{e.cost or 0:.2f}",
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Single order detail
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _order_items_sx(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 = sx_call(
|
||||
"order-item-image",
|
||||
src=item.product_image, alt=item.product_title or "Product image",
|
||||
)
|
||||
else:
|
||||
img = sx_call("order-item-no-image")
|
||||
parts.append(sx_call(
|
||||
"order-item-row",
|
||||
href=prod_url, img=SxExpr(img),
|
||||
title=item.product_title or "Unknown product",
|
||||
pid=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_sx = "(<> " + " ".join(parts) + ")"
|
||||
return sx_call("order-items-panel", items=SxExpr(items_sx))
|
||||
|
||||
|
||||
def _order_summary_sx(order: Any) -> str:
|
||||
"""Order summary card."""
|
||||
return sx_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_sx(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(sx_call(
|
||||
"order-calendar-entry",
|
||||
name=e.name, pill=pill_cls, status=st.capitalize(),
|
||||
date_str=ds, cost=f"\u00a3{e.cost or 0:.2f}",
|
||||
))
|
||||
items_sx = "(<> " + " ".join(parts) + ")"
|
||||
return sx_call("order-calendar-section", items=SxExpr(items_sx))
|
||||
|
||||
|
||||
def _order_main_sx(order: Any, calendar_entries: list | None) -> str:
|
||||
"""Main panel for single order detail."""
|
||||
summary = _order_summary_sx(order)
|
||||
items = _order_items_sx(order)
|
||||
cal = _order_calendar_items_sx(calendar_entries)
|
||||
return sx_call(
|
||||
"order-detail-panel",
|
||||
summary=SxExpr(summary),
|
||||
items=SxExpr(items) if items else None,
|
||||
calendar=SxExpr(cal) if cal else None,
|
||||
)
|
||||
|
||||
|
||||
def _order_filter_sx(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_sx = None
|
||||
if status != "paid":
|
||||
pay_sx = sx_call("order-pay-btn", url=pay_url)
|
||||
|
||||
return sx_call(
|
||||
"order-detail-filter",
|
||||
info=f"Placed {created} \u00b7 Status: {status}",
|
||||
list_url=list_url, recheck_url=recheck_url, csrf=csrf_token,
|
||||
pay=SxExpr(pay_sx) if pay_sx else None,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API: Cart overview
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API: Orders list
|
||||
# Public API: Orders list (used by cart/bp/orders/routes.py)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def render_orders_page(ctx: dict, orders: list, page: int,
|
||||
@@ -602,10 +184,16 @@ async def render_orders_page(ctx: dict, orders: list, page: int,
|
||||
|
||||
ctx["search"] = search
|
||||
ctx["search_count"] = search_count
|
||||
list_url = route_prefix() + url_for_fn("orders.list_orders")
|
||||
pfx = route_prefix()
|
||||
list_url = pfx + url_for_fn("orders.list_orders")
|
||||
rows_url = list_url
|
||||
detail_url_prefix = pfx + url_for_fn("orders.order.order_detail", order_id=0).rsplit("0/", 1)[0]
|
||||
|
||||
rows = _orders_rows_sx(orders, page, total_pages, url_for_fn, qs_fn)
|
||||
main = _orders_main_panel_sx(orders, rows)
|
||||
order_dicts = [_serialize_order(o) for o in orders]
|
||||
content = sx_call("orders-list-content",
|
||||
orders=SxExpr(serialize(order_dicts)),
|
||||
page=page, total_pages=total_pages,
|
||||
rows_url=rows_url, detail_url_prefix=detail_url_prefix)
|
||||
|
||||
hdr = root_header_sx(ctx)
|
||||
auth = _auth_header_sx(ctx)
|
||||
@@ -616,17 +204,40 @@ async def render_orders_page(ctx: dict, orders: list, page: int,
|
||||
)
|
||||
header_rows = "(<> " + hdr + " " + auth_child + ")"
|
||||
|
||||
filt = sx_call("order-list-header", search_mobile=SxExpr(search_mobile_sx(ctx)))
|
||||
return full_page_sx(ctx, header_rows=header_rows,
|
||||
filter=_orders_summary_sx(ctx),
|
||||
filter=filt,
|
||||
aside=search_desktop_sx(ctx),
|
||||
content=main)
|
||||
content=content)
|
||||
|
||||
|
||||
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_sx(orders, page, total_pages, url_for_fn, qs_fn)
|
||||
from shared.utils import route_prefix
|
||||
|
||||
pfx = route_prefix()
|
||||
list_url = pfx + url_for_fn("orders.list_orders")
|
||||
detail_url_prefix = pfx + url_for_fn("orders.order.order_detail", order_id=0).rsplit("0/", 1)[0]
|
||||
|
||||
order_dicts = [_serialize_order(o) for o in orders]
|
||||
parts = [sx_call("order-row-pair",
|
||||
order=SxExpr(serialize(od)),
|
||||
detail_url_prefix=detail_url_prefix)
|
||||
for od in order_dicts]
|
||||
|
||||
if page < total_pages:
|
||||
next_url = list_url + qs_fn(page=page + 1)
|
||||
parts.append(sx_call(
|
||||
"infinite-scroll",
|
||||
url=next_url, page=page, total_pages=total_pages,
|
||||
id_prefix="orders", colspan=5,
|
||||
))
|
||||
else:
|
||||
parts.append(sx_call("order-end-row"))
|
||||
|
||||
return "(<> " + " ".join(parts) + ")"
|
||||
|
||||
|
||||
async def render_orders_oob(ctx: dict, orders: list, page: int,
|
||||
@@ -638,10 +249,16 @@ async def render_orders_oob(ctx: dict, orders: list, page: int,
|
||||
|
||||
ctx["search"] = search
|
||||
ctx["search_count"] = search_count
|
||||
list_url = route_prefix() + url_for_fn("orders.list_orders")
|
||||
pfx = route_prefix()
|
||||
list_url = pfx + url_for_fn("orders.list_orders")
|
||||
rows_url = list_url
|
||||
detail_url_prefix = pfx + url_for_fn("orders.order.order_detail", order_id=0).rsplit("0/", 1)[0]
|
||||
|
||||
rows = _orders_rows_sx(orders, page, total_pages, url_for_fn, qs_fn)
|
||||
main = _orders_main_panel_sx(orders, rows)
|
||||
order_dicts = [_serialize_order(o) for o in orders]
|
||||
content = sx_call("orders-list-content",
|
||||
orders=SxExpr(serialize(order_dicts)),
|
||||
page=page, total_pages=total_pages,
|
||||
rows_url=rows_url, detail_url_prefix=detail_url_prefix)
|
||||
|
||||
auth_oob = _auth_header_sx(ctx, oob=True)
|
||||
auth_child_oob = sx_call(
|
||||
@@ -652,14 +269,15 @@ async def render_orders_oob(ctx: dict, orders: list, page: int,
|
||||
root_oob = root_header_sx(ctx, oob=True)
|
||||
oobs = "(<> " + auth_oob + " " + auth_child_oob + " " + root_oob + ")"
|
||||
|
||||
filt = sx_call("order-list-header", search_mobile=SxExpr(search_mobile_sx(ctx)))
|
||||
return oob_page_sx(oobs=oobs,
|
||||
filter=_orders_summary_sx(ctx),
|
||||
filter=filt,
|
||||
aside=search_desktop_sx(ctx),
|
||||
content=main)
|
||||
content=content)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API: Single order detail
|
||||
# Public API: Single order detail (used by cart/bp/order/routes.py)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def render_order_page(ctx: dict, order: Any,
|
||||
@@ -675,8 +293,16 @@ async def render_order_page(ctx: dict, order: Any,
|
||||
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_sx(order, calendar_entries)
|
||||
filt = _order_filter_sx(order, list_url, recheck_url, pay_url, generate_csrf_token())
|
||||
order_data = _serialize_order(order)
|
||||
cal_data = [_serialize_calendar_entry(e) for e in (calendar_entries or [])]
|
||||
|
||||
main = sx_call("order-detail-content",
|
||||
order=SxExpr(serialize(order_data)),
|
||||
calendar_entries=SxExpr(serialize(cal_data)))
|
||||
filt = sx_call("order-detail-filter-content",
|
||||
order=SxExpr(serialize(order_data)),
|
||||
list_url=list_url, recheck_url=recheck_url,
|
||||
pay_url=pay_url, csrf=generate_csrf_token())
|
||||
|
||||
hdr = root_header_sx(ctx)
|
||||
order_row = sx_call(
|
||||
@@ -708,8 +334,16 @@ async def render_order_oob(ctx: dict, order: Any,
|
||||
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_sx(order, calendar_entries)
|
||||
filt = _order_filter_sx(order, list_url, recheck_url, pay_url, generate_csrf_token())
|
||||
order_data = _serialize_order(order)
|
||||
cal_data = [_serialize_calendar_entry(e) for e in (calendar_entries or [])]
|
||||
|
||||
main = sx_call("order-detail-content",
|
||||
order=SxExpr(serialize(order_data)),
|
||||
calendar_entries=SxExpr(serialize(cal_data)))
|
||||
filt = sx_call("order-detail-filter-content",
|
||||
order=SxExpr(serialize(order_data)),
|
||||
list_url=list_url, recheck_url=recheck_url,
|
||||
pay_url=pay_url, csrf=generate_csrf_token())
|
||||
|
||||
order_row_oob = sx_call(
|
||||
"menu-row-sx",
|
||||
@@ -727,81 +361,42 @@ async def render_order_oob(ctx: dict, order: Any,
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API: Checkout error
|
||||
# Public API: Checkout error (used by cart/bp/cart routes + order routes)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _checkout_error_filter_sx() -> str:
|
||||
return sx_call("checkout-error-header")
|
||||
|
||||
|
||||
def _checkout_error_content_sx(error: str | None, order: Any | None) -> str:
|
||||
async def render_checkout_error_page(ctx: dict, error: str | None = None,
|
||||
order: Any | None = None) -> str:
|
||||
"""Full page: checkout error."""
|
||||
err_msg = error or "Unexpected error while creating the hosted checkout session."
|
||||
order_sx = None
|
||||
if order:
|
||||
order_sx = sx_call("checkout-error-order-id", oid=f"#{order.id}")
|
||||
back_url = cart_url("/")
|
||||
return sx_call(
|
||||
|
||||
hdr = root_header_sx(ctx)
|
||||
filt = sx_call("checkout-error-header")
|
||||
content = sx_call(
|
||||
"checkout-error-content",
|
||||
msg=err_msg,
|
||||
order=SxExpr(order_sx) if order_sx 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_sx(ctx)
|
||||
filt = _checkout_error_filter_sx()
|
||||
content = _checkout_error_content_sx(error, order)
|
||||
return full_page_sx(ctx, header_rows=hdr, filter=filt, content=content)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Page admin (/<page_slug>/admin/)
|
||||
# Public API: POST response renderers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _cart_page_admin_header_sx(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_sx(ctx, slug, oob=oob, selected=selected)
|
||||
|
||||
|
||||
def _cart_admin_main_panel_sx(ctx: dict) -> str:
|
||||
"""Admin overview panel -- links to sub-admin pages."""
|
||||
from quart import url_for
|
||||
payments_href = url_for("defpage_cart_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_sx(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 sx_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)
|
||||
|
||||
|
||||
|
||||
def render_cart_payments_panel(ctx: dict) -> str:
|
||||
"""Render the payments config panel for PUT response."""
|
||||
return _cart_payments_main_panel_sx(ctx)
|
||||
page_config = ctx.get("page_config")
|
||||
pc_data = None
|
||||
if page_config:
|
||||
pc_data = {
|
||||
"sumup_api_key": bool(getattr(page_config, "sumup_api_key", None)),
|
||||
"sumup_merchant_code": getattr(page_config, "sumup_merchant_code", None) or "",
|
||||
"sumup_checkout_prefix": getattr(page_config, "sumup_checkout_prefix", None) or "",
|
||||
}
|
||||
return sx_call("cart-payments-content",
|
||||
page_config=SxExpr(serialize(pc_data)) if pc_data else None)
|
||||
|
||||
@@ -90,20 +90,177 @@ def _register_cart_helpers() -> None:
|
||||
})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Serialization helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _serialize_cart_item(item: Any) -> dict:
|
||||
"""Serialize a cart item + product for SX defcomps."""
|
||||
from quart import url_for
|
||||
from shared.infrastructure.urls import market_product_url
|
||||
|
||||
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"
|
||||
return {
|
||||
"slug": slug,
|
||||
"title": p.title if hasattr(p, "title") else "",
|
||||
"image": p.image if hasattr(p, "image") else None,
|
||||
"brand": getattr(p, "brand", None),
|
||||
"is_deleted": getattr(item, "is_deleted", False),
|
||||
"unit_price": float(unit_price) if unit_price else None,
|
||||
"special_price": float(p.special_price) if getattr(p, "special_price", None) else None,
|
||||
"regular_price": float(p.regular_price) if getattr(p, "regular_price", None) else None,
|
||||
"currency": currency,
|
||||
"quantity": item.quantity,
|
||||
"product_id": p.id,
|
||||
"product_url": market_product_url(slug),
|
||||
"qty_url": url_for("cart_global.update_quantity", product_id=p.id),
|
||||
}
|
||||
|
||||
|
||||
def _serialize_cal_entry(e: Any) -> dict:
|
||||
"""Serialize a calendar entry for SX defcomps."""
|
||||
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 ""
|
||||
return {
|
||||
"name": name,
|
||||
"date_str": f"{start}{end_str}",
|
||||
"cost": float(cost),
|
||||
}
|
||||
|
||||
|
||||
def _serialize_ticket_group(tg: Any) -> dict:
|
||||
"""Serialize a ticket group for SX defcomps."""
|
||||
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')}"
|
||||
|
||||
return {
|
||||
"entry_name": name,
|
||||
"ticket_type_name": tt_name or None,
|
||||
"price": float(price or 0),
|
||||
"quantity": quantity,
|
||||
"line_total": float(line_total or 0),
|
||||
"entry_id": entry_id,
|
||||
"ticket_type_id": tt_id or None,
|
||||
"date_str": date_str,
|
||||
}
|
||||
|
||||
|
||||
def _serialize_page_group(grp: Any) -> dict:
|
||||
"""Serialize a page group for SX defcomps."""
|
||||
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", [])
|
||||
|
||||
if not cart_items and not cal_entries and not tickets:
|
||||
return None
|
||||
|
||||
post_data = None
|
||||
if post:
|
||||
post_data = {
|
||||
"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"),
|
||||
}
|
||||
market_place = grp.get("market_place") if isinstance(grp, dict) else getattr(grp, "market_place", None)
|
||||
mp_data = None
|
||||
if market_place:
|
||||
mp_data = {"name": market_place.name if hasattr(market_place, "name") else market_place.get("name", "")}
|
||||
|
||||
return {
|
||||
"post": post_data,
|
||||
"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": float(grp.get("total", 0) if isinstance(grp, dict) else getattr(grp, "total", 0)),
|
||||
"market_place": mp_data,
|
||||
}
|
||||
|
||||
|
||||
def _build_summary_data(ctx: dict, cart: list, cal_entries: list, tickets: list,
|
||||
total_fn, cal_total_fn, ticket_total_fn) -> dict:
|
||||
"""Build cart summary data dict for SX defcomps."""
|
||||
from quart import g, request, url_for
|
||||
from shared.infrastructure.urls import login_url
|
||||
from shared.utils import route_prefix
|
||||
|
||||
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")
|
||||
|
||||
result = {
|
||||
"item_count": item_count,
|
||||
"grand_total": grand,
|
||||
"symbol": symbol,
|
||||
"is_logged_in": bool(user),
|
||||
}
|
||||
|
||||
if user:
|
||||
if page_post:
|
||||
action = url_for("page_cart.page_checkout")
|
||||
else:
|
||||
action = url_for("cart_global.checkout")
|
||||
result["checkout_action"] = route_prefix() + action
|
||||
result["user_email"] = user.email
|
||||
else:
|
||||
result["login_href"] = login_url(request.url)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Page helper implementations
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def _h_overview_content(**kw):
|
||||
from quart import g
|
||||
from shared.sx.page import get_template_context
|
||||
from sx.sx_components import _overview_main_panel_sx
|
||||
from shared.sx.helpers import sx_call, SxExpr
|
||||
from shared.sx.parser import serialize
|
||||
from shared.infrastructure.urls import cart_url
|
||||
from bp.cart.services import get_cart_grouped_by_page
|
||||
|
||||
page_groups = await get_cart_grouped_by_page(g.s)
|
||||
ctx = await get_template_context()
|
||||
return _overview_main_panel_sx(page_groups, ctx)
|
||||
grp_dicts = [d for d in (_serialize_page_group(grp) for grp in page_groups) if d]
|
||||
return sx_call("cart-overview-content",
|
||||
page_groups=SxExpr(serialize(grp_dicts)),
|
||||
cart_url_base=cart_url(""))
|
||||
|
||||
|
||||
async def _h_page_cart_content(page_slug=None, **kw):
|
||||
from quart import g
|
||||
from shared.sx.helpers import sx_call, SxExpr
|
||||
from shared.sx.parser import serialize
|
||||
from shared.sx.page import get_template_context
|
||||
from sx.sx_components import _page_cart_main_panel_sx
|
||||
from bp.cart.services import total, calendar_total, ticket_total
|
||||
from bp.cart.services.page_cart import (
|
||||
get_cart_for_page, get_calendar_entries_for_page, get_tickets_for_page,
|
||||
@@ -117,21 +274,42 @@ async def _h_page_cart_content(page_slug=None, **kw):
|
||||
ticket_groups = group_tickets(page_tickets)
|
||||
|
||||
ctx = await get_template_context()
|
||||
return _page_cart_main_panel_sx(
|
||||
ctx, cart, cal_entries, page_tickets, ticket_groups,
|
||||
total, calendar_total, ticket_total,
|
||||
)
|
||||
sd = _build_summary_data(ctx, cart, cal_entries, page_tickets,
|
||||
total, calendar_total, ticket_total)
|
||||
|
||||
summary_sx = sx_call("cart-summary-from-data",
|
||||
item_count=sd["item_count"],
|
||||
grand_total=sd["grand_total"],
|
||||
symbol=sd["symbol"],
|
||||
is_logged_in=sd["is_logged_in"],
|
||||
checkout_action=sd.get("checkout_action"),
|
||||
login_href=sd.get("login_href"),
|
||||
user_email=sd.get("user_email"))
|
||||
|
||||
return sx_call("cart-page-cart-content",
|
||||
cart_items=SxExpr(serialize([_serialize_cart_item(i) for i in cart])),
|
||||
cal_entries=SxExpr(serialize([_serialize_cal_entry(e) for e in cal_entries])),
|
||||
ticket_groups=SxExpr(serialize([_serialize_ticket_group(tg) for tg in ticket_groups])),
|
||||
summary=SxExpr(summary_sx))
|
||||
|
||||
|
||||
async def _h_cart_admin_content(page_slug=None, **kw):
|
||||
from shared.sx.page import get_template_context
|
||||
from sx.sx_components import _cart_admin_main_panel_sx
|
||||
ctx = await get_template_context()
|
||||
return _cart_admin_main_panel_sx(ctx)
|
||||
return '(~cart-admin-content)'
|
||||
|
||||
|
||||
async def _h_cart_payments_content(page_slug=None, **kw):
|
||||
from shared.sx.page import get_template_context
|
||||
from sx.sx_components import _cart_payments_main_panel_sx
|
||||
from shared.sx.helpers import sx_call, SxExpr
|
||||
from shared.sx.parser import serialize
|
||||
|
||||
ctx = await get_template_context()
|
||||
return _cart_payments_main_panel_sx(ctx)
|
||||
page_config = ctx.get("page_config")
|
||||
pc_data = None
|
||||
if page_config:
|
||||
pc_data = {
|
||||
"sumup_api_key": bool(getattr(page_config, "sumup_api_key", None)),
|
||||
"sumup_merchant_code": getattr(page_config, "sumup_merchant_code", None) or "",
|
||||
"sumup_checkout_prefix": getattr(page_config, "sumup_checkout_prefix", None) or "",
|
||||
}
|
||||
return sx_call("cart-payments-content",
|
||||
page_config=SxExpr(serialize(pc_data)) if pc_data else None)
|
||||
|
||||
Reference in New Issue
Block a user