from __future__ import annotations from quart import ( render_template, make_response, Blueprint, g, request ) from sqlalchemy import select from models.page_config import PageConfig from suma_browser.app.authz import require_admin from suma_browser.app.utils.htmx import is_htmx_request def register(): bp = Blueprint("payments", __name__, url_prefix='/payments') @bp.context_processor async def inject_root(): return {} async def _load_payment_ctx(): """Load PageConfig SumUp data for the current page.""" post = (getattr(g, "post_data", None) or {}).get("post", {}) post_id = post.get("id") if not post_id: return {} pc = (await g.s.execute( select(PageConfig).where(PageConfig.post_id == post_id) )).scalar_one_or_none() return { "sumup_configured": bool(pc and pc.sumup_api_key), "sumup_merchant_code": (pc.sumup_merchant_code or "") if pc else "", "sumup_checkout_prefix": (pc.sumup_checkout_prefix or "") if pc else "", } @bp.get("/") @require_admin async def home(**kwargs): ctx = await _load_payment_ctx() if not is_htmx_request(): html = await render_template("_types/payments/index.html", **ctx) else: html = await render_template("_types/payments/_oob_elements.html", **ctx) return await make_response(html) @bp.put("/") @require_admin async def update_sumup(**kwargs): """Update SumUp credentials for this page.""" post = (getattr(g, "post_data", None) or {}).get("post", {}) post_id = post.get("id") if not post_id: return await make_response("Post not found", 404) pc = (await g.s.execute( select(PageConfig).where(PageConfig.post_id == post_id) )).scalar_one_or_none() if pc is None: pc = PageConfig(post_id=post_id, features={}) g.s.add(pc) await g.s.flush() form = await request.form merchant_code = (form.get("merchant_code") or "").strip() api_key = (form.get("api_key") or "").strip() checkout_prefix = (form.get("checkout_prefix") or "").strip() pc.sumup_merchant_code = merchant_code or None pc.sumup_checkout_prefix = checkout_prefix or None if api_key: pc.sumup_api_key = api_key await g.s.flush() ctx = await _load_payment_ctx() html = await render_template("_types/payments/_main_panel.html", **ctx) return await make_response(html) return bp