Skip to main content

rustango_cms/admin/
handlers.rs

1//! Admin route handlers — `/cms-admin/...`.
2
3use crate::log_err::LogErr as _;
4use super::{AdminError, PageForm};
5use crate::locale::Locale;
6use crate::media::Media;
7use crate::page::Page;
8use crate::page_type::find_handler;
9use crate::page_type_model::PageType;
10use crate::tree_ops::NewPage;
11use axum::extract::{Form, Path, Query, State};
12use axum::http::{header, HeaderMap, HeaderValue};
13use axum::response::{Html, IntoResponse, Redirect, Response};
14use axum::Json;
15use rustango::core::Column as _;
16use rustango::extractors::Tenant;
17use rustango::messages::Level as MsgLevel;
18use rustango::sql::{transaction_pool, CounterPool as _, FetcherPool as _, FetcherTx as _};
19use serde::Deserialize;
20use std::sync::OnceLock;
21use tera::Context;
22use crate::security_log::Entry as SecurityEntry;
23
24/// HMAC key for the flash-messages cookie, derived from the CMS signing
25/// secret so every replica — and the same server after a restart — reads
26/// the flash another one set.
27pub(crate) fn messages_secret() -> &'static [u8] {
28    static SECRET: OnceLock<Vec<u8>> = OnceLock::new();
29    SECRET.get_or_init(|| crate::signing::derived_key("rcms:flash"))
30}
31
32/// Sanitize WYSIWYG (RichText-widget) HTML server-side before it
33/// reaches a page-type handler's `save_extension`. The TipTap editor
34/// produces constrained HTML, but a bypassed client could POST anything,
35/// so we ammonia-clean every RichText-kind field value (looked up by the
36/// handler's own widget definitions) before persisting. This is the
37/// on-save enforcement point for extension fields; stream rich-text blocks
38/// + markdown bodies already sanitize on their own render paths, and the
39/// `| richtext` filter stays a pure linktype-rewriter that trusts the now-
40/// sanitized stored HTML. Returns a sanitized clone of `form_map`.
41async fn sanitized_extension_form(
42    handler: &dyn crate::page_type::PageTypeHandler,
43    pool: &rustango::sql::Pool,
44    page_id: i64,
45    form_map: &std::collections::HashMap<String, String>,
46) -> std::collections::HashMap<String, String> {
47    let mut out = form_map.clone();
48    if let Ok(widgets) = handler.widgets(pool, page_id).await {
49        for w in widgets {
50            if w.kind == crate::widget::WidgetKind::RichText {
51                if let Some(raw) = out.get(&w.name) {
52                    let cleaned = crate::markdown::sanitize_html(raw);
53                    out.insert(w.name.clone(), cleaned);
54                }
55            }
56        }
57    }
58    out
59}
60
61/// How long a preview token stays valid: long enough for an editor to
62/// click through and iterate, short enough that a URL pasted into a chat
63/// stops working before it becomes a way in.
64const PREVIEW_TOKEN_TTL_SECS: i64 = 3600;
65
66/// Render a CMS-admin Tera template with the CSRF token + drained
67/// flash messages stamped into the context. Returns a `Response`
68/// that carries:
69///   - any `Set-Cookie` the CSRF middleware needs to mint a fresh
70///     token (first GET per session, or when the cookie was
71///     invalidated);
72///   - the clear-cookie that empties the messages store so each
73///     flash renders exactly once.
74///
75/// Every form-rendering admin handler routes through this helper so
76/// `{{ csrf_token | csrf_input | safe }}` and
77/// `{% for msg in messages %}…{% endfor %}` in templates always
78/// resolve correctly.
79pub(crate) fn render_with_csrf(
80    state: &super::AdminState,
81    headers: &HeaderMap,
82    template: &str,
83    ctx: &mut Context,
84) -> Result<Response, AdminError> {
85    render_tera(&state.tera, headers, template, ctx)
86}
87
88/// [`render_with_csrf`] for a caller that holds the Tera instance
89/// rather than the admin state (custom admin pages).
90pub(crate) fn render_tera(
91    tera: &tera::Tera,
92    headers: &HeaderMap,
93    template: &str,
94    ctx: &mut Context,
95) -> Result<Response, AdminError> {
96    // #525/#526 — resolve the admin UI locale per request and expose it to the
97    // template. Done here so every admin page picks it up without threading
98    // through each handler. Precedence: sticky cookie → per-user preference
99    // (#526, surfaced into the ctx by `add_user_chrome`) → Accept-Language →
100    // per-tenant default (#526) → English.
101    let user_pref = ctx
102        .get("user_lang_pref")
103        .and_then(|v| v.as_str())
104        .map(str::to_owned);
105    let tenant_default = super::i18n::tenant_default_locale();
106    let lang = super::i18n::negotiate(
107        headers.get(header::COOKIE).and_then(|v| v.to_str().ok()),
108        headers
109            .get(header::ACCEPT_LANGUAGE)
110            .and_then(|v| v.to_str().ok()),
111        user_pref.as_deref(),
112        tenant_default.as_deref(),
113    );
114    let lang_dir = rustango::i18n::text_direction(&lang);
115    ctx.insert("LANG", &lang);
116    ctx.insert("LANG_DIR", lang_dir);
117    let csrf_cookie = rustango::forms::csrf::stamp_into_context(headers, ctx);
118    let msg_clear = rustango::messages::stamp_into_context(messages_secret(), headers, ctx);
119    let html = tera.render(template, ctx)?;
120    let mut resp = Html(html).into_response();
121    if let Some(c) = csrf_cookie {
122        if let Ok(v) = HeaderValue::from_str(&c) {
123            resp.headers_mut().append(header::SET_COOKIE, v);
124        }
125    }
126    if let Some(c) = msg_clear {
127        if let Ok(v) = HeaderValue::from_str(&c) {
128            resp.headers_mut().append(header::SET_COOKIE, v);
129        }
130    }
131    Ok(resp)
132}
133
134/// Redirect to a named route registered in [`crate::urls`] AND
135/// stage a flash message ([`rustango::messages`]) in the response
136/// cookie so the next GET at the destination renders it through
137/// the `messages` Tera context variable. The standard "POST → 303
138/// → render flash" idiom — every cms-admin POST handler returns
139/// through this (or its `_with_params` cousin) so editors get
140/// real feedback instead of a silent navigation.
141fn redirect_named_with_message(
142    name: &'static str,
143    level: MsgLevel,
144    body: &str,
145    headers: &HeaderMap,
146) -> Result<Response, AdminError> {
147    let url = rustango::urls::reverse(name, &std::collections::HashMap::new())
148        .map_err(|e| AdminError::Validation(format!("url reversal of `{name}` failed: {e}")))?;
149    // #528 — localize the flash for the request's admin locale (English source
150    // is the key; untranslated → unchanged).
151    let body = super::i18n::tr(headers, body, &[]);
152    Ok(rustango::messages::redirect_with_message(
153        messages_secret(),
154        headers,
155        level,
156        &body,
157        &url,
158    ))
159}
160
161/// Like [`redirect_named_with_message`] but the message is a **parameterized**
162/// translation key: the English source — with `{name}` placeholders — is
163/// the catalog key, localized + interpolated for the request locale before
164/// staging. Use instead of `&format!(…)` so the flash localizes. The framework
165/// substitutes placeholders into the source-string fallback too, so English
166/// (empty catalog) renders correctly without a catalog entry.
167fn redirect_named_with_message_args(
168    name: &'static str,
169    level: MsgLevel,
170    key: &str,
171    args: &[(&str, &str)],
172    headers: &HeaderMap,
173) -> Result<Response, AdminError> {
174    let url = rustango::urls::reverse(name, &std::collections::HashMap::new())
175        .map_err(|e| AdminError::Validation(format!("url reversal of `{name}` failed: {e}")))?;
176    let body = super::i18n::tr(headers, key, args);
177    Ok(rustango::messages::redirect_with_message(
178        messages_secret(),
179        headers,
180        level,
181        &body,
182        &url,
183    ))
184}
185
186/// Count-aware cousin of [`redirect_named_with_message_args`]:
187/// `key` is a plural source key, the form is chosen for `n` in the request
188/// locale (CLDR rules) and `args` interpolated. Pass the count as an arg too
189/// (e.g. `("count", &n.to_string())`) so the chosen form's `{count}` fills in.
190fn redirect_named_with_message_plural(
191    name: &'static str,
192    level: MsgLevel,
193    key: &str,
194    n: i64,
195    args: &[(&str, &str)],
196    headers: &HeaderMap,
197) -> Result<Response, AdminError> {
198    let url = rustango::urls::reverse(name, &std::collections::HashMap::new())
199        .map_err(|e| AdminError::Validation(format!("url reversal of `{name}` failed: {e}")))?;
200    let body = super::i18n::tr_plural(headers, key, n, args);
201    Ok(rustango::messages::redirect_with_message(
202        messages_secret(),
203        headers,
204        level,
205        &body,
206        &url,
207    ))
208}
209
210/// Plural cousin of [`redirect_named_with_params_and_message`] —
211/// for routes with path params AND a count-aware message.
212fn redirect_named_with_params_and_message_plural(
213    name: &'static str,
214    params: &[(&str, String)],
215    level: MsgLevel,
216    key: &str,
217    n: i64,
218    args: &[(&str, &str)],
219    headers: &HeaderMap,
220) -> Result<Response, AdminError> {
221    let owned: std::collections::HashMap<String, String> = params
222        .iter()
223        .map(|(k, v)| ((*k).to_owned(), v.clone()))
224        .collect();
225    let url = rustango::urls::reverse_owned(name, &owned)
226        .map_err(|e| AdminError::Validation(format!("url reversal of `{name}` failed: {e}")))?;
227    let body = super::i18n::tr_plural(headers, key, n, args);
228    Ok(rustango::messages::redirect_with_message(
229        messages_secret(),
230        headers,
231        level,
232        &body,
233        &url,
234    ))
235}
236
237/// Friendly 401 response for handlers that bail when
238/// `SessionUser` resolves to `None`. Two content-types based on
239/// `Accept`:
240///
241/// - **`application/json`** — JSON `{ error: "session_expired",
242///   message, login_url }`. XHR / fetch clients (notably the bulk
243///   media uploader) used to inline-dump the HTML page into a toast,
244///   which read as garbage. JSON lets the client render a clean
245///   "Sign in again to keep uploading" banner instead.
246/// - **Anything else** — the HTML explainer page below, useful for
247///   `<form>` POSTs that hit Submit after the cookie went stale.
248///
249/// The middleware-level `with_login_required` layer already
250/// 302s anonymous GETs to /login. A POST hitting this guard means
251/// the cookie was DECODED as anonymous (expired / wrong tenant /
252/// stale), so a hard 401 with an explanation lands better than a
253/// redirect loop.
254fn unauthorized_no_session() -> Response {
255    unauthorized_no_session_for(None)
256}
257
258/// Content-negotiating variant of [`unauthorized_no_session`]. Pass
259/// the request `HeaderMap` so the client's `Accept` (and the legacy
260/// `X-Requested-With: XMLHttpRequest`) can pick between the JSON
261/// payload and the HTML page.
262fn unauthorized_no_session_for(headers: Option<&HeaderMap>) -> Response {
263    let wants_json = headers
264        .map(|h| {
265            let accept = h
266                .get(header::ACCEPT)
267                .and_then(|v| v.to_str().ok())
268                .unwrap_or("");
269            if accept.contains("application/json") {
270                return true;
271            }
272            h.get("x-requested-with")
273                .and_then(|v| v.to_str().ok())
274                .is_some_and(|v| v.eq_ignore_ascii_case("XMLHttpRequest"))
275        })
276        .unwrap_or(false);
277    // #528 — localize for the request's admin locale when headers are present
278    // (this is the one polished user-facing admin error page); English otherwise.
279    let t = |key: &str| -> String {
280        match headers {
281            Some(h) => super::i18n::tr(h, key, &[]),
282            None => key.to_owned(),
283        }
284    };
285    if wants_json {
286        let payload = serde_json::json!({
287            "error": "session_expired",
288            "message": t("Sign in again to keep uploading."),
289            "login_url": "/login?next=/cms-admin/",
290        });
291        return (
292            axum::http::StatusCode::UNAUTHORIZED,
293            [(axum::http::header::CONTENT_TYPE, "application/json")],
294            serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_owned()),
295        )
296            .into_response();
297    }
298    let lang = headers
299        .map(|h| {
300            super::i18n::negotiate(
301                h.get(header::COOKIE).and_then(|v| v.to_str().ok()),
302                h.get(header::ACCEPT_LANGUAGE).and_then(|v| v.to_str().ok()),
303                None,
304                super::i18n::tenant_default_locale().as_deref(),
305            )
306        })
307        .unwrap_or_else(|| "en".to_owned());
308    let dir = rustango::i18n::text_direction(&lang);
309    const STYLE: &str = r#"<style>
310body{font:14px/1.5 -apple-system,system-ui,sans-serif;color:#222;background:#fafafa;margin:0;padding:48px 20px}
311.box{max-width:560px;margin:0 auto;padding:32px;background:#fff;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.08)}
312h1{font-size:18px;margin:0 0 12px}
313p{margin:0 0 12px;color:#444}
314ul{margin:0 0 12px;padding-left:20px;color:#444}
315li{margin:4px 0}
316a{color:#1565c0}
317</style>"#;
318    let mut body = String::with_capacity(STYLE.len() + 1024);
319    body.push_str("<!doctype html>\n<html lang=\"");
320    body.push_str(&crate::forms::render::html_escape(&lang));
321    body.push_str("\" dir=\"");
322    body.push_str(dir);
323    body.push_str("\"><head><meta charset=\"utf-8\"><title>");
324    body.push_str(&crate::forms::render::html_escape(&t("Session expired")));
325    body.push_str(" — ");
326    body.push_str(&crate::forms::render::html_escape(&t("CMS Admin")));
327    body.push_str("</title>");
328    body.push_str(STYLE);
329    body.push_str("</head><body><div class=\"box\">\n<h1>");
330    body.push_str(&crate::forms::render::html_escape(&t(
331        "Your session has expired",
332    )));
333    body.push_str("</h1>\n<p>");
334    body.push_str(&crate::forms::render::html_escape(&t(
335        "The form couldn't be saved because your admin session decoded as anonymous. The most likely causes:",
336    )));
337    body.push_str("</p>\n<ul>\n<li>");
338    body.push_str(&crate::forms::render::html_escape(&t(
339        "Your login session expired or was signed out from another tab.",
340    )));
341    body.push_str("</li>\n<li>");
342    body.push_str(&crate::forms::render::html_escape(&t(
343        "The cookie was issued for a different tenant slug.",
344    )));
345    body.push_str("</li>\n<li>");
346    body.push_str(&crate::forms::render::html_escape(&t(
347        "On sqlite/mysql builds the framework's tenant session store may not be wired up yet (see issue #259).",
348    )));
349    body.push_str("</li>\n</ul>\n<p><a href=\"/login?next=/cms-admin/\">");
350    body.push_str(&crate::forms::render::html_escape(&t("Sign back in")));
351    body.push_str("</a>");
352    body.push_str(&crate::forms::render::html_escape(&t(
353        ", then re-submit the form.",
354    )));
355    body.push_str("</p>\n</div></body></html>");
356    (
357        axum::http::StatusCode::UNAUTHORIZED,
358        [(axum::http::header::CONTENT_TYPE, "text/html; charset=utf-8")],
359        body,
360    )
361        .into_response()
362}
363
364/// Like [`redirect_named_with_message`], but for routes with path
365/// parameters (e.g. `rcms-admin:pages:edit` needing `{id}`).
366pub(crate) fn redirect_named_with_params_and_message(
367    name: &'static str,
368    params: &[(&str, String)],
369    level: MsgLevel,
370    body: &str,
371    headers: &HeaderMap,
372) -> Result<Response, AdminError> {
373    let owned: std::collections::HashMap<String, String> = params
374        .iter()
375        .map(|(k, v)| ((*k).to_owned(), v.clone()))
376        .collect();
377    let url = rustango::urls::reverse_owned(name, &owned)
378        .map_err(|e| AdminError::Validation(format!("url reversal of `{name}` failed: {e}")))?;
379    // #528 — localize the flash for the request's admin locale.
380    let body = super::i18n::tr(headers, body, &[]);
381    Ok(rustango::messages::redirect_with_message(
382        messages_secret(),
383        headers,
384        level,
385        &body,
386        &url,
387    ))
388}
389
390/// Parameterized-key cousin of [`redirect_named_with_params_and_message`]
391/// for routes that take path params AND a localized message with `{name}`
392/// interpolation.
393pub(crate) fn redirect_named_with_params_and_message_args(
394    name: &'static str,
395    params: &[(&str, String)],
396    level: MsgLevel,
397    key: &str,
398    args: &[(&str, &str)],
399    headers: &HeaderMap,
400) -> Result<Response, AdminError> {
401    let owned: std::collections::HashMap<String, String> = params
402        .iter()
403        .map(|(k, v)| ((*k).to_owned(), v.clone()))
404        .collect();
405    let url = rustango::urls::reverse_owned(name, &owned)
406        .map_err(|e| AdminError::Validation(format!("url reversal of `{name}` failed: {e}")))?;
407    let body = super::i18n::tr(headers, key, args);
408    Ok(rustango::messages::redirect_with_message(
409        messages_secret(),
410        headers,
411        level,
412        &body,
413        &url,
414    ))
415}
416
417/// Resolve the post-save redirect from the three-action save
418/// footer (`_save` / `_continue` /
419/// `_addanother`). Shared by `page_new_submit` and `page_edit_submit`
420/// so both honour the same button the editor pressed:
421///
422/// * `continue`   → back to **this** page's edit form (keep editing).
423/// * `addanother` → a fresh new-page form, preselecting the same parent
424///   so the next page lands as a sibling (`pages:new` honours
425///   `?parent=<id>`); root pages omit the query.
426/// * anything else (incl. the default `save` / missing) → the page list.
427///
428/// `body` must already be localized by the caller (via `tr` / `tr_plural`) —
429/// this dispatcher only resolves the destination URL and stages the message,
430/// so every branch (including `addanother`) treats `body` identically.
431fn redirect_after_page_save(
432    action: &str,
433    page_id: i64,
434    parent_id: Option<i64>,
435    body: &str,
436    headers: &HeaderMap,
437) -> Result<Response, AdminError> {
438    redirect_after_page_save_with_level(action, page_id, parent_id, body, MsgLevel::Success, headers)
439}
440
441/// [`redirect_after_page_save`] with a flash of `level`.
442fn redirect_after_page_save_with_level(
443    action: &str,
444    page_id: i64,
445    parent_id: Option<i64>,
446    body: &str,
447    level: MsgLevel,
448    headers: &HeaderMap,
449) -> Result<Response, AdminError> {
450    let url = match action {
451        "continue" => rustango::urls::reverse_owned(
452            "rcms-admin:pages:edit",
453            &std::iter::once(("id".to_owned(), page_id.to_string())).collect(),
454        )
455        .map_err(|e| AdminError::Validation(format!("url reversal of `pages:edit` failed: {e}")))?,
456        "addanother" => {
457            let base =
458                rustango::urls::reverse("rcms-admin:pages:new", &std::collections::HashMap::new())
459                    .map_err(|e| {
460                        AdminError::Validation(format!("url reversal of `pages:new` failed: {e}"))
461                    })?;
462            match parent_id {
463                Some(pid) => format!("{base}?parent={pid}"),
464                None => base,
465            }
466        }
467        _ => rustango::urls::reverse("rcms-admin:pages:list", &std::collections::HashMap::new())
468            .map_err(|e| {
469                AdminError::Validation(format!("url reversal of `pages:list` failed: {e}"))
470            })?,
471    };
472    Ok(rustango::messages::redirect_with_message(
473        messages_secret(),
474        headers,
475        level,
476        body,
477        &url,
478    ))
479}
480
481/// A user's email: the `email` column — what member sign-in, SSO and
482/// sign-up use — else the address older admin versions kept in
483/// `data.email`. Empty when neither is set.
484pub(crate) fn user_email(u: &rustango::tenancy::auth::User) -> String {
485    u.email
486        .as_deref()
487        .map(str::trim)
488        .filter(|e| !e.is_empty())
489        .or_else(|| u.data.get("email").and_then(|v| v.as_str()).map(str::trim))
490        .unwrap_or("")
491        .to_owned()
492}
493
494/// Add the chrome variables every section template reads from
495/// `_base.html`: which sidebar tab is active, the brand-display
496/// name, the current tenant slug, and — when a [`SessionUser`](rustango::extractors::SessionUser) is
497/// in scope — the sidebar gating set + per-user timezone.
498///
499/// Pass `session_user.as_ref()` from the handler signature; pass
500/// `None` for anon flows (login / password-reset). When `None`,
501/// `sidebar_gating` stays `false` so every sidebar item renders.
502///
503/// Public so a host application's [`AdminPageHandler`] can render inside
504/// the admin chrome. Without it the extension point only works for a page
505/// that does NOT extend `rcms_admin/_base.html`, since that template
506/// dereferences roughly two dozen chrome variables — and hand-supplying
507/// them in a host app is a copy that drifts silently on every release.
508///
509/// [`AdminPageHandler`]: super::admin_page::AdminPageHandler
510pub async fn add_chrome(
511    ctx: &mut Context,
512    tenant: &Tenant,
513    active_tab: &str,
514    session_user: Option<&rustango::tenancy::auth::User>,
515) {
516    add_chrome_for(ctx, tenant.pool(), &tenant.org, active_tab, session_user).await;
517}
518
519/// [`add_chrome`] from the tenant's pool and org.
520async fn add_chrome_for(
521    ctx: &mut Context,
522    pool: &rustango::sql::Pool,
523    org: &rustango::tenancy::Org,
524    active_tab: &str,
525    session_user: Option<&rustango::tenancy::auth::User>,
526) {
527    add_chrome_sync_for(ctx, org, active_tab);
528    if let Some(user) = session_user {
529        add_user_chrome(ctx, user, pool).await;
530    }
531    // #199 — per-tenant logo + favicon URLs (see [`add_branding_urls`]).
532    add_branding_urls_for(ctx, pool, org).await;
533}
534
535/// What the pre-sign-in screens (sign-in, password reset, member sign-up)
536/// share with the admin: the tenant's branding and its admin theme, so
537/// their colours and font match the admin (#918).
538pub(crate) async fn add_auth_chrome(ctx: &mut Context, tenant: &Tenant) {
539    add_branding_urls(ctx, tenant).await;
540    add_admin_theme(ctx, tenant.pool()).await;
541}
542
543/// Inject the per-tenant admin logo + favicon URLs from the `branding`
544/// site setting into a template context. Missing/empty rows leave the ctx slots
545/// unset, so templates fall back to the brand-name text + default icon. Shared
546/// by the authenticated chrome ([`add_chrome`]) and the pre-auth login /
547/// password-reset screens (which have no `add_chrome`), so those can show the
548/// tenant's branding too. The serve routes (`/__cms-branding/*`) live in
549/// `public_router` so the images load before sign-in.
550pub(crate) async fn add_branding_urls(ctx: &mut Context, tenant: &Tenant) {
551    add_branding_urls_for(ctx, tenant.pool(), &tenant.org).await;
552}
553
554async fn add_branding_urls_for(ctx: &mut Context, pool: &rustango::sql::Pool, org: &rustango::tenancy::Org) {
555    // One name, logo and icon for the admin and the site: Settings →
556    // Branding (see `crate::branding`).
557    let branding = crate::branding::get(pool).await;
558    let site_name = crate::branding::site_name(&branding, org);
559    if crate::branding::has(&branding, crate::branding::Picture::Logo) {
560        ctx.insert("branding_logo_url", crate::branding::Picture::Logo.url());
561    }
562    if crate::branding::has(&branding, crate::branding::Picture::Favicon) {
563        ctx.insert("branding_favicon_url", crate::branding::Picture::Favicon.url());
564    }
565    ctx.insert("site_name", &site_name);
566}
567
568/// Sync core of [`add_chrome`] — every call site benefits from
569/// re-using it, so it's broken out for clarity. Stuffs the static
570/// chrome bits (tab, tenant, brand, default tz, registered admin
571/// pages) into the context.
572fn add_chrome_sync_for(ctx: &mut Context, org: &rustango::tenancy::Org, active_tab: &str) {
573    ctx.insert("active_tab", active_tab);
574    ctx.insert("tenant_slug", &org.slug);
575    // #524 — admin UI locale + text direction for `<html lang/dir>` and the
576    // `translate(locale=LANG)` calls. The default here is overridden per
577    // request by `render_with_csrf` (#525 negotiation).
578    ctx.insert("LANG", "en");
579    ctx.insert("LANG_DIR", "ltr");
580    // #525 — the shipped UI locales, for the language switcher.
581    ctx.insert(
582        "ui_locales",
583        &super::i18n::UI_LOCALES
584            .iter()
585            .map(|(c, n)| serde_json::json!({ "code": c, "name": n }))
586            .collect::<Vec<_>>(),
587    );
588    // user_timezone defaults to empty; PG-authenticated requests
589    // get it filled in via `add_user_chrome` (called explicitly by
590    // handlers that have a SessionUser extractor in scope).
591    ctx.insert("user_timezone", "");
592    // #13 V2 — tenant default timezone. Sourced from
593    // `RUSTANGO_CMS_DEFAULT_TIMEZONE` so multi-tenant deployments can
594    // pin a sensible regional default without a schema change. The
595    // boot script in _base.html resolves in order:
596    //   user pref → tenant default → browser default.
597    // Process configuration, read once rather than on every admin page.
598    static DEFAULT_TZ: std::sync::OnceLock<String> = std::sync::OnceLock::new();
599    let tenant_default_tz = DEFAULT_TZ
600        .get_or_init(|| crate::config::var("DEFAULT_TIMEZONE").unwrap_or_default())
601        .clone();
602    ctx.insert("tenant_default_timezone", &tenant_default_tz);
603
604    // Custom admin pages (#23) — bucket every registered handler by
605    // its declared sidebar section so `_base.html` can group them
606    // under the right heading. Sort within each bucket by
607    // `(sort_order, label)` so authors can pin position.
608    let mut by_section: std::collections::BTreeMap<String, Vec<serde_json::Value>> =
609        std::collections::BTreeMap::new();
610    for handler in super::admin_page::registered_admin_pages() {
611        let section = handler.section().label().to_owned();
612        by_section
613            .entry(section)
614            .or_default()
615            .push(serde_json::json!({
616                "slug": handler.slug(),
617                "label": handler.label(),
618                "icon": handler.icon(),
619                "sort_order": handler.sort_order(),
620            }));
621    }
622    for items in by_section.values_mut() {
623        items.sort_by(|a, b| {
624            let ao = a.get("sort_order").and_then(|v| v.as_i64()).unwrap_or(100);
625            let bo = b.get("sort_order").and_then(|v| v.as_i64()).unwrap_or(100);
626            ao.cmp(&bo).then_with(|| {
627                a.get("label")
628                    .and_then(|v| v.as_str())
629                    .unwrap_or("")
630                    .cmp(b.get("label").and_then(|v| v.as_str()).unwrap_or(""))
631            })
632        });
633    }
634    ctx.insert("extra_admin_pages_by_section", &by_section);
635    // #439 — registry-driven report links. `_base.html` lists these
636    // under the Reports group below the built-in reports, so a
637    // `register_report!`ed report shows up in the nav with no template
638    // edit. Already title-sorted by `registered_reports()`.
639    let reports_nav: Vec<serde_json::Value> = super::report::registered_reports()
640        .iter()
641        .map(|r| {
642            serde_json::json!({
643                "slug": r.slug(),
644                "title": r.title(),
645                "icon": r.icon(),
646            })
647        })
648        .collect();
649    ctx.insert("registered_reports", &reports_nav);
650    // #107 — plugin-contributed admin menu items (runtime hook B13).
651    // Rendered at the bottom of the sidebar in stable key order.
652    let plugin_menu_items: Vec<serde_json::Value> = crate::hooks::admin_menu_items()
653        .into_iter()
654        .map(|i| {
655            serde_json::json!({
656                "key": i.key,
657                "label": i.label,
658                "icon": i.icon,
659                "href": i.href,
660            })
661        })
662        .collect();
663    ctx.insert("plugin_admin_menu_items", &plugin_menu_items);
664    // #127 — help-menu entries. Rendered in a
665    // dedicated "Help" sidebar section above Plugins.
666    let help_menu_items: Vec<serde_json::Value> = crate::hooks::help_menu_items()
667        .into_iter()
668        .map(|i| {
669            serde_json::json!({
670                "key": i.key,
671                "label": i.label,
672                "icon": i.icon,
673                "href": i.href,
674            })
675        })
676        .collect();
677    ctx.insert("help_menu_items", &help_menu_items);
678    // #422 — plugin-injected global admin CSS / JS. `_base.html` emits each blob inside
679    // a <style> / <script> tag.
680    ctx.insert("admin_css_blobs", &crate::hooks::admin_css());
681    ctx.insert("admin_js_blobs", &crate::hooks::admin_js());
682    // Sidebar gating defaults: when no SessionUser is in scope (anon
683    // public_router flows like login + password-reset), keep every
684    // sidebar item visible. Handlers with a `SessionUser` extractor
685    // override this via `add_user_chrome` below.
686    ctx.insert("sidebar_gating", &false);
687    ctx.insert("user_is_superuser", &false);
688    ctx.insert(
689        "allowed_resources",
690        &std::collections::HashSet::<String>::new(),
691    );
692}
693
694/// Per-request chrome extension for authenticated requests. Fills in
695/// the bits `add_chrome` can't compute without a user in scope:
696///
697/// - `user_timezone` from `User.data.timezone`. Empty when
698///   unset so the no-flash JS falls back to the browser TZ.
699/// - `allowed_resources`: the union of role codenames the user
700///   inherits, used to gate sidebar items + admin-side CRUD chips.
701///   Superusers skip the gating set entirely (the sidebar
702///   template checks `user_is_superuser` first).
703/// - `user_is_superuser`: short-circuit flag exposed to templates so
704///   they don't iterate the codename set when access is unconditional.
705/// - `sidebar_gating: true`: tells `_base.html` to start honoring
706///   the gating set (anon flows leave this `false` so login pages
707///   render their full chrome).
708pub(crate) async fn add_user_chrome(
709    ctx: &mut Context,
710    user: &rustango::tenancy::auth::User,
711    pool: &rustango::sql::Pool,
712) {
713    let user_timezone = user
714        .data
715        .get("timezone")
716        .and_then(serde_json::Value::as_str)
717        .unwrap_or("")
718        .to_owned();
719    ctx.insert("user_timezone", &user_timezone);
720    // #526 — durable per-user admin UI language. Surfaced into the ctx here (the
721    // one place with the authenticated user) so `render_with_csrf` can fold it
722    // into locale negotiation without threading the user through every handler.
723    if let Some(pref) = user
724        .data
725        .get("admin_lang")
726        .and_then(serde_json::Value::as_str)
727        .filter(|s| super::i18n::is_ui_locale(s))
728    {
729        ctx.insert("user_lang_pref", pref);
730    }
731    ctx.insert("user_is_superuser", &user.is_superuser);
732    ctx.insert("user_username", &user.username);
733    // #201 — profile chrome. The display name lives in
734    // rustango_users.data.display_name; fall back to the username.
735    // Avatar lives at /__cms-avatar/<user_id> when the user uploaded
736    // one (avatar_path is set as a side-effect of the upload route).
737    let display_name = user
738        .data
739        .get("display_name")
740        .and_then(serde_json::Value::as_str)
741        .filter(|s| !s.is_empty())
742        .unwrap_or(&user.username)
743        .to_owned();
744    ctx.insert("user_display_name", &display_name);
745    let has_avatar = user
746        .data
747        .get("avatar_path")
748        .and_then(serde_json::Value::as_str)
749        .map(|s| !s.is_empty())
750        .unwrap_or(false);
751    if has_avatar {
752        let uid = user.id.get().copied().unwrap_or(0);
753        ctx.insert("user_avatar_url", &format!("/__cms-avatar/{uid}"));
754    }
755    let codenames = if user.is_superuser {
756        // Superusers bypass gating; we still hand the template an
757        // empty set so unconditional checks work without branching.
758        std::collections::HashSet::<String>::new()
759    } else {
760        let uid = user.id.get().copied().unwrap_or(0);
761        crate::permissions::user_codenames(pool, uid)
762            .await
763            .unwrap_or_default()
764    };
765    ctx.insert("allowed_resources", &codenames);
766    ctx.insert("sidebar_gating", &true);
767}
768
769/// GET /cms-admin/media/collections — manage every collection in the
770/// tenant. Tree view with depth-indented names, per-row rename /
771/// delete + a "new" form per parent.
772pub async fn collections_list(
773    State(state): State<super::AdminState>,
774    tenant: Tenant,
775    headers: HeaderMap,
776    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
777    Query(paging): Query<crate::admin::pagination::PageQuery>,
778    axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
779) -> Result<Response, AdminError> {
780    // Every collection is read: the depth walk and the "Parent" picker
781    // need the whole tree, and the rows are small. The table is paged.
782    let collections: Vec<crate::media::MediaCollection> = crate::media::MediaCollection::objects()
783        .order_by(&[("parent_id", false), ("sort_order", false), ("name", false)])
784        .fetch(tenant.pool())
785        .await?;
786    // Walk into a depth-tagged tree so the template can render
787    // indented names without computing the depth itself.
788    let by_id: std::collections::HashMap<i64, &crate::media::MediaCollection> = collections
789        .iter()
790        .filter_map(|c| c.id.get().copied().map(|id| (id, c)))
791        .collect();
792    fn depth(
793        c: &crate::media::MediaCollection,
794        by_id: &std::collections::HashMap<i64, &crate::media::MediaCollection>,
795        cache: &mut std::collections::HashMap<i64, i32>,
796    ) -> i32 {
797        let id = c.id.get().copied().unwrap_or_default();
798        if let Some(d) = cache.get(&id) {
799            return *d;
800        }
801        let d = match c.parent_id {
802            None => 0,
803            Some(pid) => match by_id.get(&pid) {
804                Some(parent) => depth(parent, by_id, cache) + 1,
805                None => 0,
806            },
807        };
808        cache.insert(id, d);
809        d
810    }
811    // Media counts per collection so editors see usage at a glance —
812    // counted in SQL, not by loading the media library.
813    let counts = counts_by(tenant.pool(), Media::objects(), "collection_id").await?;
814    let mut depth_cache: std::collections::HashMap<i64, i32> = std::collections::HashMap::new();
815    let rows: Vec<serde_json::Value> = collections
816        .iter()
817        .map(|c| {
818            let id = c.id.get().copied().unwrap_or_default();
819            serde_json::json!({
820                "id": id,
821                "name": c.name,
822                "parent_id": c.parent_id,
823                // #318 — resolve the parent FK to its display name so the
824                // list shows "Photos" instead of a raw `#17`.
825                "parent_name": c.parent_id.and_then(|pid| by_id.get(&pid)).map(|p| p.name.clone()),
826                "sort_order": c.sort_order,
827                "depth": depth(c, &by_id, &mut depth_cache),
828                "media_count": counts.get(&id).copied().unwrap_or(0),
829                "created_at": c.created_at.get().copied(),
830            })
831        })
832        .collect();
833
834    let window = paging.window(rows.len());
835    let page_rows: Vec<&serde_json::Value> = rows
836        .iter()
837        .skip(usize::try_from(window.offset).unwrap_or_default())
838        .take(usize::try_from(window.limit).unwrap_or_default())
839        .collect();
840    let mut ctx = Context::new();
841    add_chrome(&mut ctx, &tenant, "media", session_user.as_ref()).await;
842    add_admin_theme(&mut ctx, tenant.pool()).await;
843    ctx.insert("collections", &rows);
844    ctx.insert("collection_rows", &page_rows);
845    ctx.insert("pagination", &window.context);
846    ctx.insert("query_string", &raw_query.unwrap_or_default());
847    render_with_csrf(
848        &state,
849        &headers,
850        "rcms_admin/collections_list.html",
851        &mut ctx,
852    )
853}
854
855/// Form payload for create / rename of a collection.
856#[derive(Debug, Deserialize)]
857pub struct CollectionForm {
858    pub name: String,
859    #[serde(default, deserialize_with = "super::deserialize_optional_i64")]
860    pub parent_id: Option<i64>,
861    #[serde(default)]
862    pub sort_order: Option<i32>,
863}
864
865/// POST /cms-admin/media/collections/new — create.
866pub async fn collections_create(
867    State(_state): State<super::AdminState>,
868    tenant: Tenant,
869    headers: HeaderMap,
870    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
871    Form(form): Form<CollectionForm>,
872) -> Result<Response, AdminError> {
873    let name = form.name.trim().to_owned();
874    if name.is_empty() {
875        return Err(AdminError::Validation(
876            "Collection name is required.".to_owned(),
877        ));
878    }
879    let mut row = crate::media::MediaCollection {
880        id: rustango::sql::Auto::Unset,
881        name: name.clone(),
882        parent_id: form.parent_id,
883        sort_order: form.sort_order.unwrap_or(100),
884        created_at: rustango::sql::Auto::Unset,
885    };
886    row.insert(tenant.pool()).await?;
887    redirect_named_with_message_args(
888        "rcms-admin:media:collections",
889        MsgLevel::Success,
890        "Collection “{name}” created.",
891        &[("name", name.as_str())],
892        &headers,
893    )
894}
895
896/// POST /cms-admin/media/collections/{id}/edit — rename + re-parent
897/// + reorder. The form posts all three fields; missing parent_id
898/// (empty / "0") sends the collection to the root.
899pub async fn collections_edit(
900    State(_state): State<super::AdminState>,
901    tenant: Tenant,
902    headers: HeaderMap,
903    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
904    Path(id): Path<i64>,
905    Form(form): Form<CollectionForm>,
906) -> Result<Response, AdminError> {
907    let mut row = crate::media::MediaCollection::objects()
908        .where_(crate::media::MediaCollection::id.eq(id))
909        .first(tenant.pool())
910        .await?
911        .ok_or(AdminError::NotFound(id))?;
912    let name = form.name.trim().to_owned();
913    if name.is_empty() {
914        return Err(AdminError::Validation(
915            "Collection name is required.".to_owned(),
916        ));
917    }
918    // Guard against parent_id = self (would orphan the row from
919    // the tree walk).
920    if form.parent_id == Some(id) {
921        return Err(AdminError::Validation(
922            "A collection cannot be its own parent.".to_owned(),
923        ));
924    }
925    row.name = name;
926    row.parent_id = form.parent_id;
927    if let Some(so) = form.sort_order {
928        row.sort_order = so;
929    }
930    row.save(tenant.pool()).await?;
931    redirect_named_with_message(
932        "rcms-admin:media:collections",
933        MsgLevel::Success,
934        "Collection saved.",
935        &headers,
936    )
937}
938
939/// POST /cms-admin/media/collections/{id}/delete — soft delete via
940/// re-parent then delete. Child collections are re-parented to the
941/// deleted row's parent; media rows lose their collection_id (FK
942/// nulls).
943pub async fn collections_delete(
944    State(_state): State<super::AdminState>,
945    tenant: Tenant,
946    headers: HeaderMap,
947    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
948    Path(id): Path<i64>,
949) -> Result<Response, AdminError> {
950    let row = crate::media::MediaCollection::objects()
951        .where_(crate::media::MediaCollection::id.eq(id))
952        .first(tenant.pool())
953        .await?
954        .ok_or(AdminError::NotFound(id))?;
955    let parent = row.parent_id;
956    let name = row.name.clone();
957    // Re-parent children so the subtree doesn't dangle.
958    for mut child in crate::media::MediaCollection::objects()
959        .where_(crate::media::MediaCollection::parent_id.eq(Some(id)))
960        .fetch(tenant.pool())
961        .await?
962    {
963        child.parent_id = parent;
964        child.save(tenant.pool()).await?;
965    }
966    // Null out media references — media doesn't get deleted, just
967    // moves to "uncategorized".
968    for mut m in Media::objects()
969        .where_(Media::collection_id.eq(Some(id)))
970        .fetch(tenant.pool())
971        .await?
972    {
973        m.collection_id = None;
974        m.save(tenant.pool()).await?;
975    }
976    row.delete(tenant.pool()).await?;
977    redirect_named_with_message_args(
978        "rcms-admin:media:collections",
979        MsgLevel::Success,
980        "Collection “{name}” deleted. Children re-parented; media moved to Uncategorized.",
981        &[("name", name.as_str())],
982        &headers,
983    )
984}
985
986// ============================================================
987// #557 — Categories / Taxonomies admin
988//
989// One vocabulary registry (`cms_taxonomy`) + a per-vocabulary tree of
990// `cms_category` rows. The category editor renders as a `Vec<Widget>`
991// through the shared `_widget.html` macro — the same engine the page
992// editor uses: base fields (name/slug/description + featured-image /
993// thumbnail MediaPickers + parent Select) plus any extension widgets a
994// custom vocabulary's handler contributes.
995// ============================================================
996
997use crate::category::model::{self as category_model, Category, CategoryError};
998
999/// Flash-redirect back to a vocabulary's category tree.
1000fn category_tree_redirect(
1001    slug: &str,
1002    headers: &HeaderMap,
1003    level: MsgLevel,
1004    key: &str,
1005    args: &[(&str, &str)],
1006) -> Result<Response, AdminError> {
1007    let body = super::i18n::tr(headers, key, args);
1008    let url = format!("/cms-admin/taxonomies/{slug}");
1009    Ok(rustango::messages::redirect_with_message(
1010        messages_secret(),
1011        headers,
1012        level,
1013        &body,
1014        &url,
1015    ))
1016}
1017
1018fn opt_i64_from_form(form: &std::collections::HashMap<String, String>, key: &str) -> Option<i64> {
1019    form.get(key)
1020        .map(|s| s.trim())
1021        .filter(|s| !s.is_empty())
1022        .and_then(|s| s.parse::<i64>().ok())
1023}
1024
1025/// The category editor's base fields as widgets (rendered via
1026/// `_widget.html`, same as page extension fields). `parent_opts` are the
1027/// selectable parents (excludes self on edit).
1028fn category_base_widgets(
1029    cat: Option<&Category>,
1030    parent_opts: Vec<(String, String)>,
1031) -> Vec<crate::widget::Widget> {
1032    use crate::widget::{Widget, WidgetKind};
1033    let mut opts = vec![(String::new(), "— none (top level) —".to_owned())];
1034    opts.extend(parent_opts);
1035    vec![
1036        Widget::new(WidgetKind::Text, "name", "Name")
1037            .required()
1038            .with_value(cat.map(|c| c.name.clone()).unwrap_or_default()),
1039        Widget::new(WidgetKind::Text, "slug", "Slug")
1040            .with_help("URL identifier — auto-generated from the name if left blank.")
1041            .with_value(cat.map(|c| c.slug.clone()).unwrap_or_default()),
1042        Widget::new(WidgetKind::Textarea, "description", "Description")
1043            .with_value(cat.map(|c| c.description.clone()).unwrap_or_default()),
1044        Widget::new(
1045            WidgetKind::MediaPicker,
1046            "featured_image_id",
1047            "Featured image",
1048        )
1049        .with_value(
1050            cat.and_then(|c| c.featured_image_id)
1051                .map(|i| i.to_string())
1052                .unwrap_or_default(),
1053        ),
1054        Widget::new(WidgetKind::MediaPicker, "thumbnail_id", "Thumbnail").with_value(
1055            cat.and_then(|c| c.thumbnail_id)
1056                .map(|i| i.to_string())
1057                .unwrap_or_default(),
1058        ),
1059        Widget::new(WidgetKind::Select, "parent_id", "Parent")
1060            .with_options(opts)
1061            .with_help("Nest this category under another (siblings share a parent).")
1062            .with_value(
1063                cat.and_then(|c| c.parent_id)
1064                    .map(|i| i.to_string())
1065                    .unwrap_or_default(),
1066            ),
1067    ]
1068}
1069
1070/// Build indented `(id, "— — Name")` parent options for a vocabulary,
1071/// optionally excluding `exclude` (and, on edit, its descendants can't be
1072/// picked — the move guard rejects that at save, so we only drop self here).
1073async fn category_parent_options(
1074    pool: &rustango::sql::Pool,
1075    taxonomy_id: i64,
1076    exclude: Option<i64>,
1077) -> Result<Vec<(String, String)>, AdminError> {
1078    let cats = category_model::all_in_taxonomy(pool, taxonomy_id)
1079        .await
1080        .map_err(|e| AdminError::Validation(e.to_string()))?;
1081    Ok(cats
1082        .iter()
1083        .filter(|c| c.id.get().copied() != exclude)
1084        .map(|c| {
1085            let indent = "— ".repeat((c.depth.max(1) - 1) as usize);
1086            (
1087                c.id.get().copied().unwrap_or_default().to_string(),
1088                format!("{indent}{}", c.name),
1089            )
1090        })
1091        .collect())
1092}
1093
1094/// GET /cms-admin/taxonomies — the vocabulary index.
1095pub async fn taxonomies_index(
1096    State(state): State<super::AdminState>,
1097    tenant: Tenant,
1098    headers: HeaderMap,
1099    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
1100) -> Result<Response, AdminError> {
1101    // Not paged: one row per vocabulary a site defines (tags, topics,
1102    // regions…), a handful. Their categories are counted in SQL.
1103    let taxes = crate::category::taxonomies(tenant.pool())
1104        .await
1105        .map_err(|e| AdminError::Validation(e.to_string()))?;
1106    let counts = counts_by(tenant.pool(), Category::objects(), "taxonomy_id").await?;
1107    let rows: Vec<serde_json::Value> = taxes
1108        .iter()
1109        .map(|t| {
1110            serde_json::json!({
1111                "slug": t.slug,
1112                "verbose_name": t.verbose_name,
1113                "icon": if t.icon.is_empty() { "sell".to_owned() } else { t.icon.clone() },
1114                "description": t.description,
1115                "hierarchical": t.hierarchical,
1116                "count": counts.get(&t.id.get().copied().unwrap_or_default()).copied().unwrap_or(0),
1117            })
1118        })
1119        .collect();
1120    let mut ctx = Context::new();
1121    add_chrome(&mut ctx, &tenant, "taxonomies", session_user.as_ref()).await;
1122    add_admin_theme(&mut ctx, tenant.pool()).await;
1123    ctx.insert("taxonomies", &rows);
1124    render_with_csrf(
1125        &state,
1126        &headers,
1127        "rcms_admin/taxonomies_list.html",
1128        &mut ctx,
1129    )
1130}
1131
1132/// GET /cms-admin/taxonomies/{slug} — one vocabulary's category tree.
1133pub async fn category_tree(
1134    State(state): State<super::AdminState>,
1135    tenant: Tenant,
1136    headers: HeaderMap,
1137    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
1138    Path(slug): Path<String>,
1139    Query(paging): Query<crate::admin::pagination::PageQuery>,
1140    axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
1141) -> Result<Response, AdminError> {
1142    let tax = crate::category::find_taxonomy(tenant.pool(), &slug)
1143        .await
1144        .map_err(|e| AdminError::Validation(e.to_string()))?
1145        .ok_or_else(|| AdminError::Validation(format!("unknown taxonomy `{slug}`")))?;
1146    // Paged in `path` order (#629): a vocabulary can grow to hundreds of
1147    // categories. A page may start inside a branch; depth still indents.
1148    let in_tax = || {
1149        Category::objects().where_(Category::taxonomy_id.eq(tax.id.get().copied().unwrap_or_default()))
1150    };
1151    let total = in_tax().count(tenant.pool()).await?;
1152    let window = paging.window(usize::try_from(total).unwrap_or_default());
1153    let cats: Vec<Category> = in_tax()
1154        .order_by(&[("path", false)])
1155        .limit(window.limit)
1156        .offset(window.offset)
1157        .fetch(tenant.pool())
1158        .await?;
1159    let rows: Vec<serde_json::Value> = cats
1160        .iter()
1161        .map(|c| {
1162            serde_json::json!({
1163                "id": c.id.get().copied(),
1164                "name": c.name,
1165                "slug": c.slug,
1166                "description": c.description,
1167                "depth": c.depth,
1168                "thumbnail_id": c.thumbnail_id,
1169                "featured_image_id": c.featured_image_id,
1170            })
1171        })
1172        .collect();
1173    let mut ctx = Context::new();
1174    add_chrome(&mut ctx, &tenant, "taxonomies", session_user.as_ref()).await;
1175    add_admin_theme(&mut ctx, tenant.pool()).await;
1176    ctx.insert("taxonomy_slug", &tax.slug);
1177    ctx.insert("taxonomy_name", &tax.verbose_name);
1178    ctx.insert("categories", &rows);
1179    ctx.insert("pagination", &window.context);
1180    ctx.insert("query_string", &raw_query.unwrap_or_default());
1181    render_with_csrf(&state, &headers, "rcms_admin/category_tree.html", &mut ctx)
1182}
1183
1184/// GET /cms-admin/taxonomies/{slug}/categories/new — create form.
1185pub async fn category_new_form(
1186    State(state): State<super::AdminState>,
1187    tenant: Tenant,
1188    headers: HeaderMap,
1189    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
1190    Path(slug): Path<String>,
1191) -> Result<Response, AdminError> {
1192    let tax = crate::category::find_taxonomy(tenant.pool(), &slug)
1193        .await
1194        .map_err(|e| AdminError::Validation(e.to_string()))?
1195        .ok_or_else(|| AdminError::Validation(format!("unknown taxonomy `{slug}`")))?;
1196    let tid = tax.id.get().copied().unwrap_or_default();
1197    let mut fields = if tax.hierarchical {
1198        category_base_widgets(
1199            None,
1200            category_parent_options(tenant.pool(), tid, None).await?,
1201        )
1202    } else {
1203        // Flat vocabulary — drop the parent picker.
1204        let mut w = category_base_widgets(None, Vec::new());
1205        w.pop();
1206        w
1207    };
1208    // Extension fields are edited after create (they key on the new id).
1209    let _ = &mut fields;
1210    let mut ctx = Context::new();
1211    add_chrome(&mut ctx, &tenant, "taxonomies", session_user.as_ref()).await;
1212    add_admin_theme(&mut ctx, tenant.pool()).await;
1213    ctx.insert("taxonomy_slug", &tax.slug);
1214    ctx.insert("taxonomy_name", &tax.verbose_name);
1215    ctx.insert("mode", "new");
1216    ctx.insert("fields", &fields);
1217    render_with_csrf(&state, &headers, "rcms_admin/category_form.html", &mut ctx)
1218}
1219
1220/// POST /cms-admin/taxonomies/{slug}/categories/new — create.
1221pub async fn category_create(
1222    State(_state): State<super::AdminState>,
1223    tenant: Tenant,
1224    headers: HeaderMap,
1225    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
1226    Path(slug): Path<String>,
1227    Form(form): Form<std::collections::HashMap<String, String>>,
1228) -> Result<Response, AdminError> {
1229    let tax = crate::category::find_taxonomy(tenant.pool(), &slug)
1230        .await
1231        .map_err(|e| AdminError::Validation(e.to_string()))?
1232        .ok_or_else(|| AdminError::Validation(format!("unknown taxonomy `{slug}`")))?;
1233    let tid = tax.id.get().copied().unwrap_or_default();
1234    let new = category_model::NewCategory {
1235        name: form
1236            .get("name")
1237            .cloned()
1238            .unwrap_or_default()
1239            .trim()
1240            .to_owned(),
1241        slug: form.get("slug").cloned().unwrap_or_default(),
1242        description: form.get("description").cloned().unwrap_or_default(),
1243        featured_image_id: opt_i64_from_form(&form, "featured_image_id"),
1244        thumbnail_id: opt_i64_from_form(&form, "thumbnail_id"),
1245        parent_id: opt_i64_from_form(&form, "parent_id"),
1246    };
1247    if new.name.is_empty() {
1248        return category_tree_redirect(
1249            &slug,
1250            &headers,
1251            MsgLevel::Error,
1252            "Category name is required.",
1253            &[],
1254        );
1255    }
1256    match category_model::create(tenant.pool(), tid, new).await {
1257        Ok(cat) => {
1258            let id = cat.id.get().copied().unwrap_or_default();
1259            let body = super::i18n::tr(
1260                &headers,
1261                "Category “{name}” created.",
1262                &[("name", cat.name.as_str())],
1263            );
1264            let url = format!("/cms-admin/taxonomies/{slug}/categories/{id}/edit");
1265            Ok(rustango::messages::redirect_with_message(
1266                messages_secret(),
1267                &headers,
1268                MsgLevel::Success,
1269                &body,
1270                &url,
1271            ))
1272        }
1273        Err(e) => category_tree_redirect(&slug, &headers, MsgLevel::Error, &e.to_string(), &[]),
1274    }
1275}
1276
1277/// GET /cms-admin/taxonomies/{slug}/categories/{id}/edit — edit form.
1278pub async fn category_edit_form(
1279    State(state): State<super::AdminState>,
1280    tenant: Tenant,
1281    headers: HeaderMap,
1282    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
1283    Path((slug, id)): Path<(String, i64)>,
1284    Query(q): Query<EditQuery>,
1285) -> Result<Response, AdminError> {
1286    let tax = crate::category::find_taxonomy(tenant.pool(), &slug)
1287        .await
1288        .map_err(|e| AdminError::Validation(e.to_string()))?
1289        .ok_or_else(|| AdminError::Validation(format!("unknown taxonomy `{slug}`")))?;
1290    let tid = tax.id.get().copied().unwrap_or_default();
1291    let cat = Category::objects()
1292        .where_(Category::id.eq(id))
1293        .where_(Category::taxonomy_id.eq(tid))
1294        .first(tenant.pool())
1295        .await?
1296        .ok_or(AdminError::NotFound(id))?;
1297    let mut fields = if tax.hierarchical {
1298        category_base_widgets(
1299            Some(&cat),
1300            category_parent_options(tenant.pool(), tid, Some(id)).await?,
1301        )
1302    } else {
1303        let mut w = category_base_widgets(Some(&cat), Vec::new());
1304        w.pop();
1305        w
1306    };
1307    // Extension widgets from the vocabulary's handler (custom typed fields).
1308    if let Some(handler) = crate::category::find_handler(&slug) {
1309        if let Ok(ext) = handler.ext_widgets(tenant.pool(), id).await {
1310            fields.extend(ext);
1311        }
1312    }
1313    let mut ctx = Context::new();
1314    add_chrome(&mut ctx, &tenant, "taxonomies", session_user.as_ref()).await;
1315    add_admin_theme(&mut ctx, tenant.pool()).await;
1316    ctx.insert("taxonomy_slug", &tax.slug);
1317    ctx.insert("taxonomy_name", &tax.verbose_name);
1318    ctx.insert("mode", "edit");
1319    ctx.insert("category_id", &id);
1320    ctx.insert("fields", &fields);
1321    // #862 — `?locale=<code>` (a non-default active locale) shows the
1322    // name's translation beside the original, like pages and snippets.
1323    let locales: Vec<crate::locale::Locale> = crate::locale::Locale::objects()
1324        .where_(crate::locale::Locale::active.eq(true))
1325        .order_by(&[("sort_order", false), ("code", false)])
1326        .fetch(tenant.pool())
1327        .await?;
1328    let editing_locale = q
1329        .locale
1330        .as_deref()
1331        .filter(|c| !c.is_empty())
1332        .and_then(|code| locales.iter().find(|l| l.code == code && !l.is_default).cloned());
1333    if let Some(loc) = &editing_locale {
1334        let lid = loc.id.get().copied().unwrap_or_default();
1335        let mut existing = crate::category_translation::fetch_for_categories(tenant.pool(), &[id], lid)
1336            .await
1337            .unwrap_or_default();
1338        ctx.insert("translation_mode", &true);
1339        ctx.insert("editing_locale", loc);
1340        ctx.insert("category_name", &cat.name);
1341        ctx.insert("tr_name", &existing.remove(&id).and_then(|mut f| f.remove("name")).unwrap_or_default());
1342    }
1343    ctx.insert("locales", &locales);
1344    render_with_csrf(&state, &headers, "rcms_admin/category_form.html", &mut ctx)
1345}
1346
1347/// POST /cms-admin/taxonomies/{slug}/categories/{id}/translate?locale=<code>
1348/// — save a category's per-locale name. An empty box deletes the
1349/// row, so the original shows again.
1350pub async fn category_translate_submit(
1351    State(_state): State<super::AdminState>,
1352    tenant: Tenant,
1353    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
1354    Path((slug, id)): Path<(String, i64)>,
1355    Query(q): Query<EditQuery>,
1356    Form(form): Form<std::collections::HashMap<String, String>>,
1357) -> Result<Response, AdminError> {
1358    use crate::category_translation::{CategoryTranslation, TRANSLATABLE_FIELDS};
1359    let code = q
1360        .locale
1361        .as_deref()
1362        .filter(|c| !c.is_empty())
1363        .ok_or_else(|| AdminError::Validation("translate requires ?locale=".to_owned()))?;
1364    let locale = crate::locale::Locale::objects()
1365        .where_(crate::locale::Locale::code.eq(code.to_owned()))
1366        .where_(crate::locale::Locale::active.eq(true))
1367        .where_(crate::locale::Locale::is_default.eq(false))
1368        .first(tenant.pool())
1369        .await?
1370        .ok_or_else(|| AdminError::Validation(format!("unknown locale `{code}`")))?;
1371    let locale_id = locale.id.get().copied().unwrap_or_default();
1372    let tax = crate::category::find_taxonomy(tenant.pool(), &slug)
1373        .await
1374        .map_err(|e| AdminError::Validation(e.to_string()))?
1375        .ok_or_else(|| AdminError::Validation(format!("unknown taxonomy `{slug}`")))?;
1376    Category::objects()
1377        .where_(Category::id.eq(id))
1378        .where_(Category::taxonomy_id.eq(tax.id.get().copied().unwrap_or_default()))
1379        .first(tenant.pool())
1380        .await?
1381        .ok_or(AdminError::NotFound(id))?;
1382    rustango::atomic!(tenant.pool(), |tx| {
1383        let mut guard = tx.lock().await?;
1384        let tx = &mut *guard;
1385        for field in TRANSLATABLE_FIELDS {
1386            let Some(value) = form.get(&format!("tr__{field}")) else {
1387                continue;
1388            };
1389            let value = value.trim().to_owned();
1390            let existing: Vec<CategoryTranslation> = CategoryTranslation::objects()
1391                .where_(CategoryTranslation::category_id.eq(id))
1392                .where_(CategoryTranslation::locale_id.eq(locale_id))
1393                .where_(CategoryTranslation::field_path.eq(field.to_owned()))
1394                .fetch_tx(tx)
1395                .await?;
1396            if value.is_empty() {
1397                for row in existing {
1398                    row.delete_tx(tx).await?;
1399                }
1400            } else if let Some(mut row) = existing.into_iter().next() {
1401                row.value = value;
1402                row.save_tx(tx).await?;
1403            } else {
1404                let mut row = CategoryTranslation {
1405                    id: rustango::sql::Auto::Unset,
1406                    category_id: id,
1407                    locale_id,
1408                    field_path: field.to_owned(),
1409                    value,
1410                    updated_at: rustango::sql::Auto::Unset,
1411                };
1412                row.save_tx(tx).await?;
1413            }
1414        }
1415        Ok::<_, rustango::sql::ExecError>(())
1416    })
1417    .await?;
1418    Ok(Redirect::to(&format!("/cms-admin/taxonomies/{slug}/categories/{id}/edit?locale={code}")).into_response())
1419}
1420
1421/// POST /cms-admin/taxonomies/{slug}/categories/{id}/edit — update.
1422pub async fn category_update(
1423    State(_state): State<super::AdminState>,
1424    tenant: Tenant,
1425    headers: HeaderMap,
1426    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
1427    Path((slug, id)): Path<(String, i64)>,
1428    Form(form): Form<std::collections::HashMap<String, String>>,
1429) -> Result<Response, AdminError> {
1430    let tax = crate::category::find_taxonomy(tenant.pool(), &slug)
1431        .await
1432        .map_err(|e| AdminError::Validation(e.to_string()))?
1433        .ok_or_else(|| AdminError::Validation(format!("unknown taxonomy `{slug}`")))?;
1434    let tid = tax.id.get().copied().unwrap_or_default();
1435    let new = category_model::NewCategory {
1436        name: form
1437            .get("name")
1438            .cloned()
1439            .unwrap_or_default()
1440            .trim()
1441            .to_owned(),
1442        slug: form.get("slug").cloned().unwrap_or_default(),
1443        description: form.get("description").cloned().unwrap_or_default(),
1444        featured_image_id: opt_i64_from_form(&form, "featured_image_id"),
1445        thumbnail_id: opt_i64_from_form(&form, "thumbnail_id"),
1446        parent_id: opt_i64_from_form(&form, "parent_id"),
1447    };
1448    if new.name.is_empty() {
1449        return category_tree_redirect(
1450            &slug,
1451            &headers,
1452            MsgLevel::Error,
1453            "Category name is required.",
1454            &[],
1455        );
1456    }
1457    let new_parent = new.parent_id;
1458    if let Err(e) = category_model::update(tenant.pool(), tid, id, new).await {
1459        return category_tree_redirect(&slug, &headers, MsgLevel::Error, &e.to_string(), &[]);
1460    }
1461    // Re-parent if the parent changed (cycle-guarded inside move_to;
1462    // a no-op when the parent is unchanged).
1463    if let Err(e) = category_model::move_to(tenant.pool(), tid, id, new_parent).await {
1464        return category_tree_redirect(&slug, &headers, MsgLevel::Error, &e.to_string(), &[]);
1465    }
1466    // Extension row (custom vocabularies).
1467    if let Some(handler) = crate::category::find_handler(&slug) {
1468        if let Err(e) = handler.save_ext(tenant.pool(), id, &form).await {
1469            tracing::warn!(category_id = id, error = %e, "category extension save failed");
1470        }
1471    }
1472    category_tree_redirect(&slug, &headers, MsgLevel::Success, "Category saved.", &[])
1473}
1474
1475/// POST /cms-admin/taxonomies/{slug}/categories/{id}/delete.
1476pub async fn category_delete(
1477    State(_state): State<super::AdminState>,
1478    tenant: Tenant,
1479    headers: HeaderMap,
1480    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
1481    Path((slug, id)): Path<(String, i64)>,
1482) -> Result<Response, AdminError> {
1483    let tax = crate::category::find_taxonomy(tenant.pool(), &slug)
1484        .await
1485        .map_err(|e| AdminError::Validation(e.to_string()))?
1486        .ok_or_else(|| AdminError::Validation(format!("unknown taxonomy `{slug}`")))?;
1487    let tid = tax.id.get().copied().unwrap_or_default();
1488    match category_model::delete(tenant.pool(), tid, id, false).await {
1489        Ok(_) => {
1490            category_tree_redirect(&slug, &headers, MsgLevel::Success, "Category deleted.", &[])
1491        }
1492        Err(CategoryError::HasChildren(_, n)) => {
1493            let n = n.to_string();
1494            category_tree_redirect(
1495                &slug,
1496                &headers,
1497                MsgLevel::Error,
1498                "Can't delete a category with {count} child categor(ies) — delete or move them first.",
1499                &[("count", n.as_str())],
1500            )
1501        }
1502        Err(e) => category_tree_redirect(&slug, &headers, MsgLevel::Error, &e.to_string(), &[]),
1503    }
1504}
1505
1506// ============================================================
1507// #559/#562 — Page-type field builder (visual schema constructor)
1508//
1509// A Developer authors a page type's body schema in the builder; save
1510// writes a DRAFT row, publish flips it live (versioned). Gated on the
1511// `cms_page_type.build` codename at the handler level (superuser bypass).
1512// ============================================================
1513
1514/// Deny access to the builder unless the user is a superuser or holds
1515/// `cms_page_type.build`. Returns `Some(redirect)` when denied (anon →
1516/// login, otherwise → no-access), `None` when allowed.
1517async fn ensure_builder_access(
1518    tenant: &Tenant,
1519    user: Option<&rustango::tenancy::auth::User>,
1520) -> Option<Response> {
1521    super::codename_gate(tenant, user, "cms_page_type.build").await
1522}
1523
1524/// GET /cms-admin/page-types/{id}/build — the visual builder.
1525pub async fn page_type_build_form(
1526    State(state): State<super::AdminState>,
1527    tenant: Tenant,
1528    headers: HeaderMap,
1529    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
1530    Path(id): Path<i64>,
1531) -> Result<Response, AdminError> {
1532    if let Some(r) = ensure_builder_access(&tenant, session_user.as_ref()).await {
1533        return Ok(r);
1534    }
1535    let pt = crate::page_type_model::PageType::objects()
1536        .where_(crate::page_type_model::PageType::id.eq(id))
1537        .first(tenant.pool())
1538        .await?
1539        .ok_or(AdminError::NotFound(id))?;
1540
1541    let draft = crate::page_builder::model::draft_for(tenant.pool(), id).await?;
1542    let published = crate::page_builder::model::published_for(tenant.pool(), id).await?;
1543    // Seed the canvas from the draft, else the live published schema,
1544    // else an empty document.
1545    let doc_value = draft
1546        .as_ref()
1547        .map(|d| d.document.clone())
1548        .or_else(|| published.as_ref().map(|p| p.document.clone()))
1549        .unwrap_or_else(|| serde_json::json!({ "nodes": [] }));
1550    let schema_json =
1551        serde_json::to_string(&doc_value).unwrap_or_else(|_| "{\"nodes\":[]}".to_owned());
1552
1553    let components: Vec<serde_json::Value> =
1554        crate::page_builder::model::all_components(tenant.pool())
1555            .await?
1556            .iter()
1557            .map(|c| serde_json::json!({ "slug": c.slug, "label": c.label }))
1558            .collect();
1559    let components_json = serde_json::to_string(&components).unwrap_or_else(|_| "[]".to_owned());
1560    let versions: Vec<serde_json::Value> =
1561        crate::page_builder::model::list_versions(tenant.pool(), id)
1562            .await?
1563            .iter()
1564            .map(|v| {
1565                serde_json::json!({
1566                    "version": v.version,
1567                    "status": v.status,
1568                    "updated_at": v.updated_at.get().copied(),
1569                })
1570            })
1571            .collect();
1572
1573    // #566 — deleting a UI-created type is a danger-zone action on this
1574    // page (not an inline row action). Only for `cms_ui` types, and only
1575    // while no pages use the type.
1576    let is_ui_type = pt.app_label == "cms_ui";
1577    let page_count = if is_ui_type {
1578        // Counted, not loaded. A failed count hides the Delete button
1579        // (the delete itself re-checks and stops on an error).
1580        Page::objects()
1581            .where_(Page::page_type_id.eq(id))
1582            .count(tenant.pool())
1583            .await
1584            .unwrap_or(1)
1585    } else {
1586        0
1587    };
1588
1589    let mut ctx = Context::new();
1590    add_chrome(&mut ctx, &tenant, "page-types", session_user.as_ref()).await;
1591    add_admin_theme(&mut ctx, tenant.pool()).await;
1592    ctx.insert("page_type_id", &id);
1593    ctx.insert("title", &pt.verbose_name);
1594    ctx.insert("schema_json", &schema_json);
1595    ctx.insert("build_url", &format!("/cms-admin/page-types/{id}/build"));
1596    ctx.insert(
1597        "publish_url",
1598        &format!("/cms-admin/page-types/{id}/build/publish"),
1599    );
1600    ctx.insert("delete_url", &format!("/cms-admin/page-types/{id}/delete"));
1601    ctx.insert("list_url", "/cms-admin/page-types");
1602    ctx.insert("components_json", &components_json);
1603    ctx.insert("versions", &versions);
1604    ctx.insert("has_unpublished", &draft.is_some());
1605    // #863 — the Translate menu: other languages, once the schema is live.
1606    let translate_locales: Vec<crate::locale::Locale> = if published.is_some() {
1607        crate::locale::Locale::objects()
1608            .where_(crate::locale::Locale::active.eq(true))
1609            .where_(crate::locale::Locale::is_default.eq(false))
1610            .order_by(&[("sort_order", false), ("code", false)])
1611            .fetch(tenant.pool())
1612            .await?
1613    } else {
1614        Vec::new()
1615    };
1616    ctx.insert("translate_locales", &translate_locales);
1617    ctx.insert("translate_url", &format!("/cms-admin/page-types/{id}/translate"));
1618    ctx.insert("is_ui_type", &is_ui_type);
1619    ctx.insert("page_count", &page_count);
1620    ctx.insert("deletable", &(is_ui_type && page_count == 0));
1621    render_with_csrf(
1622        &state,
1623        &headers,
1624        "rcms_admin/page_type_builder.html",
1625        &mut ctx,
1626    )
1627}
1628
1629/// GET /cms-admin/page-types/{id}/translate?locale=<code> — the labels of
1630/// the type's choice options in another language, side by side
1631/// with the originals like every other translation screen.
1632pub async fn page_type_translate_form(
1633    State(state): State<super::AdminState>,
1634    tenant: Tenant,
1635    headers: HeaderMap,
1636    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
1637    Path(id): Path<i64>,
1638    Query(q): Query<EditQuery>,
1639) -> Result<Response, AdminError> {
1640    if let Some(r) = ensure_builder_access(&tenant, session_user.as_ref()).await {
1641        return Ok(r);
1642    }
1643    let pt = crate::page_type_model::PageType::objects()
1644        .where_(crate::page_type_model::PageType::id.eq(id))
1645        .first(tenant.pool())
1646        .await?
1647        .ok_or(AdminError::NotFound(id))?;
1648    let locale = translate_locale(&tenant, q.locale.as_deref()).await?;
1649    let published = crate::page_builder::model::published_for(tenant.pool(), id).await?;
1650    let fields = published
1651        .as_ref()
1652        .map(|p| crate::page_builder::choice_i18n::choice_fields(&p.document, &locale.code))
1653        .unwrap_or_default();
1654    let mut ctx = Context::new();
1655    add_chrome(&mut ctx, &tenant, "page-types", session_user.as_ref()).await;
1656    add_admin_theme(&mut ctx, tenant.pool()).await;
1657    ctx.insert("title", &pt.verbose_name);
1658    ctx.insert("editing_locale", &locale);
1659    ctx.insert("choice_fields", &fields);
1660    ctx.insert("build_url", &format!("/cms-admin/page-types/{id}/build"));
1661    ctx.insert("translate_url", &format!("/cms-admin/page-types/{id}/translate"));
1662    render_with_csrf(&state, &headers, "rcms_admin/page_type_translate.html", &mut ctx)
1663}
1664
1665/// POST /cms-admin/page-types/{id}/translate?locale=<code> — store the
1666/// option labels (`tr__<field path>__<option value>`) on the published
1667/// schema and on the draft, if one is open, so publishing it keeps them.
1668pub async fn page_type_translate_submit(
1669    State(_state): State<super::AdminState>,
1670    tenant: Tenant,
1671    headers: HeaderMap,
1672    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
1673    Path(id): Path<i64>,
1674    Query(q): Query<EditQuery>,
1675    Form(form): Form<Vec<(String, String)>>,
1676) -> Result<Response, AdminError> {
1677    if let Some(r) = ensure_builder_access(&tenant, session_user.as_ref()).await {
1678        return Ok(r);
1679    }
1680    let locale = translate_locale(&tenant, q.locale.as_deref()).await?;
1681    let labels: std::collections::HashMap<(String, String), String> = form
1682        .into_iter()
1683        .filter_map(|(k, v)| {
1684            let rest = k.strip_prefix("tr__")?;
1685            let (path, value) = rest.split_once("__")?;
1686            Some(((path.to_owned(), value.to_owned()), v))
1687        })
1688        .collect();
1689    for row in [
1690        crate::page_builder::model::published_for(tenant.pool(), id).await?,
1691        crate::page_builder::model::draft_for(tenant.pool(), id).await?,
1692    ]
1693    .into_iter()
1694    .flatten()
1695    {
1696        let mut row = row;
1697        if crate::page_builder::choice_i18n::set_choice_labels(&mut row.document, &locale.code, &labels) > 0 {
1698            row.save(tenant.pool()).await?;
1699        }
1700    }
1701    let back = format!("/cms-admin/page-types/{id}/translate?locale={}", locale.code);
1702    Ok(rustango::messages::redirect_with_message(
1703        messages_secret(),
1704        &headers,
1705        MsgLevel::Success,
1706        &super::i18n::tr(&headers, "Translations saved.", &[]),
1707        &back,
1708    ))
1709}
1710
1711/// The active, non-default locale named by `?locale=`, for the
1712/// translation screens.
1713async fn translate_locale(tenant: &Tenant, code: Option<&str>) -> Result<crate::locale::Locale, AdminError> {
1714    let code = code
1715        .filter(|c| !c.is_empty())
1716        .ok_or_else(|| AdminError::Validation("translate requires ?locale=".to_owned()))?;
1717    crate::locale::Locale::objects()
1718        .where_(crate::locale::Locale::code.eq(code.to_owned()))
1719        .where_(crate::locale::Locale::active.eq(true))
1720        .where_(crate::locale::Locale::is_default.eq(false))
1721        .first(tenant.pool())
1722        .await?
1723        .ok_or_else(|| AdminError::Validation(format!("unknown locale `{code}`")))
1724}
1725
1726/// Shared body for save/publish: gate, load the page type, parse +
1727/// validate the posted schema. Returns the validated document + the
1728/// problem list, or an early access/redirect / not-found response.
1729async fn parse_builder_submit(
1730    tenant: &Tenant,
1731    user: Option<&rustango::tenancy::auth::User>,
1732    id: i64,
1733    schema_str: &str,
1734) -> Result<Result<(crate::page_builder::Document, Vec<String>), Response>, AdminError> {
1735    if let Some(r) = ensure_builder_access(tenant, user).await {
1736        return Ok(Err(r));
1737    }
1738    // Ensure the page type exists.
1739    let exists = crate::page_type_model::PageType::objects()
1740        .where_(crate::page_type_model::PageType::id.eq(id))
1741        .first(tenant.pool())
1742        .await?
1743        .is_some();
1744    if !exists {
1745        return Err(AdminError::NotFound(id));
1746    }
1747    let value: serde_json::Value = serde_json::from_str(schema_str)
1748        .map_err(|e| AdminError::Validation(format!("invalid schema JSON: {e}")))?;
1749    let doc = crate::page_builder::parse_schema(&value)
1750        .map_err(|e| AdminError::Validation(format!("invalid schema document: {e}")))?;
1751    let components = crate::page_builder::model::component_map(tenant.pool()).await?;
1752    let problems = crate::page_builder::validate_schema(&doc, &components);
1753    Ok(Ok((doc, problems)))
1754}
1755
1756/// POST /cms-admin/page-types/{id}/build — save the schema as a draft.
1757/// Warnings are non-blocking (surfaced in the flash).
1758pub async fn page_type_build_submit(
1759    State(_state): State<super::AdminState>,
1760    tenant: Tenant,
1761    headers: HeaderMap,
1762    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
1763    Path(id): Path<i64>,
1764    Form(form): Form<FormBuildSubmit>,
1765) -> Result<Response, AdminError> {
1766    let (doc, problems) =
1767        match parse_builder_submit(&tenant, session_user.as_ref(), id, &form.schema).await? {
1768            Ok(v) => v,
1769            Err(resp) => return Ok(resp),
1770        };
1771    let document =
1772        serde_json::to_value(&doc).unwrap_or_else(|_| serde_json::json!({ "nodes": [] }));
1773    let created_by = session_user.as_ref().and_then(|u| u.id.get().copied());
1774    crate::page_builder::model::save_draft(tenant.pool(), id, document, created_by).await?;
1775    let (level, msg) = if problems.is_empty() {
1776        (MsgLevel::Success, "Draft saved.".to_owned())
1777    } else {
1778        (
1779            MsgLevel::Warning,
1780            format!("Draft saved with warnings: {}", problems.join(" ")),
1781        )
1782    };
1783    redirect_named_with_params_and_message(
1784        "rcms-admin:page-types:build",
1785        &[("id", id.to_string())],
1786        level,
1787        &msg,
1788        &headers,
1789    )
1790}
1791
1792/// POST /cms-admin/page-types/{id}/build/publish — validate + publish the
1793/// schema. Validation errors block the publish (draft is still saved).
1794pub async fn page_type_publish_submit(
1795    State(_state): State<super::AdminState>,
1796    tenant: Tenant,
1797    headers: HeaderMap,
1798    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
1799    Path(id): Path<i64>,
1800    Form(form): Form<FormBuildSubmit>,
1801) -> Result<Response, AdminError> {
1802    let (doc, problems) =
1803        match parse_builder_submit(&tenant, session_user.as_ref(), id, &form.schema).await? {
1804            Ok(v) => v,
1805            Err(resp) => return Ok(resp),
1806        };
1807    // Persist what's on screen as the draft first, so a blocked publish
1808    // still saves the editor's work.
1809    let document =
1810        serde_json::to_value(&doc).unwrap_or_else(|_| serde_json::json!({ "nodes": [] }));
1811    let created_by = session_user.as_ref().and_then(|u| u.id.get().copied());
1812    crate::page_builder::model::save_draft(tenant.pool(), id, document, created_by).await?;
1813    if !problems.is_empty() {
1814        return redirect_named_with_params_and_message(
1815            "rcms-admin:page-types:build",
1816            &[("id", id.to_string())],
1817            MsgLevel::Error,
1818            &format!("Can't publish — fix these first: {}", problems.join(" ")),
1819            &headers,
1820        );
1821    }
1822    crate::page_builder::model::publish(tenant.pool(), id).await?;
1823    redirect_named_with_params_and_message(
1824        "rcms-admin:page-types:build",
1825        &[("id", id.to_string())],
1826        MsgLevel::Success,
1827        "Schema published — the page editor now uses this structure.",
1828        &headers,
1829    )
1830}
1831
1832/// Persist a page's page-builder body values from a posted form, when
1833/// its page type has a published schema. Additive to any code
1834/// handler's `save_extension` — runs regardless of whether a handler
1835/// exists.
1836///
1837/// # Errors
1838/// A failed schema/component lookup or value write. A type with no
1839/// published schema, or one that no longer parses, has nothing to save.
1840pub(crate) async fn save_page_builder_values(
1841    pool: &rustango::sql::Pool,
1842    page_type_id: i64,
1843    page_id: i64,
1844    form_map: &std::collections::HashMap<String, String>,
1845) -> Result<(), rustango::sql::ExecError> {
1846    let Some(row) = crate::page_builder::model::published_for(pool, page_type_id).await? else {
1847        return Ok(());
1848    };
1849    let Ok(doc) = crate::page_builder::parse_schema(&row.document) else {
1850        return Ok(());
1851    };
1852    let components = crate::page_builder::model::component_map(pool).await?;
1853    let compiled = crate::page_builder::compile(&doc, &components, row.version.max(1) as u32);
1854    crate::page_builder::values::save_from_form(pool, page_id, &compiled, form_map).await
1855}
1856
1857/// Save a page's type-specific content from a posted page form: the
1858/// handler's extension row and inline panels, then the page-builder
1859/// body values. Shared by the new-page and edit submits.
1860async fn save_type_content(
1861    pool: &rustango::sql::Pool,
1862    page_type: Option<&PageType>,
1863    page_type_id: i64,
1864    page_id: i64,
1865    form_map: &std::collections::HashMap<String, String>,
1866) -> Result<(), AdminError> {
1867    if let Some(handler) = page_type.and_then(|pt| find_handler(&pt.type_name)) {
1868        let ext_form = sanitized_extension_form(handler.as_ref(), pool, page_id, form_map).await;
1869        handler.save_extension(pool, page_id, &ext_form).await?;
1870        // #117 — inline panels. Reassemble row dicts from the
1871        // posted `inline__<panel>__<idx>__<field>` keys and hand
1872        // them to the handler. Handler is responsible for the
1873        // upsert / delete-removed semantics.
1874        for spec in handler.inline_panels(pool, page_id).await? {
1875            if spec.per_row {
1876                // Per-row panels save card by card, never with the page.
1877                continue;
1878            }
1879            let rows = extract_inline_panel_rows(form_map, &spec);
1880            handler.save_inline_panel(pool, page_id, &spec.name, &rows).await?;
1881        }
1882    }
1883    // #564 — page-builder body values (additive to any code handler).
1884    save_page_builder_values(pool, page_type_id, page_id, form_map).await?;
1885    Ok(())
1886}
1887
1888/// #146 — reindex the reference graph from the just-saved form
1889/// values. The (cheap, in-memory) scan stays here where the form is
1890/// in hand; #432 moves the (DB-write) reindex onto the task queue
1891/// via `reindex_page` — dispatched + retried when a sink is
1892/// installed, inline otherwise. Best-effort either way.
1893async fn reindex_from_form(
1894    pool: &rustango::sql::Pool,
1895    org_slug: &str,
1896    page_id: i64,
1897    form_map: &std::collections::HashMap<String, String>,
1898) {
1899    let mut refs: Vec<crate::reference_index::Reference> = Vec::new();
1900    for (key, value) in form_map {
1901        // Scan every form field for /__media__/... + page/snippet
1902        // links. Field-scoped so the index records which input
1903        // produced each reference.
1904        let mut found = crate::reference_index::scan(value, key);
1905        refs.append(&mut found);
1906    }
1907    crate::task_queue::reindex_page(pool, org_slug, page_id, refs).await;
1908}
1909
1910/// The page type's own editor fields — the handler's widgets (custom and
1911/// stream widgets pre-rendered), the page-builder body and the inline
1912/// panels — into `ctx`. `page_id` 0 is a page not created yet: every
1913/// field shows its default. `held` is a change held for review, shown in
1914/// place of the stored values.
1915#[allow(clippy::too_many_arguments)]
1916async fn insert_type_fields(
1917    ctx: &mut Context,
1918    tera: &tera::Tera,
1919    pool: &rustango::sql::Pool,
1920    handler: Option<&dyn crate::page_type::PageTypeHandler>,
1921    mut widgets: Vec<crate::widget::Widget>,
1922    page_id: i64,
1923    page_type_id: i64,
1924    held: Option<&std::collections::HashMap<String, String>>,
1925) {
1926    if let Some(form) = held {
1927        overlay_pending_widgets(&mut widgets, form);
1928    }
1929    // Pre-render `Custom`-kind widgets via the inventory registry.
1930    // Tera's `{% include %}` requires a string literal, so we
1931    // render once on the Rust side and stash the result on each
1932    // widget — same shape `cms_snippet` uses for its
1933    // pre-fetched-snippet HTML map.
1934    for w in &mut widgets {
1935        if matches!(w.kind, crate::widget::WidgetKind::Custom) {
1936            if let Some(reg) = crate::widget::registry::find_custom_widget(&w.custom_name) {
1937                let mut sub = Context::new();
1938                sub.insert("w", &w);
1939                w.custom_html = tera.render(reg.template, &sub).unwrap_or_else(|e| {
1940                    tracing::warn!(
1941                        target: "rustango_cms::widget",
1942                        custom_name = %w.custom_name,
1943                        template = reg.template,
1944                        error = %e,
1945                        "custom widget template render failed",
1946                    );
1947                    String::new()
1948                });
1949            }
1950        }
1951    }
1952
1953    // -- StreamField pre-render --------------------------------------
1954    // Walk each `Widget::Stream` once: parse its stored JSON, render
1955    // every contained block's editor markup + `<template>` clones
1956    // for each allowed type. The output lives on `w.custom_html`
1957    // (same stash slot the Custom widget arm uses); the `_widget.html`
1958    // macro emits it `| safe` for the stream arm.
1959    for w in &mut widgets {
1960        if matches!(w.kind, crate::widget::WidgetKind::Stream) {
1961            w.custom_html = crate::block::admin::render_stream_editor(w, tera);
1962        }
1963    }
1964    ctx.insert("extension_fields", &widgets);
1965
1966    // #564 — page-builder body. When the page type has a published
1967    // schema, pre-render its fixed fields/rows/groups + repeater/flex
1968    // stream editors (prefilled + lazily upgraded) into one HTML blob the
1969    // Body fieldset emits, plus a conditional-rules island.
1970    if let Some((body_html, rules_json, upgraded)) =
1971        page_builder_editor_ctx(pool, tera, page_id, page_type_id, held).await
1972    {
1973        ctx.insert("builder_body_html", &body_html);
1974        ctx.insert("builder_rules_json", &rules_json);
1975        ctx.insert("builder_upgraded", &upgraded);
1976    }
1977
1978    // #117 — inline panels. Collect each spec the handler declared
1979    // and the persisted rows behind it. Each panel renders as a
1980    // section with N rows; per-row fields come from the spec.
1981    let mut inline_panels: Vec<serde_json::Value> = Vec::new();
1982    if let Some(h) = handler {
1983        for spec in h.inline_panels(pool, page_id).await.unwrap_or_default() {
1984            if spec.per_row {
1985                // Titles only: each card's fields load when it is opened.
1986                let rows = if page_id > 0 { h.inline_rows(pool, page_id, &spec.name).await.unwrap_or_default() } else { Vec::new() };
1987                inline_panels.push(inline_panel_lazy_ctx(&spec, &rows, page_id));
1988                continue;
1989            }
1990            let rows = h
1991                .load_inline_panel(pool, page_id, &spec.name)
1992                .await
1993                .unwrap_or_default();
1994            inline_panels.push(inline_panel_ctx(&spec, &rows));
1995        }
1996    }
1997    // Panels that asked for a tab of their own, one tab per label, in
1998    // the order the panels were declared.
1999    let mut inline_tabs: Vec<serde_json::Value> = Vec::new();
2000    for p in &inline_panels {
2001        let Some(slug) = p["tab_slug"].as_str() else { continue };
2002        if !inline_tabs.iter().any(|t| t["slug"] == slug) {
2003            inline_tabs.push(serde_json::json!({
2004                "slug": slug,
2005                "label": p["spec"]["tab"],
2006                "icon": p["spec"]["icon"],
2007            }));
2008        }
2009    }
2010    ctx.insert("inline_panels", &inline_panels);
2011    ctx.insert("inline_tabs", &inline_tabs);
2012}
2013
2014/// GET-side: build the editor HTML + rules island + upgrade flag for a
2015/// page whose type has a published schema. Returns `None` when
2016/// the type has no published schema.
2017async fn page_builder_editor_ctx(
2018    pool: &rustango::sql::Pool,
2019    tera: &tera::Tera,
2020    page_id: i64,
2021    page_type_id: i64,
2022    held: Option<&std::collections::HashMap<String, String>>,
2023) -> Option<(String, String, bool)> {
2024    let row = crate::page_builder::model::published_for(pool, page_type_id)
2025        .await
2026        .ok()??;
2027    let doc = crate::page_builder::parse_schema(&row.document).ok()?;
2028    let components = crate::page_builder::model::component_map(pool)
2029        .await
2030        .unwrap_or_default();
2031    let compiled = crate::page_builder::compile(&doc, &components, row.version.max(1) as u32);
2032    let (mut values, report) =
2033        crate::page_builder::values::load_upgraded(pool, page_id, &compiled)
2034            .await
2035            .unwrap_or_else(|_| (serde_json::json!({}), Default::default()));
2036    // A change held for review shows in place of the stored values.
2037    if let Some(form) = held {
2038        values = serde_json::Value::Object(crate::page_builder::values::build_values(&compiled, form));
2039    }
2040    let html =
2041        crate::page_builder::values::render_body(&compiled, &values, tera);
2042    // Conditional-rules island: `[{field, rule}]` for page_builder_rules.js.
2043    let rules: Vec<serde_json::Value> = compiled
2044        .rules
2045        .iter()
2046        .map(|r| serde_json::json!({ "field": r.field, "rule": r.rule }))
2047        .collect();
2048    let rules_json = serde_json::to_string(&rules).unwrap_or_else(|_| "[]".to_owned());
2049    Some((html, rules_json, report.upgraded))
2050}
2051
2052// ---- #563 reusable components library -----------------------------------
2053
2054/// GET /cms-admin/components — the library list (Developer-gated).
2055pub async fn components_index(
2056    State(state): State<super::AdminState>,
2057    tenant: Tenant,
2058    headers: HeaderMap,
2059    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
2060) -> Result<Response, AdminError> {
2061    if let Some(r) = ensure_builder_access(&tenant, session_user.as_ref()).await {
2062        return Ok(r);
2063    }
2064    // Not paged: one row per component a developer defined. The page-type
2065    // schemas are scanned once for every component's references, not
2066    // once per component.
2067    let comps = crate::page_builder::model::all_components(tenant.pool()).await?;
2068    let slugs: Vec<&str> = comps.iter().map(|c| c.slug.as_str()).collect();
2069    let ref_counts = crate::page_builder::model::component_reference_counts(tenant.pool(), &slugs)
2070        .await
2071        .unwrap_or_default();
2072    let mut rows = Vec::with_capacity(comps.len());
2073    for c in &comps {
2074        rows.push(serde_json::json!({
2075            "id": c.id.get().copied(),
2076            "slug": c.slug,
2077            "label": c.label,
2078            "icon": if c.icon.is_empty() { "extension".to_owned() } else { c.icon.clone() },
2079            "description": c.description,
2080            "version": c.version,
2081            "ref_count": ref_counts.get(c.slug.as_str()).copied().unwrap_or(0),
2082        }));
2083    }
2084    let mut ctx = Context::new();
2085    add_chrome(&mut ctx, &tenant, "components", session_user.as_ref()).await;
2086    add_admin_theme(&mut ctx, tenant.pool()).await;
2087    ctx.insert("components", &rows);
2088    ctx.insert("new_url", "/cms-admin/components/new");
2089    render_with_csrf(
2090        &state,
2091        &headers,
2092        "rcms_admin/components_list.html",
2093        &mut ctx,
2094    )
2095}
2096
2097/// Shared render of the component builder shell (new + edit + error re-render).
2098#[allow(clippy::too_many_arguments)]
2099async fn render_component_builder(
2100    state: &super::AdminState,
2101    headers: &HeaderMap,
2102    tenant: &Tenant,
2103    user: Option<&rustango::tenancy::auth::User>,
2104    id: Option<i64>,
2105    slug: &str,
2106    label: &str,
2107    icon: &str,
2108    description: &str,
2109    schema_json: &str,
2110    error: Option<&str>,
2111) -> Result<Response, AdminError> {
2112    let mut ctx = Context::new();
2113    add_chrome(&mut ctx, tenant, "components", user).await;
2114    add_admin_theme(&mut ctx, tenant.pool()).await;
2115    ctx.insert("component_id", &id);
2116    ctx.insert("slug", slug);
2117    ctx.insert("label", label);
2118    ctx.insert("icon", icon);
2119    ctx.insert("description", description);
2120    ctx.insert("schema_json", schema_json);
2121    ctx.insert("is_edit", &id.is_some());
2122    let save_url = match id {
2123        Some(cid) => format!("/cms-admin/components/{cid}/edit"),
2124        None => "/cms-admin/components/new".to_owned(),
2125    };
2126    ctx.insert("save_url", &save_url);
2127    ctx.insert("list_url", "/cms-admin/components");
2128    if let Some(e) = error {
2129        ctx.insert("error", e);
2130    }
2131    render_with_csrf(
2132        state,
2133        headers,
2134        "rcms_admin/component_builder.html",
2135        &mut ctx,
2136    )
2137}
2138
2139/// GET /cms-admin/components/new — empty component builder (fields + rows).
2140pub async fn component_new_form(
2141    State(state): State<super::AdminState>,
2142    tenant: Tenant,
2143    headers: HeaderMap,
2144    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
2145) -> Result<Response, AdminError> {
2146    if let Some(r) = ensure_builder_access(&tenant, session_user.as_ref()).await {
2147        return Ok(r);
2148    }
2149    render_component_builder(
2150        &state,
2151        &headers,
2152        &tenant,
2153        session_user.as_ref(),
2154        None,
2155        "",
2156        "",
2157        "",
2158        "",
2159        "{\"nodes\":[]}",
2160        None,
2161    )
2162    .await
2163}
2164
2165/// GET /cms-admin/components/{id}/edit — builder seeded from the stored doc.
2166pub async fn component_edit_form(
2167    State(state): State<super::AdminState>,
2168    tenant: Tenant,
2169    headers: HeaderMap,
2170    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
2171    Path(id): Path<i64>,
2172) -> Result<Response, AdminError> {
2173    if let Some(r) = ensure_builder_access(&tenant, session_user.as_ref()).await {
2174        return Ok(r);
2175    }
2176    let c = crate::page_builder::model::component_by_id(tenant.pool(), id)
2177        .await?
2178        .ok_or(AdminError::NotFound(id))?;
2179    // The builder JS reads `{nodes:[…]}`; a component doc stores `children`.
2180    let doc: crate::page_builder::schema::ComponentDoc =
2181        serde_json::from_value(c.document.clone()).unwrap_or_default();
2182    let schema_json =
2183        serde_json::to_string(&serde_json::json!({ "nodes": doc.children })).unwrap_or_default();
2184    render_component_builder(
2185        &state,
2186        &headers,
2187        &tenant,
2188        session_user.as_ref(),
2189        Some(id),
2190        &c.slug,
2191        &c.label,
2192        &c.icon,
2193        &c.description,
2194        &schema_json,
2195        None,
2196    )
2197    .await
2198}
2199
2200/// Parse the posted `{nodes:[…]}` into a validated [`ComponentDoc`].
2201/// `Ok(doc)` on success; `Err(problems)` with the editor-facing errors.
2202fn parse_component_doc(
2203    schema_str: &str,
2204) -> Result<crate::page_builder::schema::ComponentDoc, String> {
2205    let value: serde_json::Value =
2206        serde_json::from_str(schema_str).map_err(|e| format!("invalid schema JSON: {e}"))?;
2207    let doc = crate::page_builder::parse_schema(&value)
2208        .map_err(|e| format!("invalid schema document: {e}"))?;
2209    let cdoc = crate::page_builder::schema::ComponentDoc {
2210        label_format: None,
2211        children: doc.nodes,
2212    };
2213    let problems = crate::page_builder::schema::validate_component(&cdoc);
2214    if problems.is_empty() {
2215        Ok(cdoc)
2216    } else {
2217        Err(problems.join(" "))
2218    }
2219}
2220
2221/// POST /cms-admin/components/new — create a component (version 1).
2222pub async fn component_create(
2223    State(state): State<super::AdminState>,
2224    tenant: Tenant,
2225    headers: HeaderMap,
2226    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
2227    Form(form): Form<FormComponentSubmit>,
2228) -> Result<Response, AdminError> {
2229    if let Some(r) = ensure_builder_access(&tenant, session_user.as_ref()).await {
2230        return Ok(r);
2231    }
2232    let slug = crate::forms::schema::slugify_key(&form.slug);
2233    // Validate slug → label → document, in order; first failure wins.
2234    let checked: Result<crate::page_builder::schema::ComponentDoc, String> =
2235        if !crate::forms::schema::is_valid_key(&slug) {
2236            Err(
2237                "Slug is invalid — use letters/digits/underscores, starting with a letter."
2238                    .to_owned(),
2239            )
2240        } else if form.label.trim().is_empty() {
2241            Err("Label is required.".to_owned())
2242        } else {
2243            parse_component_doc(&form.schema)
2244        };
2245    // On success, create; a unique-slug clash re-shows with a clear error.
2246    let msg: Option<String> = match checked {
2247        Ok(cdoc) => {
2248            let document = serde_json::to_value(&cdoc).unwrap_or_else(|_| serde_json::json!({}));
2249            match crate::page_builder::model::create_component(
2250                tenant.pool(),
2251                &slug,
2252                form.label.trim(),
2253                form.icon.trim(),
2254                form.description.trim(),
2255                document,
2256            )
2257            .await
2258            {
2259                Ok(_) => {
2260                    return redirect_named_with_message(
2261                        "rcms-admin:components:index",
2262                        MsgLevel::Success,
2263                        "Component created.",
2264                        &headers,
2265                    )
2266                }
2267                Err(_) => Some(format!(
2268                    "Could not create — a component with slug `{slug}` may already exist."
2269                )),
2270            }
2271        }
2272        Err(e) => Some(e),
2273    };
2274    render_component_builder(
2275        &state,
2276        &headers,
2277        &tenant,
2278        session_user.as_ref(),
2279        None,
2280        &form.slug,
2281        &form.label,
2282        &form.icon,
2283        &form.description,
2284        &form.schema,
2285        msg.as_deref(),
2286    )
2287    .await
2288}
2289
2290/// POST /cms-admin/components/{id}/edit — update + bump version.
2291pub async fn component_update(
2292    State(state): State<super::AdminState>,
2293    tenant: Tenant,
2294    headers: HeaderMap,
2295    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
2296    Path(id): Path<i64>,
2297    Form(form): Form<FormComponentSubmit>,
2298) -> Result<Response, AdminError> {
2299    if let Some(r) = ensure_builder_access(&tenant, session_user.as_ref()).await {
2300        return Ok(r);
2301    }
2302    let existing = crate::page_builder::model::component_by_id(tenant.pool(), id)
2303        .await?
2304        .ok_or(AdminError::NotFound(id))?;
2305    if form.label.trim().is_empty() {
2306        return render_component_builder(
2307            &state,
2308            &headers,
2309            &tenant,
2310            session_user.as_ref(),
2311            Some(id),
2312            &existing.slug,
2313            &form.label,
2314            &form.icon,
2315            &form.description,
2316            &form.schema,
2317            Some("Label is required."),
2318        )
2319        .await;
2320    }
2321    let cdoc = match parse_component_doc(&form.schema) {
2322        Ok(d) => d,
2323        Err(e) => {
2324            return render_component_builder(
2325                &state,
2326                &headers,
2327                &tenant,
2328                session_user.as_ref(),
2329                Some(id),
2330                &existing.slug,
2331                &form.label,
2332                &form.icon,
2333                &form.description,
2334                &form.schema,
2335                Some(&e),
2336            )
2337            .await
2338        }
2339    };
2340    let document = serde_json::to_value(&cdoc).unwrap_or_else(|_| serde_json::json!({}));
2341    crate::page_builder::model::update_component(
2342        tenant.pool(),
2343        id,
2344        form.label.trim(),
2345        form.icon.trim(),
2346        form.description.trim(),
2347        document,
2348    )
2349    .await?;
2350    redirect_named_with_message(
2351        "rcms-admin:components:index",
2352        MsgLevel::Success,
2353        "Component saved — referencing page types pick it up on next open.",
2354        &headers,
2355    )
2356}
2357
2358/// POST /cms-admin/components/{id}/delete — blocked while referenced.
2359pub async fn component_delete(
2360    State(_state): State<super::AdminState>,
2361    tenant: Tenant,
2362    headers: HeaderMap,
2363    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
2364    Path(id): Path<i64>,
2365) -> Result<Response, AdminError> {
2366    if let Some(r) = ensure_builder_access(&tenant, session_user.as_ref()).await {
2367        return Ok(r);
2368    }
2369    let c = crate::page_builder::model::component_by_id(tenant.pool(), id)
2370        .await?
2371        .ok_or(AdminError::NotFound(id))?;
2372    let refs = crate::page_builder::model::component_references(tenant.pool(), &c.slug).await?;
2373    if !refs.is_empty() {
2374        // Resolve referencing page-type names for a clear error.
2375        let ids: Vec<i64> = refs.iter().map(|(pt, _)| *pt).collect();
2376        let pts: Vec<PageType> = PageType::objects()
2377            .where_(PageType::id.is_in(ids))
2378            .fetch(tenant.pool())
2379            .await
2380            .unwrap_or_default();
2381        let names: Vec<String> = pts.iter().map(|p| p.verbose_name.clone()).collect();
2382        let listed = if names.is_empty() {
2383            format!("{} page type(s)", refs.len())
2384        } else {
2385            names.join(", ")
2386        };
2387        return redirect_named_with_message(
2388            "rcms-admin:components:index",
2389            MsgLevel::Error,
2390            &format!("Can't delete `{}` — still used by: {listed}.", c.slug),
2391            &headers,
2392        );
2393    }
2394    crate::page_builder::model::delete_component(tenant.pool(), id).await?;
2395    redirect_named_with_message(
2396        "rcms-admin:components:index",
2397        MsgLevel::Success,
2398        "Component deleted.",
2399        &headers,
2400    )
2401}
2402
2403// ---- #566 UI-created page types -----------------------------------------
2404
2405/// GET /cms-admin/page-types/new — the create-a-type form.
2406pub async fn page_type_new_form(
2407    State(state): State<super::AdminState>,
2408    tenant: Tenant,
2409    headers: HeaderMap,
2410    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
2411) -> Result<Response, AdminError> {
2412    if let Some(r) = ensure_builder_access(&tenant, session_user.as_ref()).await {
2413        return Ok(r);
2414    }
2415    let mut ctx = Context::new();
2416    add_chrome(&mut ctx, &tenant, "page-types", session_user.as_ref()).await;
2417    add_admin_theme(&mut ctx, tenant.pool()).await;
2418    ctx.insert("list_url", "/cms-admin/page-types");
2419    insert_workflow_choices(&mut ctx, tenant.pool()).await;
2420    render_with_csrf(&state, &headers, "rcms_admin/page_type_form.html", &mut ctx)
2421}
2422
2423/// The active workflows, by name, for the page-type form's Workflow field.
2424/// A failed lookup leaves only "publish directly".
2425async fn insert_workflow_choices(ctx: &mut Context, pool: &rustango::sql::Pool) {
2426    let names: Vec<String> = crate::workflow::Workflow::objects()
2427        .where_(crate::workflow::Workflow::active.eq(true))
2428        .order_by(&[("name", false)])
2429        .fetch(pool)
2430        .await
2431        .unwrap_or_default()
2432        .into_iter()
2433        .map(|w| w.name)
2434        .collect();
2435    ctx.insert("workflows", &names);
2436}
2437
2438/// A comma-separated list of type identifiers as the JSON array a page-type
2439/// row stores (empty = no rule).
2440fn type_list_json(raw: &str) -> serde_json::Value {
2441    serde_json::Value::Array(
2442        raw.split(',')
2443            .map(str::trim)
2444            .filter(|s| !s.is_empty())
2445            .map(|s| serde_json::Value::String(s.to_owned()))
2446            .collect(),
2447    )
2448}
2449
2450/// An admin-made page type by id; `None` for a missing or code type, whose
2451/// settings are re-seeded from its handler at every boot.
2452async fn ui_page_type(
2453    pool: &rustango::sql::Pool,
2454    id: i64,
2455) -> Result<Option<crate::page_type_model::PageType>, AdminError> {
2456    Ok(crate::page_type_model::PageType::objects()
2457        .where_(crate::page_type_model::PageType::id.eq(id))
2458        .first(pool)
2459        .await?
2460        .filter(|t| crate::page_type::find_handler(&t.type_name).is_none()))
2461}
2462
2463/// GET /cms-admin/page-types/{id}/edit — an admin-made type's settings.
2464pub async fn page_type_edit_form(
2465    State(state): State<super::AdminState>,
2466    tenant: Tenant,
2467    headers: HeaderMap,
2468    Path(id): Path<i64>,
2469    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
2470) -> Result<Response, AdminError> {
2471    if let Some(r) = ensure_builder_access(&tenant, session_user.as_ref()).await {
2472        return Ok(r);
2473    }
2474    let Some(pt) = ui_page_type(tenant.pool(), id).await? else {
2475        return Err(AdminError::NotFound(id));
2476    };
2477    let mut ctx = Context::new();
2478    add_chrome(&mut ctx, &tenant, "page-types", session_user.as_ref()).await;
2479    add_admin_theme(&mut ctx, tenant.pool()).await;
2480    ctx.insert("list_url", "/cms-admin/page-types");
2481    ctx.insert("edit_id", &id);
2482    ctx.insert("form_verbose_name", &pt.verbose_name);
2483    ctx.insert("form_type_name", &pt.type_name);
2484    ctx.insert("form_allowed_parents", &pt.allowed_parents().join(", "));
2485    ctx.insert("form_allowed_children", &pt.allowed_children().join(", "));
2486    ctx.insert("form_workflow", &pt.workflow);
2487    insert_workflow_choices(&mut ctx, tenant.pool()).await;
2488    render_with_csrf(&state, &headers, "rcms_admin/page_type_form.html", &mut ctx)
2489}
2490
2491/// POST /cms-admin/page-types/{id}/edit — save an admin-made type's name,
2492/// parent/child rules and workflow. The identifier can't change.
2493pub async fn page_type_update(
2494    tenant: Tenant,
2495    headers: HeaderMap,
2496    Path(id): Path<i64>,
2497    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
2498    Form(form): Form<FormPageTypeCreate>,
2499) -> Result<Response, AdminError> {
2500    if let Some(r) = ensure_builder_access(&tenant, session_user.as_ref()).await {
2501        return Ok(r);
2502    }
2503    let Some(mut pt) = ui_page_type(tenant.pool(), id).await? else {
2504        return Err(AdminError::NotFound(id));
2505    };
2506    if form.verbose_name.trim().is_empty() {
2507        return Err(AdminError::Validation("Name is required.".to_owned()));
2508    }
2509    pt.verbose_name = form.verbose_name.trim().to_owned();
2510    pt.allowed_parent_types = type_list_json(&form.allowed_parents);
2511    pt.allowed_child_types = type_list_json(&form.allowed_children);
2512    pt.workflow = form.workflow.trim().to_owned();
2513    pt.save(tenant.pool()).await?;
2514    redirect_named_with_message(
2515        "rcms-admin:page-types",
2516        MsgLevel::Success,
2517        "Page type settings saved.",
2518        &headers,
2519    )
2520}
2521
2522/// POST /cms-admin/page-types/new — create a UI page type
2523/// (`app_label = "cms_ui"`) + an empty draft schema, then jump to the
2524/// field builder so the Developer designs its body immediately.
2525pub async fn page_type_create(
2526    State(state): State<super::AdminState>,
2527    tenant: Tenant,
2528    headers: HeaderMap,
2529    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
2530    Form(form): Form<FormPageTypeCreate>,
2531) -> Result<Response, AdminError> {
2532    if let Some(r) = ensure_builder_access(&tenant, session_user.as_ref()).await {
2533        return Ok(r);
2534    }
2535    // Blank identifier derives from the name — `slugify_key` is a FIELD-key
2536    // slugifier whose empty-input fallback is the literal "field", which made
2537    // every no-identifier type `cms_ui.field` (and the second one collide).
2538    let ident_src = if form.type_name.trim().is_empty() {
2539        form.verbose_name.as_str()
2540    } else {
2541        form.type_name.as_str()
2542    };
2543    let slug = crate::forms::schema::slugify_key(ident_src);
2544    let err: Option<String> = if form.verbose_name.trim().is_empty() {
2545        Some("Name is required.".to_owned())
2546    } else if !crate::forms::schema::is_valid_key(&slug) {
2547        Some(
2548            "Identifier is invalid — use letters/digits/underscores, starting with a letter."
2549                .to_owned(),
2550        )
2551    } else if crate::page_type_model::PageType::objects()
2552        .where_(crate::page_type_model::PageType::type_name.eq(slug.clone()))
2553        .first(tenant.pool())
2554        .await?
2555        .is_some()
2556        || crate::page_type::find_handler(&slug).is_some()
2557    {
2558        Some(format!(
2559            "A page type with identifier `{slug}` already exists."
2560        ))
2561    } else {
2562        None
2563    };
2564    if let Some(msg) = err {
2565        let mut ctx = Context::new();
2566        add_chrome(&mut ctx, &tenant, "page-types", session_user.as_ref()).await;
2567        add_admin_theme(&mut ctx, tenant.pool()).await;
2568        ctx.insert("list_url", "/cms-admin/page-types");
2569        ctx.insert("error", &msg);
2570        ctx.insert("form_verbose_name", &form.verbose_name);
2571        ctx.insert("form_type_name", &form.type_name);
2572        ctx.insert("form_allowed_parents", &form.allowed_parents);
2573        ctx.insert("form_allowed_children", &form.allowed_children);
2574        ctx.insert("form_workflow", &form.workflow);
2575        insert_workflow_choices(&mut ctx, tenant.pool()).await;
2576        return render_with_csrf(&state, &headers, "rcms_admin/page_type_form.html", &mut ctx);
2577    }
2578    // An API type has no HTML representation, so it gets the blank
2579    // template sentinel rather than the generic schema template —
2580    // otherwise `page_view::resolve_kind` would see a template and
2581    // never reach the JSON branch.
2582    let view_mode = crate::page_view::PageViewMode::parse(&form.view_mode);
2583    let default_template = if view_mode == crate::page_view::PageViewMode::Api {
2584        String::new()
2585    } else {
2586        crate::page_builder::DEFAULT_SCHEMA_TEMPLATE.to_owned()
2587    };
2588    let mut row = crate::page_type_model::PageType {
2589        id: rustango::sql::Auto::Unset,
2590        app_label: "cms_ui".to_owned(),
2591        type_name: slug.clone(),
2592        verbose_name: form.verbose_name.trim().to_owned(),
2593        default_template,
2594        view_mode: view_mode.as_str().to_owned(),
2595        is_creatable: true,
2596        allowed_parent_types: type_list_json(&form.allowed_parents),
2597        allowed_child_types: type_list_json(&form.allowed_children),
2598        workflow: form.workflow.trim().to_owned(),
2599        created_at: rustango::sql::Auto::Unset,
2600        updated_at: rustango::sql::Auto::Unset,
2601    };
2602    row.insert(tenant.pool()).await?;
2603    let new_id = row.id.get().copied().unwrap_or_default();
2604    // Seed an empty draft schema so the builder opens cleanly.
2605    let created_by = session_user.as_ref().and_then(|u| u.id.get().copied());
2606    crate::page_builder::model::save_draft(
2607        tenant.pool(),
2608        new_id,
2609        serde_json::json!({ "nodes": [] }),
2610        created_by,
2611    )
2612    .await
2613        .log_warn("empty builder draft not seeded");
2614    redirect_named_with_params_and_message(
2615        "rcms-admin:page-types:build",
2616        &[("id", new_id.to_string())],
2617        MsgLevel::Success,
2618        "Page type created — design its body, then Publish.",
2619        &headers,
2620    )
2621}
2622
2623/// POST /cms-admin/page-types/{id}/delete — delete a UI-created type.
2624/// Refused for code types and for types with existing pages.
2625pub async fn page_type_delete(
2626    State(_state): State<super::AdminState>,
2627    tenant: Tenant,
2628    headers: HeaderMap,
2629    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
2630    Path(id): Path<i64>,
2631) -> Result<Response, AdminError> {
2632    if let Some(r) = ensure_builder_access(&tenant, session_user.as_ref()).await {
2633        return Ok(r);
2634    }
2635    let pt = crate::page_type_model::PageType::objects()
2636        .where_(crate::page_type_model::PageType::id.eq(id))
2637        .first(tenant.pool())
2638        .await?
2639        .ok_or(AdminError::NotFound(id))?;
2640    // Only UI-created types are deletable; code types never are.
2641    if pt.app_label != "cms_ui" {
2642        return redirect_named_with_message(
2643            "rcms-admin:page-types",
2644            MsgLevel::Error,
2645            "Only UI-created page types can be deleted.",
2646            &headers,
2647        );
2648    }
2649    // A failed count must stop the delete, not read as "no pages" (#769).
2650    let page_count = Page::objects().where_(Page::page_type_id.eq(id)).count(tenant.pool()).await?;
2651    if page_count > 0 {
2652        return redirect_named_with_message(
2653            "rcms-admin:page-types",
2654            MsgLevel::Error,
2655            "Can't delete — pages still use this type. Delete or move them first.",
2656            &headers,
2657        );
2658    }
2659    // Drop the type's schema rows (draft/published/archived) then the row.
2660    for row in crate::page_builder::model::list_versions(tenant.pool(), id)
2661        .await
2662        .unwrap_or_default()
2663    {
2664        row.delete(tenant.pool()).await.log_warn("page-builder schema version not deleted");
2665    }
2666    pt.delete(tenant.pool()).await?;
2667    redirect_named_with_message(
2668        "rcms-admin:page-types",
2669        MsgLevel::Success,
2670        "Page type deleted.",
2671        &headers,
2672    )
2673}
2674
2675/// The canonical column of a translation row shows rich text formatted,
2676/// not as `<p>…</p>` markup. Sanitized: it is author content rendered
2677/// into the admin. Empty for every other widget kind (shown as text).
2678fn translation_canonical_html(widget_tag: &str, canonical: &str) -> String {
2679    if widget_tag == "richtext" && !canonical.trim().is_empty() {
2680        crate::markdown::sanitize_html(canonical)
2681    } else {
2682        String::new()
2683    }
2684}
2685
2686/// Translation-surface groups for a page's builder body: the
2687/// canonical text leaves (fixed fields, group members, zone stream
2688/// blocks) grouped like the StreamField leaf rows, each prefilled with
2689/// its existing per-locale override. Returns `[]` when the type has no
2690/// published schema. Paths are `builder.<…>` (see `values::…leaves`).
2691async fn builder_translation_groups(
2692    pool: &rustango::sql::Pool,
2693    page_id: i64,
2694    page_type_id: i64,
2695    existing: &std::collections::HashMap<String, String>,
2696) -> (Vec<serde_json::Value>, std::collections::HashSet<String>) {
2697    let mut paths = std::collections::HashSet::new();
2698    let Ok(Some(row)) =
2699        crate::page_builder::model::published_for(pool, page_type_id).await
2700    else {
2701        return (Vec::new(), paths);
2702    };
2703    let Ok(doc) = crate::page_builder::parse_schema(&row.document) else {
2704        return (Vec::new(), paths);
2705    };
2706    let components = crate::page_builder::model::component_map(pool)
2707        .await
2708        .unwrap_or_default();
2709    let compiled = crate::page_builder::compile(&doc, &components, row.version.max(1) as u32);
2710    let (values, _) = crate::page_builder::values::load_upgraded(pool, page_id, &compiled)
2711        .await
2712        .unwrap_or_else(|_| (serde_json::json!({}), Default::default()));
2713    let leaves = crate::page_builder::values::builder_translatable_leaves(&compiled, &values);
2714    // Group consecutively by block instance, mirroring stream_translations.
2715    let mut groups: Vec<serde_json::Value> = Vec::new();
2716    let mut cur = String::new();
2717    for leaf in &leaves {
2718        paths.insert(leaf.path.clone());
2719        let rowv = serde_json::json!({
2720            "path": leaf.path,
2721            "widget_kind": leaf.widget_kind.as_tag(),
2722            "field_label": leaf.field_label,
2723            "canonical": leaf.canonical_text,
2724            "canonical_html": translation_canonical_html(leaf.widget_kind.as_tag(), &leaf.canonical_text),
2725            "value": existing.get(&leaf.path).cloned().unwrap_or_default(),
2726        });
2727        if leaf.block_id != cur {
2728            cur.clone_from(&leaf.block_id);
2729            groups.push(serde_json::json!({
2730                "block_type": leaf.block_type,
2731                "block_label": leaf.block_label,
2732                "block_id": leaf.block_id,
2733                "depth": leaf.depth,
2734                "leaves": [rowv],
2735            }));
2736        } else if let Some(arr) = groups
2737            .last_mut()
2738            .and_then(|g| g.get_mut("leaves"))
2739            .and_then(|v| v.as_array_mut())
2740        {
2741            arr.push(rowv);
2742        }
2743    }
2744    (groups, paths)
2745}
2746
2747/// POST /cms-admin/media/bulk-move-collection — move every checked
2748/// media id into the selected `collection_id` (or NULL for
2749/// uncategorized).
2750pub async fn media_bulk_move_collection(
2751    State(_state): State<super::AdminState>,
2752    tenant: Tenant,
2753    headers: HeaderMap,
2754    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
2755    Form(form): Form<Vec<(String, String)>>,
2756) -> Result<Response, AdminError> {
2757    let target: Option<i64> = form
2758        .iter()
2759        .find(|(k, _)| k == "collection_id")
2760        .and_then(|(_, v)| v.parse::<i64>().ok())
2761        .filter(|id| *id > 0);
2762    let ids: Vec<i64> = form
2763        .iter()
2764        .filter(|(k, _)| k == "ids" || k == "id")
2765        .filter_map(|(_, v)| v.parse::<i64>().ok())
2766        .collect();
2767    let kind = form
2768        .iter()
2769        .find(|(k, _)| k == "kind")
2770        .map(|(_, v)| v.clone())
2771        .unwrap_or_else(|| "image".to_owned());
2772    // One UPDATE per chunk of the selection (#631), not a read and a
2773    // write per row; the count is what the database actually changed.
2774    // The count is of matched rows: MySQL reports only rows it changed,
2775    // so items already in the target would read as "Moved 0".
2776    let mut touched: i64 = 0;
2777    for chunk in ids.chunks(500) {
2778        use rustango::sql::UpdaterPool as _;
2779        let selected = || Media::objects().where_(Media::id.is_in(chunk.to_vec()));
2780        touched += selected().count(tenant.pool()).await?;
2781        let value = target.map_or(rustango::core::SqlValue::Null, rustango::core::SqlValue::I64);
2782        selected().update().set("collection_id", value).execute_pool(tenant.pool()).await?;
2783    }
2784    let redirect_url = if kind == "document" {
2785        "rcms-admin:documents:list"
2786    } else {
2787        "rcms-admin:media:list"
2788    };
2789    let dest = match target {
2790        Some(id) => format!("to collection #{id}"),
2791        None => "to Uncategorized".to_owned(),
2792    };
2793    redirect_named_with_message_plural(
2794        redirect_url,
2795        MsgLevel::Success,
2796        "Moved {count} item(s) {dest}.",
2797        touched as i64,
2798        &[("count", &touched.to_string()), ("dest", &dest)],
2799        &headers,
2800    )
2801}
2802
2803/// GET /cms-admin/media/collections/{id}/permissions — per-collection
2804/// permission editor. Same role × action grid shape as the
2805/// page permissions tab, just retargeted at `cms_collection_permission`.
2806pub async fn collection_permissions_form(
2807    State(state): State<super::AdminState>,
2808    tenant: Tenant,
2809    headers: HeaderMap,
2810    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
2811    Path(id): Path<i64>,
2812) -> Result<Response, AdminError> {
2813    let collection = crate::media::MediaCollection::objects()
2814        .where_(crate::media::MediaCollection::id.eq(id))
2815        .first(tenant.pool())
2816        .await?
2817        .ok_or(AdminError::NotFound(id))?;
2818    let roles: Vec<rustango::tenancy::permissions::Role> =
2819        rustango::tenancy::permissions::Role::objects()
2820            .order_by(&[("name", false)])
2821            .fetch(tenant.pool())
2822            .await?;
2823    let grants: Vec<crate::permissions::CollectionPermission> =
2824        crate::permissions::CollectionPermission::objects()
2825            .where_(crate::permissions::CollectionPermission::collection_id.eq(id))
2826            .fetch(tenant.pool())
2827            .await?;
2828    let granted: std::collections::HashSet<(i64, String)> = grants
2829        .iter()
2830        .map(|g| (g.role_id, g.permission.clone()))
2831        .collect();
2832    let actions: Vec<&str> = crate::permissions::Action::all()
2833        .iter()
2834        .map(|a| a.as_str())
2835        .collect();
2836    let perm_grid: Vec<serde_json::Value> = roles
2837        .iter()
2838        .map(|r| {
2839            let rid = r.id.get().copied().unwrap_or_default();
2840            let row_cells: Vec<serde_json::Value> = actions
2841                .iter()
2842                .map(|a| {
2843                    serde_json::json!({
2844                        "action": a,
2845                        "granted": granted.contains(&(rid, (*a).to_owned())),
2846                    })
2847                })
2848                .collect();
2849            serde_json::json!({
2850                "role_id": rid,
2851                "role_name": r.name,
2852                "role_description": r.description,
2853                "cells": row_cells,
2854            })
2855        })
2856        .collect();
2857
2858    let mut ctx = Context::new();
2859    add_chrome(&mut ctx, &tenant, "media", session_user.as_ref()).await;
2860    add_admin_theme(&mut ctx, tenant.pool()).await;
2861    ctx.insert("collection_id", &id);
2862    ctx.insert("collection_name", &collection.name);
2863    ctx.insert("perm_actions", &actions);
2864    ctx.insert("perm_grid", &perm_grid);
2865
2866    // #195 — view restriction picker. Surface the current direct
2867    // restriction (if any) and the role list for the groups option.
2868    let restriction = crate::collection_view_restriction::direct_for_collection(tenant.pool(), id)
2869        .await
2870        .unwrap_or_default();
2871    let restriction_kind = restriction
2872        .as_ref()
2873        .map(|r| r.kind.clone())
2874        .unwrap_or_else(|| "none".to_owned());
2875    let restriction_groups: std::collections::HashSet<i64> = restriction
2876        .as_ref()
2877        .map(|r| r.parsed_groups().into_iter().collect())
2878        .unwrap_or_default();
2879    let restriction_has_password = restriction
2880        .as_ref()
2881        .map(|r| !r.password_hash.is_empty())
2882        .unwrap_or(false);
2883    let role_options: Vec<serde_json::Value> = roles
2884        .iter()
2885        .map(|r| {
2886            let rid = r.id.get().copied().unwrap_or_default();
2887            serde_json::json!({
2888                "id": rid,
2889                "name": r.name,
2890                "selected": restriction_groups.contains(&rid),
2891            })
2892        })
2893        .collect();
2894    // #members — permission-codename picker (the permission-engine gate).
2895    let restriction_codenames: Vec<String> = restriction
2896        .as_ref()
2897        .map(|r| r.parsed_codenames())
2898        .unwrap_or_default();
2899    let restriction_codenames_str = restriction_codenames.join(",");
2900    let codename_choices: Vec<serde_json::Value> = super::resources::membership_codenames()
2901        .into_iter()
2902        .map(|(codename, label)| {
2903            serde_json::json!({
2904                "codename": codename,
2905                "label": label,
2906                "checked": restriction_codenames.contains(&codename),
2907            })
2908        })
2909        .collect();
2910    ctx.insert("restriction_kind", &restriction_kind);
2911    ctx.insert("restriction_has_password", &restriction_has_password);
2912    ctx.insert("restriction_roles", &role_options);
2913    ctx.insert("restriction_codenames_str", &restriction_codenames_str);
2914    ctx.insert("restriction_codename_choices", &codename_choices);
2915
2916    render_with_csrf(
2917        &state,
2918        &headers,
2919        "rcms_admin/collection_permissions.html",
2920        &mut ctx,
2921    )
2922}
2923
2924/// Form body for `POST /cms-admin/media/collections/{id}/privacy`.
2925#[derive(Deserialize)]
2926pub struct CollectionPrivacyForm {
2927    pub kind: String,
2928    #[serde(default)]
2929    pub password: String,
2930    #[serde(default)]
2931    pub group_ids: String,
2932    /// Comma-separated permission codenames — used when `kind =
2933    /// permission` (the permission-engine gate). Empty otherwise.
2934    #[serde(default)]
2935    pub codenames: String,
2936}
2937
2938/// POST /cms-admin/media/collections/{id}/privacy — upsert the view
2939/// restriction for a collection. `kind=none` deletes the row.
2940/// Mirrors the page-privacy submit handler exactly.
2941pub async fn collection_privacy_submit(
2942    State(_state): State<super::AdminState>,
2943    tenant: Tenant,
2944    headers: HeaderMap,
2945    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
2946    Path(id): Path<i64>,
2947    Form(form): Form<CollectionPrivacyForm>,
2948) -> Result<Response, AdminError> {
2949    use rustango::sql::Auto;
2950    let existing =
2951        crate::collection_view_restriction::direct_for_collection(tenant.pool(), id).await?;
2952    if form.kind == "none" {
2953        if let Some(row) = existing {
2954            row.delete(tenant.pool()).await?;
2955            return redirect_named_with_params_and_message(
2956                "rcms-admin:media:collection-permissions",
2957                &[("id", id.to_string())],
2958                MsgLevel::Success,
2959                "Removed view restriction — collection is now public.",
2960                &headers,
2961            );
2962        }
2963        return redirect_named_with_params_and_message(
2964            "rcms-admin:media:collection-permissions",
2965            &[("id", id.to_string())],
2966            MsgLevel::Info,
2967            "No restriction to remove.",
2968            &headers,
2969        );
2970    }
2971    let Some(kind) = crate::collection_view_restriction::RestrictionKind::parse(&form.kind) else {
2972        return Err(AdminError::Validation(format!(
2973            "unknown restriction kind `{}`",
2974            form.kind
2975        )));
2976    };
2977    let password_hash = match kind {
2978        crate::collection_view_restriction::RestrictionKind::Password => {
2979            if form.password.is_empty() {
2980                if let Some(row) = &existing {
2981                    if row.kind == kind.as_str() {
2982                        row.password_hash.clone()
2983                    } else {
2984                        return redirect_named_with_params_and_message(
2985                            "rcms-admin:media:collection-permissions",
2986                            &[("id", id.to_string())],
2987                            MsgLevel::Error,
2988                            "Password is required when switching the restriction kind to password.",
2989                            &headers,
2990                        );
2991                    }
2992                } else {
2993                    return redirect_named_with_params_and_message(
2994                        "rcms-admin:media:collection-permissions",
2995                        &[("id", id.to_string())],
2996                        MsgLevel::Error,
2997                        "Password is required for password-protected collections.",
2998                        &headers,
2999                    );
3000                }
3001            } else {
3002                crate::passwords::hash(&form.password).await
3003                    .map_err(|e| AdminError::Validation(format!("password hash failed: {e}")))?
3004            }
3005        }
3006        _ => String::new(),
3007    };
3008    let group_ids: Vec<i64> = if matches!(
3009        kind,
3010        crate::collection_view_restriction::RestrictionKind::Groups
3011    ) {
3012        form.group_ids
3013            .split(',')
3014            .filter_map(|s| s.trim().parse::<i64>().ok())
3015            .collect()
3016    } else {
3017        Vec::new()
3018    };
3019    let group_json = serde_json::json!(group_ids);
3020    let codenames: Vec<String> = if matches!(
3021        kind,
3022        crate::collection_view_restriction::RestrictionKind::Permission
3023    ) {
3024        form.codenames
3025            .split(',')
3026            .map(str::trim)
3027            .filter(|s| !s.is_empty())
3028            .map(str::to_owned)
3029            .collect()
3030    } else {
3031        Vec::new()
3032    };
3033    let codenames_json = serde_json::json!(codenames);
3034    match existing {
3035        Some(mut row) => {
3036            row.kind = kind.as_str().to_owned();
3037            row.password_hash = password_hash;
3038            row.group_ids = group_json;
3039            row.codenames = codenames_json;
3040            row.save(tenant.pool()).await?;
3041        }
3042        None => {
3043            let mut row = crate::collection_view_restriction::CollectionViewRestriction {
3044                id: Auto::Unset,
3045                collection_id: id,
3046                kind: kind.as_str().to_owned(),
3047                password_hash,
3048                group_ids: group_json,
3049                codenames: codenames_json,
3050                created_at: Auto::Unset,
3051                updated_at: Auto::Unset,
3052            };
3053            row.insert(tenant.pool()).await?;
3054        }
3055    }
3056    redirect_named_with_params_and_message(
3057        "rcms-admin:media:collection-permissions",
3058        &[("id", id.to_string())],
3059        MsgLevel::Success,
3060        "Collection privacy updated. New requests to /__media__/<spec>/<id> will enforce it.",
3061        &headers,
3062    )
3063}
3064
3065/// POST /cms-admin/media/collections/{id}/permissions — replace the
3066/// collection's permission set with the JSON body's grant list.
3067/// Idempotent want/have diff, returns 204 on success. Mirrors the
3068/// page-permission save endpoint exactly.
3069pub async fn collection_permissions_submit(
3070    State(_state): State<super::AdminState>,
3071    tenant: Tenant,
3072    Path(collection_id): Path<i64>,
3073    axum::Json(payload): axum::Json<PagePermissionsPayload>,
3074) -> Result<Response, AdminError> {
3075    use rustango::sql::Auto;
3076    let valid_actions: std::collections::HashSet<&str> = crate::permissions::Action::all()
3077        .iter()
3078        .map(|a| a.as_str())
3079        .collect();
3080    let want: std::collections::BTreeSet<(i64, String)> = payload
3081        .grants
3082        .iter()
3083        .filter(|g| valid_actions.contains(g.action.as_str()))
3084        .map(|g| (g.role_id, g.action.clone()))
3085        .collect();
3086
3087    let existing: Vec<crate::permissions::CollectionPermission> =
3088        crate::permissions::CollectionPermission::objects()
3089            .where_(crate::permissions::CollectionPermission::collection_id.eq(collection_id))
3090            .fetch(tenant.pool())
3091            .await?;
3092    let have: std::collections::BTreeSet<(i64, String)> = existing
3093        .iter()
3094        .map(|p| (p.role_id, p.permission.clone()))
3095        .collect();
3096
3097    for p in &existing {
3098        let key = (p.role_id, p.permission.clone());
3099        if !want.contains(&key) {
3100            p.clone().delete(tenant.pool()).await?;
3101        }
3102    }
3103    for (role_id, action) in &want {
3104        if !have.contains(&(*role_id, action.clone())) {
3105            let mut row = crate::permissions::CollectionPermission {
3106                id: Auto::Unset,
3107                collection_id,
3108                role_id: *role_id,
3109                permission: action.clone(),
3110                created_at: Auto::Unset,
3111            };
3112            row.insert(tenant.pool()).await?;
3113        }
3114    }
3115    Ok(axum::http::StatusCode::NO_CONTENT.into_response())
3116}
3117
3118/// JSON payload for the permission tab's bulk save endpoint —
3119/// the grid POSTs a list of `(role_id, action)` pairs and the
3120/// handler replaces the page's grant set with that list.
3121#[derive(Debug, Deserialize)]
3122pub struct PagePermissionsPayload {
3123    pub grants: Vec<PagePermissionGrant>,
3124}
3125#[derive(Debug, Deserialize)]
3126pub struct PagePermissionGrant {
3127    pub role_id: i64,
3128    pub action: String,
3129}
3130
3131/// POST /cms-admin/pages/{id}/permissions — replace the page's
3132/// permission set with the list in the JSON body. Idempotent;
3133/// computes the want/have diff and applies the minimum INSERTs +
3134/// DELETEs. Returns 204 on success.
3135pub async fn page_permissions_submit(
3136    State(_state): State<super::AdminState>,
3137    tenant: Tenant,
3138    Path(page_id): Path<i64>,
3139    axum::Json(payload): axum::Json<PagePermissionsPayload>,
3140) -> Result<Response, AdminError> {
3141    use rustango::sql::Auto;
3142    let valid_actions: std::collections::HashSet<&str> = crate::permissions::Action::all()
3143        .iter()
3144        .map(|a| a.as_str())
3145        .collect();
3146    let want: std::collections::BTreeSet<(i64, String)> = payload
3147        .grants
3148        .iter()
3149        .filter(|g| valid_actions.contains(g.action.as_str()))
3150        .map(|g| (g.role_id, g.action.clone()))
3151        .collect();
3152
3153    let existing: Vec<crate::permissions::PagePermission> =
3154        crate::permissions::PagePermission::objects()
3155            .where_(crate::permissions::PagePermission::page_id.eq(page_id))
3156            .fetch(tenant.pool())
3157            .await?;
3158    let have: std::collections::BTreeSet<(i64, String)> = existing
3159        .iter()
3160        .map(|p| (p.role_id, p.permission.clone()))
3161        .collect();
3162
3163    // Drop rows that aren't wanted.
3164    for p in &existing {
3165        let key = (p.role_id, p.permission.clone());
3166        if !want.contains(&key) {
3167            p.clone().delete(tenant.pool()).await?;
3168        }
3169    }
3170    // Insert rows that don't exist yet.
3171    for (role_id, action) in &want {
3172        if !have.contains(&(*role_id, action.clone())) {
3173            let mut row = crate::permissions::PagePermission {
3174                id: Auto::Unset,
3175                page_id,
3176                role_id: *role_id,
3177                permission: action.clone(),
3178                created_at: Auto::Unset,
3179            };
3180            row.insert(tenant.pool()).await?;
3181        }
3182    }
3183
3184    Ok(axum::http::StatusCode::NO_CONTENT.into_response())
3185}
3186
3187/// Resolve every [`TabSpec`](crate::page_type::TabSpec) variant
3188/// into the flat shape page_form.html iterates: `{name, label, icon,
3189/// badge, html}`. Failures on `Template` / `Widgets` rendering
3190/// fall back to an inline error banner instead of crashing the page
3191/// editor — the author sees the Tera message + can fix the template.
3192fn render_extra_tabs(
3193    specs: Vec<crate::page_type::TabSpec>,
3194    tera: &std::sync::Arc<tera::Tera>,
3195    base_ctx: &Context,
3196    headers: &HeaderMap,
3197) -> Vec<serde_json::Value> {
3198    use crate::page_type::TabBody;
3199    specs
3200        .into_iter()
3201        .map(|spec| {
3202            let html = match spec.body {
3203                TabBody::Html(s) => s,
3204                TabBody::Template { path, context } => {
3205                    let mut tab_ctx = base_ctx.clone();
3206                    for (k, v) in context {
3207                        tab_ctx.insert(&k, &v);
3208                    }
3209                    tera.render(&path, &tab_ctx).unwrap_or_else(|e| {
3210                        format!(
3211                            r#"<div class="rcms-flash rcms-flash--error" style="margin: 12px 0;">
3212    <span class="rcms-flash-body"><strong>{label}</strong> {failed} <code>{path}</code>: {e}</span>
3213</div>"#,
3214                            label = tera::escape_html(&super::i18n::tr(headers, "Tab template error:", &[])),
3215                            failed = tera::escape_html(&super::i18n::tr(headers, "failed to render", &[])),
3216                            path = tera::escape_html(&path),
3217                            e = tera::escape_html(&e.to_string()),
3218                        )
3219                    })
3220                }
3221                TabBody::Widgets(widgets) => {
3222                    let mut ctx = Context::new();
3223                    ctx.insert("widgets", &widgets);
3224                    tera.render("rcms_admin/_widget_group.html", &ctx)
3225                        .unwrap_or_else(|e| {
3226                            format!(
3227                                r#"<div class="rcms-flash rcms-flash--error" style="margin: 12px 0;">
3228    <span class="rcms-flash-body"><strong>{label}</strong> {e}</span>
3229</div>"#,
3230                                label = tera::escape_html(&super::i18n::tr(headers, "Widget-group tab error:", &[])),
3231                                e = tera::escape_html(&e.to_string()),
3232                            )
3233                        })
3234                }
3235                TabBody::Group { heading, help, layout, widgets } => {
3236                    // Field group panel (column or row layout).
3237                    // Wrap the same _widget_group output in a
3238                    // <fieldset> with a heading + (optional) help
3239                    // paragraph + layout class.
3240                    let mut ctx = Context::new();
3241                    ctx.insert("widgets", &widgets);
3242                    let inner = tera
3243                        .render("rcms_admin/_widget_group.html", &ctx)
3244                        .unwrap_or_else(|e| {
3245                            format!(
3246                                r#"<div class="rcms-flash rcms-flash--error" style="margin: 12px 0;">
3247    <span class="rcms-flash-body"><strong>{label}</strong> {e}</span>
3248</div>"#,
3249                                label = tera::escape_html(&super::i18n::tr(headers, "Panel-group tab error:", &[])),
3250                                e = tera::escape_html(&e.to_string()),
3251                            )
3252                        });
3253                    let help_html = if help.is_empty() {
3254                        String::new()
3255                    } else {
3256                        format!(
3257                            r#"<p class="rcms-hint rcms-panel-group-help">{}</p>"#,
3258                            tera::escape_html(&help),
3259                        )
3260                    };
3261                    format!(
3262                        r#"<fieldset class="rcms-panel-group rcms-panel-group--{layout}">
3263    <legend>{heading}</legend>
3264    {help_html}
3265    <div class="rcms-panel-group-body">{inner}</div>
3266</fieldset>"#,
3267                        layout = layout.class_suffix(),
3268                        heading = tera::escape_html(&heading),
3269                        help_html = help_html,
3270                        inner = inner,
3271                    )
3272                }
3273                TabBody::Help { content } => {
3274                    // Static help block. Author-supplied HTML; emit
3275                    // raw inside a hint-styled container.
3276                    format!(
3277                        r#"<div class="rcms-panel-help">{content}</div>"#,
3278                        content = content,
3279                    )
3280                }
3281            };
3282            serde_json::json!({
3283                "name": spec.name,
3284                "label": spec.label,
3285                "icon": spec.icon,
3286                "badge": spec.badge,
3287                "html": html,
3288            })
3289        })
3290        .collect()
3291}
3292
3293/// `/cms-admin/x/{slug}` and `/cms-admin/x/{slug}/{action}`: the custom
3294/// admin page dispatcher. Finds the
3295/// [`AdminPageHandler`](super::admin_page::AdminPageHandler) registered
3296/// for `slug` and hands a `GET` to its `render`, a `POST` to its `post`
3297/// with the parsed form. The route gate has already checked the page's
3298/// codename; the host's CSRF layer has checked the token. Unknown slugs
3299/// are 404.
3300pub async fn admin_page_dispatch(
3301    State(state): State<super::AdminState>,
3302    tenant: Tenant,
3303    method: axum::http::Method,
3304    uri: axum::http::Uri,
3305    headers: HeaderMap,
3306    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
3307    Path(params): Path<std::collections::HashMap<String, String>>,
3308    body: axum::body::Bytes,
3309) -> Result<Response, AdminError> {
3310    let slug = params.get("slug").map(String::as_str).unwrap_or_default();
3311    let Some(handler) = super::admin_page::find_admin_page(slug) else {
3312        return Err(AdminError::NotFound(0));
3313    };
3314    let ctx = super::admin_page::AdminPageCtx {
3315        tera: &state.tera,
3316        tenant: &tenant,
3317        headers: &headers,
3318        user: session_user.as_ref(),
3319        uri: &uri,
3320        action: params.get("action").map(String::as_str),
3321    };
3322    Ok(if method == axum::http::Method::POST {
3323        handler.post(ctx, super::admin_page::AdminForm::parse(&body)).await
3324    } else {
3325        handler.render(ctx).await
3326    })
3327}
3328
3329/// Load the active admin theme + its brand colors and stuff the
3330/// rendered CSS / data-attrs into the Tera context so `_base.html`
3331/// can drop them straight into the page chrome. Falls back gracefully
3332/// if no theme is configured (admin renders with built-in defaults).
3333pub(crate) async fn add_admin_theme(ctx: &mut Context, pool: &rustango::sql::Pool) {
3334    // Pick the row flagged `is_admin_default`; if none, fall back to
3335    // whichever is `is_default`; if still none, the first row.
3336    let mut admin_default: Vec<crate::theme::Theme> = crate::theme::Theme::objects()
3337        .where_(crate::theme::Theme::is_admin_default.eq(true))
3338        .fetch(pool)
3339        .await
3340        .unwrap_or_default();
3341    let theme = if let Some(t) = admin_default.pop() {
3342        t
3343    } else {
3344        let mut any: Vec<crate::theme::Theme> = crate::theme::Theme::objects()
3345            .where_(crate::theme::Theme::is_default.eq(true))
3346            .fetch(pool)
3347            .await
3348            .unwrap_or_default();
3349        match any.pop() {
3350            Some(t) => t,
3351            None => {
3352                let mut first: Vec<crate::theme::Theme> = crate::theme::Theme::objects()
3353                    .order_by(&[("name", false)])
3354                    .fetch(pool)
3355                    .await
3356                    .unwrap_or_default();
3357                let Some(t) = first.pop() else {
3358                    // No themes at all — set empty strings so the
3359                    // template's `{% if %}` guards short-circuit.
3360                    ctx.insert("theme_css", &String::new());
3361                    ctx.insert("theme_slug", &String::new());
3362                    ctx.insert("theme_default_mode", &"light");
3363                    ctx.insert("theme_font_url", &String::new());
3364                    return;
3365                };
3366                t
3367            }
3368        }
3369    };
3370    let theme_id = theme.id.get().copied().unwrap_or_default();
3371    let brand_colors: Vec<crate::theme::BrandColor> = crate::theme::BrandColor::objects()
3372        .where_(crate::theme::BrandColor::theme_id.eq(theme_id))
3373        .order_by(&[("sort_order", false)])
3374        .fetch(pool)
3375        .await
3376        .unwrap_or_default();
3377    let css = crate::theme::emit_css(&theme, &brand_colors);
3378    ctx.insert("theme_css", &css);
3379    ctx.insert("theme_slug", &theme.slug);
3380    ctx.insert("theme_name", &theme.name);
3381    ctx.insert("theme_default_mode", &theme.default_mode);
3382    ctx.insert("theme_font_url", &theme.font_url);
3383}
3384
3385/// Query string for the page list / search view.
3386#[derive(Debug, Deserialize)]
3387pub struct ListQuery {
3388    /// Filter children of this parent only. Omitted = root listing.
3389    /// Ignored when `q` is set — search always spans the full tree.
3390    #[serde(default)]
3391    pub parent: Option<i64>,
3392    /// Full-tree search query. Case-insensitive substring match
3393    /// across title, slug, and url_path. Empty string skips the
3394    /// search path and shows the current parent's children.
3395    #[serde(default)]
3396    pub q: Option<String>,
3397    /// Filter results by page type slug — pairs with `q` or stands
3398    /// alone. Matches `cms_page_type.type_name`.
3399    #[serde(default)]
3400    pub r#type: Option<String>,
3401    /// Filter results by status (`draft|scheduled|published|archived`).
3402    #[serde(default)]
3403    pub status: Option<String>,
3404}
3405
3406/// GET /cms-admin/pages — flat list of pages directly under the
3407/// current parent (root by default). Editors drill into a subtree
3408/// via the per-row "View children" action; the breadcrumb trail
3409/// at the top lets them navigate back up. Replaces the previous
3410/// indented full-tree view.
3411///
3412/// Per-page permissions: when the request carries a
3413/// session cookie, the resolver filters out rows the user can't
3414/// `view`. Superusers + anonymous / no-session contexts (sqlite
3415/// dev) see every row.
3416pub async fn page_list(
3417    State(state): State<super::AdminState>,
3418    tenant: Tenant,
3419    headers: HeaderMap,
3420    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
3421    Query(q): Query<ListQuery>,
3422) -> Result<Response, AdminError> {
3423    // Best-effort schedule sweep so editors always see current state.
3424    // #207 — uses the mailer-aware variant so the pre-publish
3425    // reminder pass runs on the same tick.
3426    match crate::page::run_schedule_sweep_with_mailer(
3427        tenant.pool(),
3428        state.mailer.as_deref(),
3429        &state.mailer_from,
3430        &tenant.org.slug,
3431    )
3432    .await
3433    {
3434        // A page this sweep put live or took down must leave the cache
3435        // too, as the timed sweep's purge does (#692).
3436        Ok(result) if !result.changed_urls.is_empty() => {
3437            crate::task_queue::purge_urls(
3438                state.cache_invalidator.clone(),
3439                tenant_key(&tenant.org)?,
3440                result.changed_urls,
3441            )
3442            .await;
3443        }
3444        Ok(_) => {}
3445        Err(e) => tracing::warn!(target: "rustango_cms::admin", error = %e, "schedule sweep failed"),
3446    }
3447
3448    // Pull every page once — we need the full list both for
3449    // breadcrumb computation (walk ancestors of `parent`) and child
3450    // counts (how many pages live under each row in the current
3451    // listing). Tenants stay in the small-N range; the materialized
3452    // list is cheap.
3453    let all_pages: Vec<Page> = Page::objects()
3454        .order_by(&[("path", false), ("sort_order", false)])
3455        .fetch(tenant.pool())
3456        .await?;
3457
3458    // Index pages by id for ancestor walk.
3459    let by_id: std::collections::HashMap<i64, &Page> = all_pages
3460        .iter()
3461        .filter_map(|p| p.id.get().copied().map(|id| (id, p)))
3462        .collect();
3463
3464    // Current parent — None means root listing.
3465    let parent_page: Option<&Page> = q.parent.and_then(|pid| by_id.get(&pid).copied());
3466
3467    // Breadcrumb: walk parent chain up to root, then reverse.
3468    let mut breadcrumbs: Vec<serde_json::Value> = Vec::new();
3469    if let Some(mut cur) = parent_page {
3470        breadcrumbs.push(serde_json::json!({
3471            "id": cur.id.get().copied(),
3472            "title": cur.title.clone(),
3473        }));
3474        while let Some(ppid) = cur.parent_id {
3475            if let Some(p) = by_id.get(&ppid).copied() {
3476                breadcrumbs.push(serde_json::json!({
3477                    "id": p.id.get().copied(),
3478                    "title": p.title.clone(),
3479                }));
3480                cur = p;
3481            } else {
3482                break;
3483            }
3484        }
3485        breadcrumbs.reverse();
3486    }
3487
3488    // Determine the working set:
3489    //   - search mode (`q`): full tree, filtered by ILIKE on title/slug/url_path
3490    //   - browse mode (no `q`): direct children of `parent` only
3491    let search_query =
3492        q.q.as_deref()
3493            .map(str::trim)
3494            .filter(|s| !s.is_empty())
3495            .map(str::to_owned);
3496    let status_filter = q
3497        .status
3498        .as_deref()
3499        .map(str::trim)
3500        .filter(|s| !s.is_empty())
3501        .map(str::to_owned);
3502    let type_filter_slug = q
3503        .r#type
3504        .as_deref()
3505        .map(str::trim)
3506        .filter(|s| !s.is_empty())
3507        .map(str::to_owned);
3508
3509    // Per-page permissions filter (#18 phase 3). Skipped when the
3510    // request is anonymous (sqlite dev / no session) or the user
3511    // is a tenant superuser — both paths see every page. For
3512    // authenticated, non-superuser sessions we pre-compute the
3513    // viewable set so the browse/search filter below can apply it.
3514    let viewer_user_id: Option<i64> = session_user
3515        .as_ref()
3516        .filter(|u| u.active)
3517        .and_then(|u| u.id.get().copied());
3518    let viewer_is_superuser = session_user.as_ref().is_some_and(|u| u.is_superuser);
3519    let permission_filter_enabled = viewer_user_id.is_some() && !viewer_is_superuser;
3520    let viewable_ids: Option<std::collections::HashSet<i64>> = match viewer_user_id {
3521        Some(uid) if permission_filter_enabled => {
3522            let pages: Vec<(i64, Option<i64>)> = all_pages
3523                .iter()
3524                .filter_map(|p| p.id.get().copied().map(|id| (id, p.parent_id)))
3525                .collect();
3526            Some(
3527                crate::permissions::viewable_page_ids(tenant.pool(), uid, &pages)
3528                    .await
3529                    .unwrap_or_default(),
3530            )
3531        }
3532        _ => None,
3533    };
3534
3535    // #408 — relevance-ranked, all-status admin search on Postgres: FTS
3536    // finds stemmed / word-boundary matches the substring filter misses
3537    // (across drafts too) and orders by relevance. `None` on non-PG / a
3538    // query error → the substring filter below stands.
3539    let fts_rank: Option<std::collections::HashMap<i64, usize>> = match search_query.as_deref() {
3540        Some(q) => crate::search::search_page_ids_all_statuses(tenant.pool(), q, 1000)
3541            .await
3542            .map(|ids| ids.iter().enumerate().map(|(i, id)| (*id, i)).collect()),
3543        None => None,
3544    };
3545    let visible: Vec<&Page> = if search_query.is_some()
3546        || status_filter.is_some()
3547        || type_filter_slug.is_some()
3548    {
3549        // Search / filter mode — full-tree.
3550        let q_lower = search_query.as_deref().map(str::to_lowercase);
3551        // Resolve type slug → id via the not-yet-fetched type list.
3552        // We pull `cms_page_type` below for the verbose-name map
3553        // either way; do it inline here for the filter id.
3554        let prefetch_types: Vec<PageType> = PageType::objects().fetch(tenant.pool()).await?;
3555        let type_id_by_slug: std::collections::HashMap<String, i64> = prefetch_types
3556            .iter()
3557            .filter_map(|t| t.id.get().copied().map(|id| (t.type_name.clone(), id)))
3558            .collect();
3559        let type_id_filter = type_filter_slug
3560            .as_deref()
3561            .and_then(|s| type_id_by_slug.get(s).copied());
3562        all_pages
3563            .iter()
3564            .filter(|p| {
3565                // A full-text hit OR a substring match (#702): full-text finds
3566                // stemmed words, but not a partial word, a slug fragment or a
3567                // URL path, so on Postgres it must add to the substring match
3568                // the other backends use, not replace it. Relevance order is
3569                // the re-sort below; substring-only hits follow the ranked ones.
3570                let matches_search = match &q_lower {
3571                    None => true,
3572                    Some(needle) => {
3573                        fts_rank.as_ref().is_some_and(|rank| {
3574                            p.id.get().copied().is_some_and(|id| rank.contains_key(&id))
3575                        }) || p.title.to_lowercase().contains(needle)
3576                            || p.slug.to_lowercase().contains(needle)
3577                            || p.url_path.to_lowercase().contains(needle)
3578                    }
3579                };
3580                let matches_status = match &status_filter {
3581                    None => true,
3582                    Some(s) => p.status == *s,
3583                };
3584                let matches_type = match type_id_filter {
3585                    None => true,
3586                    Some(id) => p.page_type_id == id,
3587                };
3588                matches_search && matches_status && matches_type
3589            })
3590            .collect()
3591    } else {
3592        // Browse mode — direct children only.
3593        all_pages
3594            .iter()
3595            .filter(|p| p.parent_id == q.parent)
3596            .collect()
3597    };
3598    // Snapshot the pre-permission visible count so the empty-state
3599    // copy can distinguish "tree is empty here" from "you can't see
3600    // any of these pages" (#70).
3601    let visible_before_permission_filter = visible.len();
3602    // Apply per-page view filter as a final pass — affects both
3603    // search and browse modes uniformly.
3604    let visible: Vec<&Page> = match &viewable_ids {
3605        None => visible,
3606        Some(set) => visible
3607            .into_iter()
3608            .filter(|p| p.id.get().copied().is_some_and(|id| set.contains(&id)))
3609            .collect(),
3610    };
3611    // #408 — when FTS drove the search, order results by relevance
3612    // (overriding the default path order in search mode).
3613    let visible: Vec<&Page> = if let Some(rank) = &fts_rank {
3614        let mut v = visible;
3615        v.sort_by_key(|p| {
3616            p.id.get()
3617                .copied()
3618                .and_then(|id| rank.get(&id).copied())
3619                .unwrap_or(usize::MAX)
3620        });
3621        v
3622    } else {
3623        visible
3624    };
3625    let is_search_mode =
3626        search_query.is_some() || status_filter.is_some() || type_filter_slug.is_some();
3627    // #70 — empty-state classification. Exactly one of these is
3628    // surfaced into the template when `rows | length == 0`:
3629    //   * `empty_filtered`         — search/filter mode dropped every row
3630    //   * `empty_hidden_by_perms`  — per-page permissions dropped every row
3631    //                                that would otherwise be visible
3632    //   * (default)                — genuinely empty section
3633    let empty_filtered = is_search_mode && visible.is_empty();
3634    let empty_hidden_by_perms = !is_search_mode
3635        && visible.is_empty()
3636        && visible_before_permission_filter > 0
3637        && permission_filter_enabled;
3638
3639    // Child counts — for the "View children" CTA.
3640    let mut child_counts: std::collections::HashMap<i64, i64> = std::collections::HashMap::new();
3641    for p in &all_pages {
3642        if let Some(ppid) = p.parent_id {
3643            *child_counts.entry(ppid).or_insert(0) += 1;
3644        }
3645    }
3646
3647    let types: Vec<PageType> = PageType::objects().fetch(tenant.pool()).await?;
3648    let type_map: std::collections::HashMap<i64, String> = types
3649        .iter()
3650        .filter_map(|t| t.id.get().copied().map(|id| (id, t.verbose_name.clone())))
3651        .collect();
3652
3653    let live_urls = build_live_url_map(&all_pages);
3654
3655    // Helper: walk a page's parent chain into a list of `{id, title}`
3656    // crumbs (root → page). Only computed in search mode where the
3657    // editor needs context for results that live deep in the tree.
3658    let ancestors_for = |p: &Page| -> Vec<serde_json::Value> {
3659        let mut chain: Vec<serde_json::Value> = Vec::new();
3660        let mut cur_parent = p.parent_id;
3661        while let Some(pid) = cur_parent {
3662            match by_id.get(&pid).copied() {
3663                Some(ancestor) => {
3664                    chain.push(serde_json::json!({
3665                        "id": ancestor.id.get().copied(),
3666                        "title": ancestor.title.clone(),
3667                    }));
3668                    cur_parent = ancestor.parent_id;
3669                }
3670                None => break,
3671            }
3672        }
3673        chain.reverse();
3674        chain
3675    };
3676
3677    let rows: Vec<serde_json::Value> = visible
3678        .iter()
3679        .map(|p| {
3680            let id = p.id.get().copied();
3681            let ancestors = if is_search_mode {
3682                ancestors_for(p)
3683            } else {
3684                Vec::new()
3685            };
3686            serde_json::json!({
3687                "id": id,
3688                "title": p.title,
3689                "slug": p.slug,
3690                "path": p.path,
3691                "url_path": p.url_path,
3692                "status": p.status,
3693                "page_type_id": p.page_type_id,
3694                "go_live_at": p.go_live_at,
3695                "expire_at": p.expire_at,
3696                "updated_at": p.updated_at.get().copied(),
3697                "published_at": p.published_at,
3698                "locale_variant_of": p.locale_variant_of,
3699                "alias_of": p.alias_of,
3700                "child_count": id.and_then(|i| child_counts.get(&i).copied()).unwrap_or(0),
3701                "ancestors": ancestors,
3702            })
3703        })
3704        .collect();
3705
3706    let mut ctx = Context::new();
3707    add_chrome(&mut ctx, &tenant, "pages", session_user.as_ref()).await;
3708    add_admin_theme(&mut ctx, tenant.pool()).await;
3709    ctx.insert("rows", &rows);
3710    ctx.insert("type_map", &type_map);
3711    // #614 — the "+ New root page" menu must offer only root-legal types.
3712    ctx.insert("creatable_types", &allowed_root_types(&types));
3713    ctx.insert("live_urls", &live_urls);
3714    ctx.insert("breadcrumbs", &breadcrumbs);
3715    ctx.insert("parent_id", &q.parent);
3716    ctx.insert("parent_title", &parent_page.map(|p| p.title.clone()));
3717    ctx.insert("search_query", &search_query);
3718    ctx.insert("status_filter", &status_filter);
3719    ctx.insert("type_filter", &type_filter_slug);
3720    ctx.insert("is_search_mode", &is_search_mode);
3721    ctx.insert("empty_filtered", &empty_filtered);
3722    ctx.insert("empty_hidden_by_perms", &empty_hidden_by_perms);
3723    // For the type/status filter dropdowns the template renders, we
3724    // pass a slug → verbose-name map and a sorted slug list.
3725    let mut type_slugs: Vec<(String, String)> = types
3726        .iter()
3727        .map(|t| (t.type_name.clone(), t.verbose_name.clone()))
3728        .collect();
3729    type_slugs.sort_by(|a, b| a.1.cmp(&b.1));
3730    ctx.insert("type_choices", &type_slugs);
3731
3732    // #65 — Move-to destination picker for the bulk action bar.
3733    // Every page (any depth) is a valid parent except the visible
3734    // selection itself; we expose the full tree pre-formatted with
3735    // an indent prefix so the dropdown reads as a tree. JS filters
3736    // out self/descendants of the actual selection at click time.
3737    let move_choices: Vec<serde_json::Value> = all_pages
3738        .iter()
3739        .map(|p| {
3740            let indent = "—".repeat(p.depth.max(1) as usize - 1);
3741            let label = if indent.is_empty() {
3742                p.title.clone()
3743            } else {
3744                format!("{indent} {}", p.title)
3745            };
3746            serde_json::json!({
3747                "id": p.id.get().copied(),
3748                "label": label,
3749                "path": p.path.clone(),
3750            })
3751        })
3752        .collect();
3753    ctx.insert("move_choices", &move_choices);
3754    // #107 — plugin-contributed per-row buttons. Hand the raw button
3755    // templates over; the template substitutes `{page_id}` per row.
3756    ctx.insert(
3757        "plugin_page_listing_buttons",
3758        &crate::hooks::page_listing_buttons_raw(),
3759    );
3760    // #134 — plugin-contributed bulk actions targeting `cms_page`.
3761    let plugin_bulk_actions: Vec<serde_json::Value> = crate::hooks::bulk_actions_for("cms_page")
3762        .into_iter()
3763        .map(|a| {
3764            serde_json::json!({
3765                "key": a.key,
3766                "label": a.label,
3767                "icon": a.icon,
3768                "danger": a.danger,
3769                "confirm_message": a.confirm_message,
3770                "action_url": a.action_url,
3771            })
3772        })
3773        .collect();
3774    ctx.insert("plugin_bulk_actions", &plugin_bulk_actions);
3775    // #438 — active non-default locales for the copy-to-locale bulk
3776    // action (the default locale already holds canonical content).
3777    let copy_locales: Vec<Locale> = Locale::objects()
3778        .where_(Locale::active.eq(true))
3779        .order_by(&[("sort_order", false), ("code", false)])
3780        .fetch(tenant.pool())
3781        .await
3782        .unwrap_or_default()
3783        .into_iter()
3784        .filter(|l| !l.is_default)
3785        .collect();
3786    ctx.insert("copy_locales", &copy_locales);
3787    render_with_csrf(&state, &headers, "rcms_admin/page_list.html", &mut ctx)
3788}
3789
3790/// Build a map of `page_id → public URL` for every row in `pages`.
3791/// Walks the list once in tree order (the list is already sorted by
3792/// `path` + `sort_order`), so each parent's URL is computed before
3793/// its children. Root pages with empty slug map to `/`.
3794/// Reassemble inline-panel rows from the posted form map.
3795///
3796/// Form keys are shaped `inline__<panel>__<row_idx>__<field>`. The
3797/// extractor iterates the spec's fields (so unknown / extraneous
3798/// keys are ignored), groups them by `row_idx`, and returns rows in
3799/// `row_idx` order so the handler can persist sort_order from the
3800/// position in the slice.
3801///
3802/// Rows are emitted whenever ANY of the spec's fields appears for
3803/// that index. The optional `inline__<panel>__<row_idx>____deleted`
3804/// sentinel hides a row entirely (so the editor can remove rows
3805/// without re-numbering everything).
3806/// The index placeholder in an inline panel's blank row template; the
3807/// editor's add button swaps it for the next free row index.
3808const INLINE_ROW_PLACEHOLDER: &str = "__IDX__";
3809
3810/// A loaded row value as the text an input shows.
3811fn inline_value_text(v: &serde_json::Value) -> String {
3812    match v {
3813        serde_json::Value::Null => String::new(),
3814        serde_json::Value::String(s) => s.clone(),
3815        serde_json::Value::Bool(b) => if *b { "true".to_owned() } else { String::new() },
3816        other => other.to_string(),
3817    }
3818}
3819
3820/// One row's widgets, named `inline__<panel>__<idx>__<field>` and filled
3821/// from `row` (blank for the add template).
3822fn inline_row_widgets(
3823    spec: &crate::page_type::InlinePanelSpec,
3824    idx: &str,
3825    row: Option<&serde_json::Map<String, serde_json::Value>>,
3826) -> Vec<crate::widget::Widget> {
3827    spec.row_widgets()
3828        .into_iter()
3829        .map(|mut w| {
3830            if let Some(v) = row.and_then(|r| r.get(&w.name)) {
3831                w.value = inline_value_text(v);
3832            }
3833            w.name = format!("inline__{}__{idx}__{}", spec.name, w.name);
3834            w
3835        })
3836        .collect()
3837}
3838
3839/// Template context for one inline panel: its spec, each loaded row as
3840/// named widgets (with the row's `id` and `__title`), and a blank row
3841/// the add button clones.
3842fn inline_panel_ctx(
3843    spec: &crate::page_type::InlinePanelSpec,
3844    rows: &[serde_json::Map<String, serde_json::Value>],
3845) -> serde_json::Value {
3846    // The blank row the add button clones comes first, flagged
3847    // `template`, so the editor renders every card from one loop.
3848    let mut cards: Vec<serde_json::Value> = vec![serde_json::json!({
3849        "template": true,
3850        "idx": INLINE_ROW_PLACEHOLDER,
3851        "id": "",
3852        "title": "",
3853        "widgets": inline_row_widgets(spec, INLINE_ROW_PLACEHOLDER, None),
3854    })];
3855    cards.extend(rows.iter().enumerate().map(|(i, row)| {
3856        serde_json::json!({
3857            "template": false,
3858            "idx": i,
3859            "id": row.get("id").map(inline_value_text).unwrap_or_default(),
3860            "title": row.get("__title").map(inline_value_text).unwrap_or_default(),
3861            "widgets": inline_row_widgets(spec, &i.to_string(), Some(row)),
3862        })
3863    }));
3864    let tab_slug = spec.tab.as_deref().map(|t| format!("inline-{}", slugify(t)));
3865    serde_json::json!({
3866        "spec": spec,
3867        "cards": cards,
3868        "row_count": rows.len(),
3869        "placeholder": INLINE_ROW_PLACEHOLDER,
3870        "tab_slug": tab_slug,
3871    })
3872}
3873
3874/// Template context for a per-row panel: only each row's id and title.
3875fn inline_panel_lazy_ctx(
3876    spec: &crate::page_type::InlinePanelSpec,
3877    rows: &[crate::page_type::InlineRowSummary],
3878    page_id: i64,
3879) -> serde_json::Value {
3880    let tab_slug = spec.tab.as_deref().map(|t| format!("inline-{}", slugify(t)));
3881    let cards: Vec<serde_json::Value> = rows
3882        .iter()
3883        .map(|r| serde_json::json!({ "template": false, "id": r.id.to_string(), "title": r.title }))
3884        .collect();
3885    serde_json::json!({
3886        "spec": spec,
3887        "cards": cards,
3888        "row_count": rows.len(),
3889        "tab_slug": tab_slug,
3890        // A page not saved yet has no rows to attach cards to.
3891        "endpoint": (page_id > 0).then(|| format!("/cms-admin/pages/{page_id}/inline/{}", spec.name)),
3892    })
3893}
3894
3895/// The page's type handler and the per-row panel named `panel`, or 404.
3896async fn per_row_panel(
3897    pool: &rustango::sql::Pool,
3898    page_id: i64,
3899    panel: &str,
3900) -> Result<(Box<dyn crate::page_type::PageTypeHandler>, crate::page_type::InlinePanelSpec), AdminError> {
3901    let page = Page::objects()
3902        .where_(Page::id.eq(page_id))
3903        .first(pool)
3904        .await?
3905        .ok_or(AdminError::NotFound(page_id))?;
3906    let pt = PageType::objects()
3907        .where_(PageType::id.eq(page.page_type_id))
3908        .first(pool)
3909        .await?
3910        .ok_or(AdminError::NotFound(page_id))?;
3911    let handler = find_handler(&pt.type_name).ok_or(AdminError::NotFound(page_id))?;
3912    let spec = handler
3913        .inline_panels(pool, page_id)
3914        .await?
3915        .into_iter()
3916        .find(|s| s.name == panel && s.per_row)
3917        .ok_or(AdminError::NotFound(page_id))?;
3918    Ok((handler, spec))
3919}
3920
3921/// `new-row` or a row id from the URL (not `new`: the route gate reads a POST ending in `/new` as adding a page).
3922fn inline_row_id(raw: &str) -> Result<Option<i64>, AdminError> {
3923    if raw == "new-row" {
3924        return Ok(None);
3925    }
3926    raw.parse::<i64>().map(Some).map_err(|_| AdminError::Validation(format!("bad row id `{raw}`")))
3927}
3928
3929#[derive(serde::Deserialize, Default)]
3930pub struct InlineCardQuery {
3931    /// The DOM prefix the card's field names carry (unique per open card).
3932    #[serde(default)]
3933    pub prefix: String,
3934}
3935
3936/// GET /cms-admin/pages/{id}/inline/{panel}/{row} — one card's fields
3937/// (`row` = `new-row` for a blank one), as an HTML fragment. Field names
3938/// carry `?prefix=` so two open cards never share an element id; the
3939/// editor strips it again when it saves.
3940pub async fn inline_card_body(
3941    State(state): State<super::AdminState>,
3942    tenant: Tenant,
3943    headers: HeaderMap,
3944    Path((page_id, panel, row)): Path<(i64, String, String)>,
3945    Query(q): Query<InlineCardQuery>,
3946) -> Result<Response, AdminError> {
3947    let pool = tenant.pool();
3948    let row_id = inline_row_id(&row)?;
3949    let (handler, spec) = per_row_panel(pool, page_id, &panel).await?;
3950    let Some(values) = handler.inline_row(pool, page_id, &panel, row_id).await? else {
3951        return Err(AdminError::NotFound(page_id));
3952    };
3953    let prefix: String = q.prefix.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-').collect();
3954    let widgets: Vec<crate::widget::Widget> = spec
3955        .row_widgets()
3956        .into_iter()
3957        .map(|mut w| {
3958            if let Some(v) = values.get(&w.name) {
3959                w.value = inline_value_text(v);
3960            }
3961            w.name = format!("{prefix}{}", w.name);
3962            w
3963        })
3964        .collect();
3965    let mut ctx = Context::new();
3966    ctx.insert("widgets", &widgets);
3967    ctx.insert("can_save", &(row_id.is_some() || spec.can_add));
3968    render_with_csrf(&state, &headers, "rcms_admin/_inline_card.html", &mut ctx)
3969}
3970
3971/// POST /cms-admin/pages/{id}/inline/{panel}/{row} — save one card.
3972/// JSON: `{ok, id, title}` or `{ok: false, errors: [{field, message}]}`.
3973pub async fn inline_card_save(
3974    tenant: Tenant,
3975    Path((page_id, panel, row)): Path<(i64, String, String)>,
3976    body: axum::body::Bytes,
3977) -> Result<Response, AdminError> {
3978    let pool = tenant.pool();
3979    let row_id = inline_row_id(&row)?;
3980    let (handler, spec) = per_row_panel(pool, page_id, &panel).await?;
3981    if row_id.is_none() && !spec.can_add {
3982        return Ok((axum::http::StatusCode::FORBIDDEN, axum::Json(serde_json::json!({ "ok": false }))).into_response());
3983    }
3984    let values: serde_json::Map<String, serde_json::Value> = super::admin_page::AdminForm::parse(&body)
3985        .to_map()
3986        .into_iter()
3987        .filter(|(k, _)| k != "_csrf")
3988        .map(|(k, v)| (k, serde_json::Value::String(v)))
3989        .collect();
3990    let out = match handler.save_inline_row(pool, page_id, &panel, row_id, &values).await? {
3991        crate::page_type::InlineRowSaved::Saved { id, title } => serde_json::json!({ "ok": true, "id": id, "title": title }),
3992        crate::page_type::InlineRowSaved::Invalid(errors) => serde_json::json!({
3993            "ok": false,
3994            "errors": errors.iter().map(|e| serde_json::json!({ "field": e.field, "message": e.message })).collect::<Vec<_>>(),
3995        }),
3996    };
3997    let status = if out["ok"] == true { axum::http::StatusCode::OK } else { axum::http::StatusCode::UNPROCESSABLE_ENTITY };
3998    Ok((status, axum::Json(out)).into_response())
3999}
4000
4001/// POST /cms-admin/pages/{id}/inline/{panel}/{row}/remove — remove one row.
4002pub async fn inline_card_remove(
4003    tenant: Tenant,
4004    Path((page_id, panel, row)): Path<(i64, String, String)>,
4005) -> Result<Response, AdminError> {
4006    let pool = tenant.pool();
4007    let Some(row_id) = inline_row_id(&row)? else {
4008        return Err(AdminError::NotFound(page_id));
4009    };
4010    let (handler, spec) = per_row_panel(pool, page_id, &panel).await?;
4011    let removed = spec.can_delete && handler.delete_inline_row(pool, page_id, &panel, row_id).await?;
4012    let status = if removed { axum::http::StatusCode::OK } else { axum::http::StatusCode::FORBIDDEN };
4013    Ok((status, axum::Json(serde_json::json!({ "ok": removed }))).into_response())
4014}
4015
4016/// POST /cms-admin/pages/{id}/inline/{panel}/order — `ids` is a JSON
4017/// array of row ids, first to last.
4018pub async fn inline_cards_order(
4019    tenant: Tenant,
4020    Path((page_id, panel)): Path<(i64, String)>,
4021    body: axum::body::Bytes,
4022) -> Result<Response, AdminError> {
4023    let pool = tenant.pool();
4024    let (handler, spec) = per_row_panel(pool, page_id, &panel).await?;
4025    if !spec.can_order {
4026        return Ok((axum::http::StatusCode::FORBIDDEN, axum::Json(serde_json::json!({ "ok": false }))).into_response());
4027    }
4028    let form = super::admin_page::AdminForm::parse(&body);
4029    let ids: Vec<i64> = serde_json::from_str(&form.text("ids")).unwrap_or_default();
4030    handler.reorder_inline_rows(pool, page_id, &panel, &ids).await?;
4031    Ok(axum::Json(serde_json::json!({ "ok": true })).into_response())
4032}
4033
4034fn extract_inline_panel_rows(
4035    form: &std::collections::HashMap<String, String>,
4036    spec: &crate::page_type::InlinePanelSpec,
4037) -> Vec<serde_json::Map<String, serde_json::Value>> {
4038    let mut by_idx: std::collections::BTreeMap<usize, serde_json::Map<String, serde_json::Value>> =
4039        std::collections::BTreeMap::new();
4040    let prefix = format!("inline__{}__", spec.name);
4041    let names: Vec<String> = spec.row_widgets().into_iter().map(|w| w.name).collect();
4042    for (key, value) in form {
4043        let Some(rest) = key.strip_prefix(&prefix) else {
4044            continue;
4045        };
4046        let Some((idx_str, field_name)) = rest.split_once("__") else {
4047            continue;
4048        };
4049        let Ok(idx) = idx_str.parse::<usize>() else {
4050            continue;
4051        };
4052        if field_name == "__deleted" && value == "1" {
4053            by_idx.remove(&idx);
4054            // Mark this index as tombstone — any later entries for
4055            // it get re-inserted into a fresh row that we then drop
4056            // at the end. Use a sentinel key to track.
4057            let mut row = serde_json::Map::new();
4058            row.insert("__deleted".to_owned(), serde_json::Value::Bool(true));
4059            by_idx.insert(idx, row);
4060            continue;
4061        }
4062        if field_name != "id" && !names.iter().any(|n| n == field_name) {
4063            continue;
4064        }
4065        let row = by_idx.entry(idx).or_default();
4066        if row.contains_key("__deleted") {
4067            continue;
4068        }
4069        row.insert(
4070            field_name.to_owned(),
4071            serde_json::Value::String(value.clone()),
4072        );
4073    }
4074    by_idx
4075        .into_iter()
4076        .filter_map(|(_, row)| {
4077            if row.contains_key("__deleted") {
4078                None
4079            } else {
4080                Some(row)
4081            }
4082        })
4083        .collect()
4084}
4085
4086fn build_live_url_map(pages: &[Page]) -> std::collections::HashMap<String, String> {
4087    let mut by_id: std::collections::HashMap<String, String> = std::collections::HashMap::new();
4088    for p in pages {
4089        let Some(pid) = p.id.get().copied() else {
4090            continue;
4091        };
4092        let url = match p.parent_id {
4093            None => {
4094                if p.slug.is_empty() {
4095                    "/".to_owned()
4096                } else {
4097                    format!("/{}", p.slug)
4098                }
4099            }
4100            Some(parent_id) => {
4101                let parent_url = by_id
4102                    .get(&parent_id.to_string())
4103                    .cloned()
4104                    .unwrap_or_else(|| "/".to_owned());
4105                if p.slug.is_empty() {
4106                    parent_url
4107                } else if parent_url == "/" {
4108                    format!("/{}", p.slug)
4109                } else {
4110                    format!("{}/{}", parent_url, p.slug)
4111                }
4112            }
4113        };
4114        // Stringify the id key so Tera's `m[page.id]` lookup works
4115        // when the serializer flattens to JSON.
4116        by_id.insert(pid.to_string(), url);
4117    }
4118    by_id
4119}
4120
4121/// GET /cms-admin/pages/new[?parent=<id>][&type=<page_type_id>] —
4122/// create flow. Two steps:
4123///
4124/// 1. Without `?type=`, render the page-type picker — a tile grid of
4125///    every creatable type (filtered to the parent's `allowed_child_
4126///    types` when `?parent=` is set). Picking a tile sends the
4127///    editor to step 2.
4128/// 2. With `?type=<id>`, render the page form with the chosen type
4129///    locked. The hidden `page_type_id` input carries it through to
4130///    the POST; the editor can NOT change it after this point.
4131///
4132/// Splitting the type selection out of the form is what makes the
4133/// "page-type is permanent" guarantee actually visible to authors —
4134/// once they're filling fields they're committed to the type.
4135#[derive(Debug, Deserialize)]
4136pub struct NewQuery {
4137    #[serde(default)]
4138    pub parent: Option<i64>,
4139    #[serde(default, rename = "type")]
4140    pub type_id: Option<i64>,
4141}
4142
4143pub async fn page_new_form(
4144    State(state): State<super::AdminState>,
4145    tenant: Tenant,
4146    headers: HeaderMap,
4147    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
4148    Query(q): Query<NewQuery>,
4149) -> Result<Response, AdminError> {
4150    let all_types: Vec<PageType> = PageType::objects().fetch(tenant.pool()).await?;
4151
4152    let (parent, allowed_types) = match q.parent {
4153        Some(pid) => {
4154            let parent_row = Page::objects()
4155                .where_(Page::id.eq(pid))
4156                .first(tenant.pool())
4157                .await?
4158                .ok_or(AdminError::NotFound(pid))?;
4159            let allowed = allowed_children_for(&parent_row, &all_types);
4160            (Some(parent_row), allowed)
4161        }
4162        // Root: only types that may legally be roots (#614).
4163        None => (None, allowed_root_types(&all_types)),
4164    };
4165
4166    // Step 1: no type picked yet → show the picker tile grid.
4167    let Some(type_id) = q.type_id else {
4168        // Enrich each PageType row with the registered handler's
4169        // `icon()` + `description()` so the picker can show them.
4170        // Plain `PageType` rows only carry table-level metadata
4171        // (type_name, verbose_name).
4172        #[derive(serde::Serialize)]
4173        struct PickerType<'a> {
4174            id: i64,
4175            type_name: &'a str,
4176            verbose_name: &'a str,
4177            icon: Option<&'static str>,
4178            description: Option<&'static str>,
4179        }
4180        let allowed_enriched: Vec<PickerType<'_>> = allowed_types
4181            .iter()
4182            .map(|t| {
4183                let handler = find_handler(&t.type_name);
4184                PickerType {
4185                    id: t.id.get().copied().unwrap_or_default(),
4186                    type_name: t.type_name.as_str(),
4187                    verbose_name: t.verbose_name.as_str(),
4188                    icon: handler.as_ref().and_then(|h| h.icon()),
4189                    description: handler.as_ref().and_then(|h| h.description()),
4190                }
4191            })
4192            .collect();
4193
4194        let mut ctx = Context::new();
4195        add_chrome(&mut ctx, &tenant, "pages", session_user.as_ref()).await;
4196        add_admin_theme(&mut ctx, tenant.pool()).await;
4197        ctx.insert("parent", &parent);
4198        ctx.insert("allowed_types", &allowed_enriched);
4199        return render_with_csrf(
4200            &state,
4201            &headers,
4202            "rcms_admin/page_type_picker.html",
4203            &mut ctx,
4204        );
4205    };
4206
4207    // Step 2: type picked → validate it sits in the allowed set for
4208    // this parent, then render the form with the type locked. Reject
4209    // out-of-set selections so a hand-crafted URL can't bypass the
4210    // parent's whitelist.
4211    let chosen_type = allowed_types
4212        .iter()
4213        .find(|t| t.id.get().copied() == Some(type_id))
4214        .cloned()
4215        .ok_or_else(|| {
4216            AdminError::Validation(format!(
4217                "page type {type_id} is not creatable under the chosen parent"
4218            ))
4219        })?;
4220
4221    let mut page_seed = empty_page_form_values();
4222    if let Some(obj) = page_seed.as_object_mut() {
4223        obj.insert("page_type_id".to_owned(), serde_json::json!(type_id));
4224    }
4225
4226    let mut ctx = Context::new();
4227    add_chrome(&mut ctx, &tenant, "pages", session_user.as_ref()).await;
4228    add_admin_theme(&mut ctx, tenant.pool()).await;
4229    ctx.insert("mode", "new");
4230    ctx.insert("parent", &parent);
4231    ctx.insert("chosen_type", &chosen_type);
4232    ctx.insert("page", &page_seed);
4233    let review_required = !session_user.as_ref().is_some_and(|u| u.is_superuser)
4234        && crate::workflow::review_workflow_for_type(tenant.pool(), type_id).await?.is_some();
4235    ctx.insert("review_required", &review_required);
4236    // Custom tabs — only the existing-page editor
4237    // calls the handler for them. New-page mode shows the built-in
4238    // tabs only.
4239    ctx.insert("extra_tabs", &Vec::<crate::page_type::TabSpec>::new());
4240    // The type's own fields, at their defaults, so they can be filled
4241    // in before the first save (#857).
4242    let handler = find_handler(&chosen_type.type_name);
4243    let widgets = match &handler {
4244        Some(h) => h.widgets(tenant.pool(), 0).await.unwrap_or_default(),
4245        None => Vec::new(),
4246    };
4247    insert_type_fields(&mut ctx, &state.tera, tenant.pool(), handler.as_deref(), widgets, 0, type_id, None).await;
4248    // Stream-field picker options — every registered block surfaces
4249    // as an option even on the new-page form (so authors can drop
4250    // blocks before the first save).
4251    ctx.insert(
4252        "picker_options",
4253        &crate::block::admin::picker_options(&state.tera),
4254    );
4255    ctx.insert("page_tags", &Vec::<String>::new());
4256    ctx.insert("page_tags_csv", "");
4257    ctx.insert("all_tags", &Vec::<serde_json::Value>::new());
4258    insert_category_choices(&mut ctx, tenant.pool(), None, None).await;
4259    render_with_csrf(&state, &headers, "rcms_admin/page_form.html", &mut ctx)
4260}
4261
4262/// Slugify a raw string for the `cms_page.slug` column. Mirrors the
4263/// JS-side slugifier in `page_form.html` so the auto-fill the
4264/// editor sees stays consistent with what the server would have
4265/// generated.
4266///
4267/// Lowercase ASCII, hyphens for whitespace, drop everything else,
4268/// collapse runs of hyphens, trim leading / trailing hyphens, cap
4269/// length at 60 chars.
4270pub(crate) fn slugify(raw: &str) -> String {
4271    let mut out = String::with_capacity(raw.len());
4272    let mut last_hyphen = true;
4273    for ch in raw.chars() {
4274        let c = ch.to_ascii_lowercase();
4275        if c.is_ascii_alphanumeric() {
4276            out.push(c);
4277            last_hyphen = false;
4278        } else if !last_hyphen {
4279            out.push('-');
4280            last_hyphen = true;
4281        }
4282    }
4283    while out.ends_with('-') {
4284        out.pop();
4285    }
4286    if out.len() > 60 {
4287        out.truncate(60);
4288        while out.ends_with('-') {
4289            out.pop();
4290        }
4291    }
4292    out
4293}
4294
4295/// Pick a slug that doesn't collide with any sibling of
4296/// `parent_id`. If `candidate` is free, return it unchanged. If
4297/// taken, try `<base>-copy`, then `<base>-copy-2`, `<base>-copy-3`,
4298/// … up to a safety limit of 50 attempts (past which we surface an
4299/// error so the editor sees the collision).
4300///
4301/// Roots compare against other roots (`parent_id IS NULL`); children
4302/// compare against same-parent siblings only.
4303pub(crate) async fn dedup_slug_under_parent(
4304    pool: &rustango::sql::Pool,
4305    parent_id: Option<i64>,
4306    candidate: &str,
4307) -> Result<String, AdminError> {
4308    let taken: std::collections::HashSet<String> = {
4309        let q = Page::objects();
4310        let rows = match parent_id {
4311            Some(pid) => q.where_(Page::parent_id.eq(pid)).fetch(pool).await?,
4312            None => q.where_(Page::parent_id.is_null()).fetch(pool).await?,
4313        };
4314        rows.into_iter().map(|p| p.slug).collect()
4315    };
4316
4317    if !taken.contains(candidate) {
4318        return Ok(candidate.to_owned());
4319    }
4320    let with_copy = format!("{candidate}-copy");
4321    if !taken.contains(&with_copy) {
4322        return Ok(with_copy);
4323    }
4324    for n in 2..50_u32 {
4325        let trial = format!("{candidate}-copy-{n}");
4326        if !taken.contains(&trial) {
4327            return Ok(trial);
4328        }
4329    }
4330    Err(AdminError::Validation(format!(
4331        "could not find a free slug for “{candidate}” after 50 -copy attempts"
4332    )))
4333}
4334
4335/// Whether a root page already has the empty slug, i.e. serves "/".
4336async fn front_page_taken(pool: &rustango::sql::Pool) -> Result<bool, AdminError> {
4337    let n = Page::objects()
4338        .where_(Page::parent_id.is_null())
4339        .where_(Page::slug.eq(String::new()))
4340        .count(pool)
4341        .await?;
4342    Ok(n > 0)
4343}
4344
4345/// The page editor's Categories field. A failed lookup leaves the
4346/// field out rather than failing the form. `posted` (the form's raw
4347/// value, after a refused save) checks those ids instead of the stored.
4348async fn insert_category_choices(
4349    ctx: &mut tera::Context,
4350    pool: &rustango::sql::Pool,
4351    page_id: Option<i64>,
4352    posted: Option<&str>,
4353) {
4354    let (mut groups, mut checked) = match crate::category::assign::editor_groups(pool, page_id).await {
4355        Ok(v) => v,
4356        Err(e) => {
4357            tracing::warn!(error = %e, "category choices not loaded; the field is hidden");
4358            Default::default()
4359        }
4360    };
4361    if let Some(raw) = posted {
4362        let ids = crate::category::assign::parse_id_list(raw);
4363        let mut ticked = Vec::new();
4364        for o in groups.iter_mut().flat_map(|g| g.options.iter_mut()) {
4365            o.checked = ids.contains(&o.id);
4366            if o.checked {
4367                ticked.push(o.id.to_string());
4368            }
4369        }
4370        checked = serde_json::to_string(&ticked).unwrap_or_else(|_| "[]".to_owned());
4371    }
4372    ctx.insert("category_groups", &groups);
4373    ctx.insert("page_category_ids", &checked);
4374}
4375
4376/// POST /cms-admin/pages/new — submit. Dispatches to
4377/// `Page::create_root` when no parent_id is in the form, otherwise
4378/// `Page::create_child`. Both paths compute path/depth/sort_order
4379/// and enforce the type whitelist.
4380pub async fn page_new_submit(
4381    State(_state): State<super::AdminState>,
4382    tenant: Tenant,
4383    headers: HeaderMap,
4384    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
4385    Form(form_map): Form<std::collections::HashMap<String, String>>,
4386) -> Result<Response, AdminError> {
4387    // The raw map also carries the type's own fields (#857), saved once
4388    // the page exists.
4389    let form: PageForm = serde_urlencoded::from_str(
4390        &serde_urlencoded::to_string(&form_map).unwrap_or_default(),
4391    )
4392    .map_err(|e| AdminError::Validation(format!("page form: {e}")))?;
4393    // #614 — a type that names `allowed_parent_types` may only live under one
4394    // of those parents, so it can never be a root. The picker now hides such
4395    // types at the root, but `page_type_id` arrives in the form (and the
4396    // picker is reachable as `?type=<id>`), so re-check it here rather than
4397    // trusting the UI.
4398    if form.parent_id.is_none() {
4399        let types = PageType::objects().fetch(tenant.pool()).await?;
4400        if let Some(row) = types
4401            .iter()
4402            .find(|t| t.id.get().copied() == Some(form.page_type_id))
4403        {
4404            let parents = row.allowed_parents();
4405            if !parents.is_empty() {
4406                return Err(AdminError::Validation(format!(
4407                    "`{}` can't be a root page — it may only be created under: {}",
4408                    row.type_name,
4409                    parents.join(", ")
4410                )));
4411            }
4412        }
4413    }
4414
4415    // An empty slug on a root page makes it the front page ("/"), as the
4416    // form's hint says — unless another root already is; otherwise the
4417    // slug comes from the title.
4418    let mut effective_slug = if !form.slug.trim().is_empty() {
4419        slugify(&form.slug)
4420    } else if form.parent_id.is_none() && !front_page_taken(tenant.pool()).await? {
4421        String::new()
4422    } else {
4423        slugify(&form.title)
4424    };
4425    if !effective_slug.is_empty() {
4426        effective_slug =
4427            dedup_slug_under_parent(tenant.pool(), form.parent_id, &effective_slug).await?;
4428    }
4429
4430    // A new page that would go live takes the publish right (#761, as on
4431    // edit), and a type with a review workflow goes live only through
4432    // it. Decided before the insert and saved as a draft instead, so the
4433    // page is never live for a moment and nothing typed is lost.
4434    let intended = derive_scheduled_status(form.parsed_status().as_str(), form.parsed_go_live_at());
4435    let mut held_back: Option<String> = None;
4436    if let Some(user) = session_user.as_ref().filter(|u| !u.is_superuser) {
4437        if crate::page::PageStatus::str_goes_live(crate::page::PageStatus::Draft.as_str(), &intended) {
4438            let uid = user.id.get().copied().unwrap_or_default();
4439            let req = super::route_perms::Requirement {
4440                codename: "cms_page.publish".to_owned(),
4441                page: form.parent_id.map(|pid| (pid, crate::permissions::Action::Publish)),
4442            };
4443            if let Some(wf) = crate::workflow::review_workflow_for_type(tenant.pool(), form.page_type_id).await? {
4444                held_back = Some(super::i18n::tr(
4445                    &headers,
4446                    "Saved as a draft: pages of this type go live after review (“{workflow}”). Click Submit for review.",
4447                    &[("workflow", wf.name.as_str())],
4448                ));
4449            } else if !super::route_perms::allows_id(tenant.pool(), uid, false, &req).await {
4450                held_back = Some(super::i18n::tr(
4451                    &headers,
4452                    "Saved as a draft: you don't have permission to publish pages here.",
4453                    &[],
4454                ));
4455            }
4456        }
4457    }
4458
4459    let new = NewPage::new(
4460        form.page_type_id,
4461        form.title.clone(),
4462        effective_slug.clone(),
4463    )
4464    .with_status(if held_back.is_some() { crate::page::PageStatus::Draft } else { form.parsed_status() })
4465    .with_seo(form.seo_title.clone(), form.seo_description.clone());
4466
4467    let mut page = match form.parent_id {
4468        Some(pid) => {
4469            let parent = Page::objects()
4470                .where_(Page::id.eq(pid))
4471                .first(tenant.pool())
4472                .await?
4473                .ok_or(AdminError::NotFound(pid))?;
4474            Page::create_child(&tenant, &parent, new).await?
4475        }
4476        None => Page::create_root(&tenant, new).await?,
4477    };
4478
4479    // Apply the non-tree-shape fields that NewPage doesn't carry
4480    // (robots, sitemap_priority) via a follow-up save.
4481    page.robots_index = form.parsed_robots_index();
4482    page.sitemap_priority = form.parsed_sitemap_priority();
4483    page.theme_id = form.theme_id.flatten();
4484    // A held-back page keeps no go-live date: a dated draft would be
4485    // scheduled, and go live without the review.
4486    page.go_live_at = if held_back.is_some() { None } else { form.parsed_go_live_at() };
4487    page.expire_at = form.parsed_expire_at();
4488    page.status = derive_scheduled_status(&page.status, page.go_live_at);
4489    page.show_in_menus = form.parsed_show_in_menus();
4490    page.preview_path = form.preview_path.trim().to_owned();
4491    page.template_override = form.template_override.trim().to_owned();
4492    // #183 — social sharing fields.
4493    page.og_title = form.og_title.clone();
4494    page.og_description = form.og_description.clone();
4495    page.og_image_media_id = form.og_image_media_id;
4496    if let Some(tc) = form.twitter_card.as_deref() {
4497        if matches!(tc, "summary" | "summary_large_image") {
4498            page.twitter_card = tc.to_owned();
4499        }
4500    }
4501    page.save(tenant.pool()).await?;
4502    let new_id = page.id.get().copied().unwrap_or_default();
4503    // Tags and categories are on the new-page form too; they used to be
4504    // dropped here, and only an edit saved them.
4505    if let Some(raw) = form.tags.as_deref().filter(|t| !t.trim().is_empty()) {
4506        let names: Vec<String> = raw.split(',').map(str::to_owned).collect();
4507        crate::page_tag::replace_tags(tenant.pool(), new_id, &names).await?;
4508    }
4509    crate::category::assign::save_from_form(tenant.pool(), new_id, form.categories.as_deref()).await?;
4510    let page_type: Option<PageType> = PageType::objects()
4511        .where_(PageType::id.eq(page.page_type_id))
4512        .first(tenant.pool())
4513        .await?;
4514    save_type_content(tenant.pool(), page_type.as_ref(), page.page_type_id, new_id, &form_map).await?;
4515
4516    // Capture revision #1 for this page so the history
4517    // panel has something to show from the moment a page is born.
4518    crate::revision::capture(tenant.pool(), &page, None)
4519        .await
4520        .log_warn("revision not captured; the history has a gap");
4521    reindex_from_form(tenant.pool(), &tenant.org.slug, new_id, &form_map).await;
4522
4523    // Public render cache (rustango::cache_page::CachePageLayer)
4524    // expires on TTL; no manual invalidation needed here.
4525    let message = held_back.unwrap_or_else(|| {
4526        super::i18n::tr(&headers, "Created page “{title}”.", &[("title", page.title.as_str())])
4527    });
4528    redirect_after_page_save(
4529        &form.action,
4530        page.id.get().copied().unwrap_or_default(),
4531        page.parent_id,
4532        &message,
4533        &headers,
4534    )
4535}
4536
4537/// GET /cms-admin/pages/{id}/edit — load and render the form.
4538/// Query string for the page-edit form. `locale=<code>` flips the
4539/// editor into translation mode for that locale; absent OR pointing
4540/// at the default locale shows the canonical edit form.
4541#[derive(Debug, Deserialize, Default)]
4542pub struct EditQuery {
4543    #[serde(default)]
4544    pub locale: Option<String>,
4545}
4546
4547pub async fn page_edit_form(
4548    State(state): State<super::AdminState>,
4549    tenant: Tenant,
4550    headers: HeaderMap,
4551    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
4552    Path(id): Path<i64>,
4553    Query(q): Query<EditQuery>,
4554) -> Result<Response, AdminError> {
4555    render_page_edit_form(&state, tenant.pool(), &tenant.org, &headers, session_user, id, q, None).await
4556}
4557
4558/// A save refused because another editor changed the same fields
4559/// (#903): the form is shown again with the editor's values, the
4560/// conflicts listed, and a baseline of the row as it is now.
4561struct EditConflict {
4562    conflicts: Vec<crate::page_baseline::FieldConflict>,
4563    /// The stored row with the editor's changes on top.
4564    page: Page,
4565    /// The posted form, for the tags and the type's own fields.
4566    form: std::collections::HashMap<String, String>,
4567}
4568
4569async fn render_page_edit_form(
4570    state: &super::AdminState,
4571    pool: &rustango::sql::Pool,
4572    org: &rustango::tenancy::Org,
4573    headers: &HeaderMap,
4574    session_user: Option<rustango::tenancy::auth::User>,
4575    id: i64,
4576    q: EditQuery,
4577    conflict: Option<EditConflict>,
4578) -> Result<Response, AdminError> {
4579    let page = Page::objects()
4580        .where_(Page::id.eq(id))
4581        .first(pool)
4582        .await?
4583        .ok_or(AdminError::NotFound(id))?;
4584
4585    // #75 — alias proxy. Editing an alias means editing the source;
4586    // bounce the editor there so they're never tweaking a row that
4587    // can't actually accept content changes. Flash explains the
4588    // redirect so it isn't surprising.
4589    if let Some(source_id) = page.alias_of {
4590        return redirect_named_with_params_and_message_args(
4591            "rcms-admin:pages:edit",
4592            &[("id", source_id.to_string())],
4593            MsgLevel::Info,
4594            "Editing the source — alias “{title}” shares content with this row.",
4595            &[("title", page.title.as_str())],
4596            &headers,
4597        );
4598    }
4599
4600    // Load all active locales for the picker + translation lookup.
4601    let locales: Vec<Locale> = Locale::objects()
4602        .where_(Locale::active.eq(true))
4603        .order_by(&[("is_default", false), ("code", false)])
4604        .fetch(pool)
4605        .await?;
4606    let editing_locale: Option<Locale> = match q.locale.as_deref() {
4607        Some(code) if !code.is_empty() => locales.iter().find(|l| l.code == code).cloned(),
4608        _ => None,
4609    };
4610    let translation_mode = editing_locale
4611        .as_ref()
4612        .map(|l| !l.is_default)
4613        .unwrap_or(false);
4614    let pending = crate::pending_change::for_page(pool, id).await?;
4615    let existing_translations = if translation_mode {
4616        let lid = editing_locale
4617            .as_ref()
4618            .and_then(|l| l.id.get().copied())
4619            .unwrap_or(0);
4620        crate::translation::fetch_for(pool, id, lid)
4621            .await
4622            .unwrap_or_default()
4623    } else {
4624        std::collections::HashMap::new()
4625    };
4626
4627    // Theme picker dropdown options.
4628    let themes_for_picker: Vec<crate::theme::Theme> = crate::theme::Theme::objects()
4629        .order_by(&[("name", false)])
4630        .fetch(pool)
4631        .await?;
4632
4633    // Page type is permanent — assigned once at create-time, never
4634    // reassigned. We surface the type as a read-only chip in the
4635    // form so authors can still see what they're editing; the edit
4636    // submit handler also strips `page_type_id` from its canonical
4637    // keys as a defense-in-depth measure.
4638    let chosen_type: PageType = PageType::objects()
4639        .where_(PageType::id.eq(page.page_type_id))
4640        .first(pool)
4641        .await?
4642        .ok_or_else(|| {
4643            AdminError::Validation(format!(
4644                "page_type_id {} on cms_page row has no cms_page_type row",
4645                page.page_type_id
4646            ))
4647        })?;
4648
4649    // Public URL for the "View live" link in the edit form chrome.
4650    let ancestors = page.ancestors(pool).await.unwrap_or_default();
4651    let mut segments: Vec<&str> = ancestors
4652        .iter()
4653        .filter(|a| !a.slug.is_empty())
4654        .map(|a| a.slug.as_str())
4655        .collect();
4656    if !page.slug.is_empty() {
4657        segments.push(page.slug.as_str());
4658    }
4659    let live_url = if segments.is_empty() {
4660        "/".to_owned()
4661    } else {
4662        format!("/{}", segments.join("/"))
4663    };
4664
4665    // Fetch the revision history for the sidebar
4666    // panel. Sorted newest first, capped at 20 for the panel; older
4667    // revisions stay queryable via direct URL.
4668    //
4669    // The cap is applied in SQL (`.limit`), not after the fetch: every
4670    // `Revision` row carries a full JSON `snapshot` of the page, so
4671    // fetching the whole history to show 20 grew the edit-form cost with
4672    // every save (a page edited 300 times pulled 300 page snapshots).
4673    let revisions: Vec<crate::revision::Revision> = crate::revision::Revision::objects()
4674        .where_(crate::revision::Revision::page_id.eq(id))
4675        .order_by(&[("sequence", true)]) // desc
4676        .limit(20)
4677        .fetch(pool)
4678        .await?;
4679
4680    // Sort existing translations into "core" (title / seo_title /
4681    // seo_description) and "extra" so the template can render the
4682    // core fields side-by-side with the canonical, and list the rest
4683    // as editable rows below.
4684    let core_fields = ["title", "seo_title", "seo_description"];
4685    let core_translations: std::collections::HashMap<String, String> = core_fields
4686        .iter()
4687        .map(|f| {
4688            (
4689                (*f).to_owned(),
4690                existing_translations.get(*f).cloned().unwrap_or_default(),
4691            )
4692        })
4693        .collect();
4694    let mut extra_translations: Vec<(String, String)> = existing_translations
4695        .iter()
4696        .filter(|(k, _)| !core_fields.contains(&k.as_str()))
4697        .map(|(k, v)| (k.clone(), v.clone()))
4698        .collect();
4699    extra_translations.sort_by(|a, b| a.0.cmp(&b.0));
4700
4701    let mut ctx = Context::new();
4702    add_chrome_for(&mut ctx, pool, org, "pages", session_user.as_ref()).await;
4703    add_admin_theme(&mut ctx, pool).await;
4704    ctx.insert("mode", "edit");
4705    ctx.insert("parent", &Option::<Page>::None);
4706    ctx.insert("chosen_type", &chosen_type);
4707    ctx.insert("page", &page);
4708    ctx.insert("live_url", &live_url);
4709    // Headless preview: when the tenant has configured a decoupled
4710    // frontend, mint a token now and hand the editor a link that carries
4711    // it. The mint endpoint is inside the session-gated admin, so an
4712    // editor could otherwise only use preview by copying a token by hand
4713    // — which meant decoupled sites had no working preview at all.
4714    //
4715    // Minted per render rather than per click: the token is short-lived
4716    // and page-scoped, and generating it here keeps the link a plain
4717    // anchor instead of requiring JS. `None` (no frontend set) simply
4718    // hides the action.
4719    // The site-wide template, which the page may override. A lookup
4720    // failure is not fatal — it costs the preview action, not the editor.
4721    let site_preview_base = match crate::preview_url::configured_base(pool).await {
4722        Ok(base) => base,
4723        Err(e) => {
4724            tracing::warn!(
4725                target: "rustango_cms::admin",
4726                error = %e,
4727                "headless preview setting lookup failed",
4728            );
4729            None
4730        }
4731    };
4732    // Minted only when there is somewhere to send it: a page with no
4733    // override on a tenant with no frontend has no preview URL at all.
4734    let headless_preview_url = if site_preview_base.is_some() || !page.preview_path.trim().is_empty()
4735    {
4736        let token = crate::preview_token::mint(
4737            &tenant_key(org)?,
4738            id,
4739            chrono::Utc::now().timestamp() + PREVIEW_TOKEN_TTL_SECS,
4740        );
4741        crate::preview_url::for_page(
4742            site_preview_base.as_deref(),
4743            &page.preview_path,
4744            &token,
4745            id,
4746            &page.url_path,
4747        )
4748    } else {
4749        None
4750    };
4751    ctx.insert("headless_preview_url", &headless_preview_url);
4752    // #532 — full ancestor trail for the editor breadcrumb (each crumb links
4753    // to that level's children list); plus the immediate parent for "back".
4754    let ancestor_crumbs: Vec<serde_json::Value> = ancestors
4755        .iter()
4756        .map(|a| serde_json::json!({ "id": a.id.get().copied(), "title": a.title }))
4757        .collect();
4758    ctx.insert("ancestors", &ancestor_crumbs);
4759    ctx.insert(
4760        "parent_crumb",
4761        &ancestors
4762            .last()
4763            .map(|a| serde_json::json!({ "id": a.id.get().copied(), "title": a.title })),
4764    );
4765    // #107 — plugin-contributed kebab entries. Server-side substitutes the
4766    // page id into each entry's `href_template`.
4767    ctx.insert(
4768        "plugin_page_action_menu_items",
4769        &crate::hooks::page_action_menu_items(id),
4770    );
4771    // #140 — plugin-contributed page header buttons (next to Save).
4772    ctx.insert(
4773        "plugin_page_header_buttons",
4774        &crate::hooks::page_header_buttons(id),
4775    );
4776    // #115 — is the viewing user subscribed to publish events on
4777    // this page? Drives the Subscribe / Unsubscribe toggle on the
4778    // Status field.
4779    let is_subscribed = match session_user.as_ref().and_then(|u| u.id.get().copied()) {
4780        Some(uid) => crate::page_subscription::is_subscribed(pool, id, uid)
4781            .await
4782            .unwrap_or(false),
4783        None => false,
4784    };
4785    ctx.insert("is_subscribed", &is_subscribed);
4786    // #189 — page tags.
4787    let page_tags: Vec<String> = crate::page_tag::tags_for_page(pool, id)
4788        .await
4789        .unwrap_or_default()
4790        .into_iter()
4791        .map(|t| t.name)
4792        .collect();
4793    let page_tags_csv = page_tags.join(", ");
4794    ctx.insert("page_tags", &page_tags);
4795    ctx.insert(
4796        "page_tags_csv",
4797        conflict.as_ref().and_then(|c| c.form.get("tags")).unwrap_or(&page_tags_csv),
4798    );
4799    // #903 — what this form loaded, so its save can tell this editor's
4800    // changes from anyone else's.
4801    ctx.insert(
4802        "page_baseline",
4803        &crate::page_baseline::Baseline::of(&org.slug, &page).token(),
4804    );
4805    let all_tags = crate::page_tag::all_tags(pool)
4806        .await
4807        .unwrap_or_default()
4808        .into_iter()
4809        .map(|(name, count)| serde_json::json!({ "name": name, "count": count }))
4810        .collect::<Vec<_>>();
4811    ctx.insert("all_tags", &all_tags);
4812    insert_category_choices(
4813        &mut ctx,
4814        pool,
4815        Some(id),
4816        conflict
4817            .as_ref()
4818            .and_then(|c| c.form.get(crate::category::assign::FORM_KEY))
4819            .map(String::as_str),
4820    )
4821    .await;
4822    // #146/#419 — inbound usage ("what links here"), aggregated per
4823    // referrer with resolved titles + a "used in N places" count.
4824    // Best-effort; failure leaves the panel empty.
4825    let usage =
4826        crate::reference_index::usage_summary(pool, crate::reference_index::KIND_PAGE, id)
4827            .await;
4828    ctx.insert("usage", &usage);
4829
4830    // #116 — accessibility heuristics. Run server-side on every
4831    // page editor open. `body_html` comes from the handler's
4832    // `load_extension`-rendered HTML when one is available; only the
4833    // canonical Page fields are checked, since extension shape is
4834    // per-handler.
4835    let a11y_violations = crate::a11y::check_page(&page, None);
4836    let (a11y_errors, a11y_warnings, a11y_infos) = crate::a11y::count_by_severity(&a11y_violations);
4837    ctx.insert("a11y_violations", &a11y_violations);
4838    ctx.insert("a11y_errors", &a11y_errors);
4839    ctx.insert("a11y_warnings", &a11y_warnings);
4840    ctx.insert("a11y_infos", &a11y_infos);
4841    // #417 — extensible content/SEO checks (registry-driven). Rendered
4842    // in a sibling "Content & SEO" panel; same Severity buckets as a11y.
4843    let mut content_findings = crate::content_checks::run_all(&page);
4844    // No share image chosen is fine when the page has a photo: the public
4845    // page uses it (see `meta_tags::fallback_share_image`).
4846    if content_findings.iter().any(|f| f.code == "missing_og_image")
4847        && crate::meta_tags::fallback_share_image(pool, &page).await.is_some()
4848    {
4849        content_findings.retain(|f| f.code != "missing_og_image");
4850    }
4851    let (content_errors, content_warnings, content_infos) =
4852        crate::content_checks::count_by_severity(&content_findings);
4853    ctx.insert("content_findings", &content_findings);
4854    ctx.insert("content_errors", &content_errors);
4855    ctx.insert("content_warnings", &content_warnings);
4856    ctx.insert("content_infos", &content_infos);
4857    ctx.insert("revisions", &revisions);
4858
4859    // #192 — audit-log timeline for this page. Capped at 100 entries
4860    // for the inline table; the full set is downloadable via the CSV
4861    // export endpoint linked alongside the table.
4862    let log_entries = crate::page_log::for_page(pool, id, Some(100))
4863        .await
4864        .unwrap_or_default();
4865    let log_user_ids: std::collections::BTreeSet<i64> =
4866        log_entries.iter().filter_map(|e| e.actor_id).collect();
4867    let log_users: std::collections::HashMap<i64, String> = if log_user_ids.is_empty() {
4868        std::collections::HashMap::new()
4869    } else {
4870        rustango::tenancy::auth::User::objects()
4871            .where_(
4872                rustango::tenancy::auth::User::id
4873                    .is_in(log_user_ids.into_iter().collect::<Vec<_>>()),
4874            )
4875            .fetch(pool)
4876            .await
4877            .unwrap_or_default()
4878            .into_iter()
4879            .filter_map(|u| u.id.get().copied().map(|id| (id, u.username)))
4880            .collect()
4881    };
4882    let log_view: Vec<serde_json::Value> = log_entries
4883        .iter()
4884        .map(|e| {
4885            serde_json::json!({
4886                "id": e.id.get().copied(),
4887                "action": e.action,
4888                "actor_id": e.actor_id,
4889                "actor_username": e.actor_id.and_then(|uid| log_users.get(&uid).cloned()),
4890                "message": e.message,
4891                "created_at": e.created_at.get().copied(),
4892            })
4893        })
4894        .collect();
4895    ctx.insert("page_log", &log_view);
4896
4897    ctx.insert("locales", &locales);
4898    ctx.insert("editing_locale", &editing_locale);
4899    ctx.insert("translation_mode", &translation_mode);
4900    ctx.insert("core_translations", &core_translations);
4901    ctx.insert("extra_translations", &extra_translations);
4902    ctx.insert("themes_for_picker", &themes_for_picker);
4903
4904    // Extension fields contributed by the page-type handler — typed
4905    // body / hero / etc. The admin form renders one widget per entry
4906    // alongside the canonical fields so authors edit "Content" in
4907    // one place.
4908    // Resolve the registered handler for this page's type once —
4909    // both `extension_fields` and `display_fields` come off the
4910    // same instance.
4911    // Reuses `chosen_type` (fetched above for the read-only type chip)
4912    // instead of re-querying the identical `cms_page_type` row.
4913    let resolved_handler: Option<Box<dyn crate::page_type::PageTypeHandler>> =
4914        find_handler(&chosen_type.type_name);
4915
4916    // Which preview surface the pane should render: the iframe, the JSON
4917    // body, or a plain "not available" notice.
4918    //
4919    // "No template" is not just an empty string — a non-empty name that
4920    // was never registered in Tera fails identically at render time, so
4921    // both cases have to count or the pane would lazy-load an iframe
4922    // that can only 500.
4923    let preview_mode = {
4924        let kind = crate::page_view::kind_for(&chosen_type);
4925        let template_renders = !chosen_type.default_template.trim().is_empty()
4926            && state
4927                .tera
4928                .get_template_names()
4929                .any(|n| n == chosen_type.default_template);
4930        if kind.serves_json() && !kind.serves_html() {
4931            "json"
4932        } else if template_renders {
4933            "html"
4934        } else {
4935            "none"
4936        }
4937    };
4938    ctx.insert("preview_mode", preview_mode);
4939
4940    // Pull widgets via the rich-typed `widgets()` method, which by
4941    // default delegates to the legacy `extension_fields()` shape
4942    // for handlers that haven't migrated. Returns `Vec<Widget>`
4943    // directly so new handlers can use the full 26-kind catalog
4944    // (Date, Color, Radio, Checkboxes, MultiSelect, Custom, …).
4945    let raw_widgets: Vec<crate::widget::Widget> = match &resolved_handler {
4946        Some(h) => h.widgets(pool, id).await.unwrap_or_default(),
4947        None => Vec::new(),
4948    };
4949
4950    // #416 — content metrics (word count / reading time / readability)
4951    // from the content-bearing widget values, so the editor shows them
4952    // without opening the preview. Computed before the widgets are
4953    // mutated for rendering (chooser options etc.).
4954    let content_metrics =
4955        crate::metrics::analyze(&crate::metrics::collect_widget_text(&raw_widgets));
4956    ctx.insert("content_metrics", &content_metrics);
4957
4958    // #i18n — per-leaf StreamField translation rows. In translation mode,
4959    // walk each Stream widget's canonical JSON, enumerate every
4960    // translatable text leaf (recursively, incl. nested blocks), group by
4961    // block instance, and prefill each from the existing per-locale
4962    // overrides. `raw_widgets` still holds canonical values here (it is
4963    // mutated for chooser-option rendering further below).
4964    if translation_mode {
4965        let mut stream_translations: Vec<serde_json::Value> = Vec::new();
4966        let mut leaf_paths: std::collections::HashSet<String> = std::collections::HashSet::new();
4967        for w in &raw_widgets {
4968            if !matches!(w.kind, crate::widget::WidgetKind::Stream) {
4969                continue;
4970            }
4971            let base: serde_json::Value = serde_json::from_str(&w.value)
4972                .unwrap_or_else(|_| serde_json::Value::Array(Vec::new()));
4973            let leaves = crate::block::translate::collect_translatable_leaves(&w.name, &base);
4974            if leaves.is_empty() {
4975                continue;
4976            }
4977            let mut groups: Vec<serde_json::Value> = Vec::new();
4978            let mut cur_id = String::new();
4979            for leaf in &leaves {
4980                leaf_paths.insert(leaf.path.clone());
4981                let row = serde_json::json!({
4982                    "path": leaf.path,
4983                    "widget_kind": leaf.widget_kind.as_tag(),
4984                    "field_label": leaf.field_label,
4985                    "canonical": leaf.canonical_text,
4986                    "canonical_html": translation_canonical_html(leaf.widget_kind.as_tag(), &leaf.canonical_text),
4987                    "value": existing_translations.get(&leaf.path).cloned().unwrap_or_default(),
4988                });
4989                if leaf.block_id != cur_id {
4990                    cur_id.clone_from(&leaf.block_id);
4991                    groups.push(serde_json::json!({
4992                        "block_type": leaf.block_type,
4993                        "block_label": leaf.block_label,
4994                        "block_id": leaf.block_id,
4995                        "depth": leaf.depth,
4996                        "leaves": [row],
4997                    }));
4998                } else if let Some(arr) = groups
4999                    .last_mut()
5000                    .and_then(|g| g.get_mut("leaves"))
5001                    .and_then(|v| v.as_array_mut())
5002                {
5003                    arr.push(row);
5004                }
5005            }
5006            stream_translations.push(serde_json::json!({ "field": w.name, "label": w.label, "groups": groups }));
5007        }
5008        // A code-made type's own text fields (a home page's heading, …).
5009        // Flat keys — the field's name — which the renderer overlays onto
5010        // `extension.<name>` (`translation::overlay_translations`). They
5011        // were translatable but never listed, so the form could not reach
5012        // them.
5013        let field_rows: Vec<serde_json::Value> = raw_widgets
5014            .iter()
5015            .filter(|w| {
5016                use crate::widget::WidgetKind as K;
5017                matches!(w.kind, K::Text | K::Textarea | K::Markdown | K::RichText)
5018                    && !w.name.starts_with(crate::page_builder::compile::FIELD_PREFIX)
5019            })
5020            .map(|w| {
5021                leaf_paths.insert(w.name.clone());
5022                serde_json::json!({
5023                    "path": w.name,
5024                    "widget_kind": w.kind.as_tag(),
5025                    "field_label": w.label,
5026                    "canonical": w.value,
5027                    "canonical_html": translation_canonical_html(w.kind.as_tag(), &w.value),
5028                    "value": existing_translations.get(&w.name).cloned().unwrap_or_default(),
5029                })
5030            })
5031            .collect();
5032        if !field_rows.is_empty() {
5033            stream_translations.insert(
5034                0,
5035                serde_json::json!({
5036                    "field": "fields",
5037                    "label": super::i18n::tr(&headers, "Fields", &[]),
5038                    "groups": [{
5039                        "block_type": "fields",
5040                        "block_label": "",
5041                        "block_id": "fields",
5042                        "depth": 0,
5043                        "leaves": field_rows,
5044                    }],
5045                }),
5046            );
5047        }
5048        // #567 — page-builder body leaves (fixed fields, group members,
5049        // repeater/flex zone blocks). Listed as one more translatable
5050        // "field" alongside the StreamField leaves, keyed `builder.<…>`.
5051        let (builder_groups, builder_paths) =
5052            builder_translation_groups(pool, id, page.page_type_id, &existing_translations)
5053                .await;
5054        if !builder_groups.is_empty() {
5055            leaf_paths.extend(builder_paths);
5056            stream_translations
5057                .push(serde_json::json!({
5058                    "field": "builder",
5059                    "label": super::i18n::tr(&headers, "Fields", &[]),
5060                    "groups": builder_groups,
5061                }));
5062        }
5063        // Don't also list dotted leaf paths under the raw "custom keys"
5064        // section (orphaned paths whose block was deleted still appear
5065        // there so editors can clear them).
5066        extra_translations.retain(|(k, _)| !leaf_paths.contains(k));
5067        ctx.insert("stream_translations", &stream_translations);
5068        ctx.insert("extra_translations", &extra_translations);
5069    }
5070
5071    // Computed display chips for the "At a glance" panel above the
5072    // form. See `PageTypeHandler::display_fields` — handlers can
5073    // surface word counts / derived metadata / linked-snippet
5074    // previews without subclassing a panel.
5075    let display_fields: Vec<crate::page_type::DisplayField> = match &resolved_handler {
5076        Some(h) => h
5077            .display_fields(pool, id)
5078            .await
5079            .unwrap_or_default(),
5080        None => Vec::new(),
5081    };
5082    ctx.insert("display_fields", &display_fields);
5083
5084    // Handler-contributed tabs — appended to the built-in tab strip
5085    // (Content / Promote / Theme / Revisions). See
5086    // `PageTypeHandler::extra_tabs`.
5087    let mut raw_extra_tabs: Vec<crate::page_type::TabSpec> = match &resolved_handler {
5088        Some(h) => h.extra_tabs(pool, id).await.unwrap_or_default(),
5089        None => Vec::new(),
5090    };
5091
5092    // Role list — shared by the Permissions-tab grid below and the
5093    // Privacy tab's "allowed roles" picker further down. Fetched once:
5094    // both used to run the same full-table query independently.
5095    let all_roles: Vec<rustango::tenancy::permissions::Role> =
5096        rustango::tenancy::permissions::Role::objects()
5097            .order_by(&[("name", false)])
5098            .fetch(pool)
5099            .await
5100            .unwrap_or_default();
5101
5102    // (#18) Permissions tab — every page gets one, regardless of
5103    // page type. Inject a TabSpec::template entry at the front of
5104    // the list so it sits right after Theme.
5105    {
5106        let grants: Vec<crate::permissions::PagePermission> =
5107            crate::permissions::PagePermission::objects()
5108                .where_(crate::permissions::PagePermission::page_id.eq(id))
5109                .fetch(pool)
5110                .await
5111                .unwrap_or_default();
5112        // (role_id, action) → granted?
5113        let granted: std::collections::HashSet<(i64, String)> = grants
5114            .iter()
5115            .map(|g| (g.role_id, g.permission.clone()))
5116            .collect();
5117        let actions: Vec<&str> = crate::permissions::Action::all()
5118            .iter()
5119            .map(|a| a.as_str())
5120            .collect();
5121        let perm_grid: Vec<serde_json::Value> = all_roles
5122            .iter()
5123            .map(|r| {
5124                let rid = r.id.get().copied().unwrap_or_default();
5125                let row_cells: Vec<serde_json::Value> = actions
5126                    .iter()
5127                    .map(|a| {
5128                        serde_json::json!({
5129                            "action": a,
5130                            "granted": granted.contains(&(rid, (*a).to_owned())),
5131                        })
5132                    })
5133                    .collect();
5134                serde_json::json!({
5135                    "role_id": rid,
5136                    "role_name": r.name,
5137                    "role_description": r.description,
5138                    "cells": row_cells,
5139                })
5140            })
5141            .collect();
5142        let perm_tab = crate::page_type::TabSpec::template(
5143            "permissions",
5144            "Permissions",
5145            "rcms_admin/_permissions_tab.html",
5146        )
5147        .with_icon("admin_panel_settings")
5148        .with_context_value(
5149            "perm_actions",
5150            serde_json::to_value(&actions).unwrap_or_default(),
5151        )
5152        .with_context_value(
5153            "perm_grid",
5154            serde_json::to_value(&perm_grid).unwrap_or_default(),
5155        )
5156        .with_context_value("perm_page_id", serde_json::Value::Number(id.into()));
5157        raw_extra_tabs.insert(0, perm_tab);
5158    }
5159    // (#20) Resolve each `TabSpec` into the flat `{name, label,
5160    // icon, badge, html}` shape the page_form.html template
5161    // expects. `Html` variants pass through; `Template` variants
5162    // render the named Tera template with the standard chrome
5163    // context + the spec's own context map merged in; `Widgets`
5164    // variants route through `_widget_group.html` so widget visuals
5165    // match the Content tab's main stack exactly.
5166    let extra_tabs: Vec<serde_json::Value> =
5167        render_extra_tabs(raw_extra_tabs, &state.tera, &ctx, &headers);
5168    ctx.insert("extra_tabs", &extra_tabs);
5169
5170    // A change held for review shows in place of the live values.
5171    // After a conflict, the editor's own values.
5172    let pending_form = match conflict.as_ref() {
5173        Some(c) => Some(c.form.clone()),
5174        None => pending.as_ref().filter(|_| !translation_mode).map(crate::pending_change::PendingChange::form_map),
5175    };
5176    insert_type_fields(
5177        &mut ctx,
5178        &state.tera,
5179        pool,
5180        resolved_handler.as_deref(),
5181        raw_widgets,
5182        id,
5183        page.page_type_id,
5184        pending_form.as_ref(),
5185    )
5186    .await;
5187
5188    // Picker options — every registered block surfaces as an option in
5189    // the block-picker dialog inside each stream editor. The dialog
5190    // filters client-side by `data-allowed` at open time.
5191    ctx.insert(
5192        "picker_options",
5193        &crate::block::admin::picker_options(&state.tera),
5194    );
5195
5196    // #72 — editor lock. Best-effort claim on form open: if the page
5197    // is unlocked or already owned by us, we hold the lock and the
5198    // form renders normally. If someone else holds an unexpired
5199    // lock, render the banner with their username + force-unlock
5200    // affordance; the form itself stays editable (we'll reject the
5201    // POST unless the user force-unlocks first).
5202    let mut lock_banner: Option<serde_json::Value> = None;
5203    let mut lock_owned_by_me = false;
5204    let reviewing_elsewhere = match session_user.as_ref() {
5205        Some(u) => read_only_under_review(pool, id, u).await?,
5206        None => false,
5207    };
5208    if let Some(viewer_id) = session_user
5209        .as_ref()
5210        .and_then(|u| u.id.get().copied())
5211        .filter(|_| !reviewing_elsewhere)
5212    {
5213        match crate::lock::acquire(pool, id, viewer_id, false).await {
5214            Ok(crate::lock::AcquireOutcome::Acquired(_)) => {
5215                lock_owned_by_me = true;
5216            }
5217            Ok(crate::lock::AcquireOutcome::Held(other)) => {
5218                let holder_name = rustango::tenancy::auth::User::objects()
5219                    .where_(rustango::tenancy::auth::User::id.eq(other.user_id))
5220                    .fetch(pool)
5221                    .await
5222                    .ok()
5223                    .and_then(|v| v.into_iter().next())
5224                    .map(|u| u.username)
5225                    .unwrap_or_else(|| format!("user#{}", other.user_id));
5226                lock_banner = Some(serde_json::json!({
5227                    "holder_username": holder_name,
5228                    "holder_id": other.user_id,
5229                    "acquired_at": other.acquired_at.get().copied(),
5230                    "expires_at": other.expires_at,
5231                }));
5232            }
5233            Err(e) => {
5234                tracing::warn!(target: "rustango_cms::admin", page_id = id, error = %e, "lock acquire failed");
5235            }
5236        }
5237    }
5238    ctx.insert("lock_banner", &lock_banner);
5239    ctx.insert("lock_owned_by_me", &lock_owned_by_me);
5240    ctx.insert("lock_heartbeat_secs", &crate::lock::HEARTBEAT_INTERVAL_SECS);
5241
5242    // #73 PR 2 — workflow context for the action bar + side panel.
5243    // Surface:
5244    //   * `workflow_slug` — the slug the page-type opted into (None if direct-publish)
5245    //   * `workflow` — the resolved Workflow row, if found + active
5246    //   * `workflow_state` — the active WorkflowState row, if one exists
5247    //   * `workflow_current_task` — task currently waiting for a decision (when in_progress)
5248    //   * `workflow_history` — [{task_name, status, decided_by_username, decided_at, comment}, …]
5249    //   * `workflow_viewer_can_decide` — true when viewer is in the current task's role (or superuser)
5250    let workflow_slug: Option<String> = chosen_type.workflow_name();
5251    let mut workflow_ctx: Option<serde_json::Value> = None;
5252    let mut workflow_state_ctx: Option<serde_json::Value> = None;
5253    let mut workflow_current_task_ctx: Option<serde_json::Value> = None;
5254    let mut workflow_history_ctx: Vec<serde_json::Value> = Vec::new();
5255    let mut workflow_viewer_can_decide = false;
5256    if let Some(slug) = workflow_slug.as_deref() {
5257        let workflow = crate::workflow::find_by_name(pool, slug)
5258            .await
5259            .unwrap_or(None);
5260        if let Some(wf) = workflow {
5261            let wf_id = wf.id.get().copied().unwrap_or_default();
5262            let tasks = crate::workflow::tasks_for(pool, wf_id)
5263                .await
5264                .unwrap_or_default();
5265            workflow_ctx = Some(serde_json::json!({
5266                "id": wf_id,
5267                "name": wf.name,
5268                "description": wf.description,
5269                "task_count": tasks.len(),
5270            }));
5271            // The latest round, whatever its outcome: an approved page says
5272            // so (and can go through review again), not what an earlier
5273            // round ended with.
5274            if let Some(state_row) = crate::workflow::latest_state_for_page(pool, id)
5275                .await
5276                .unwrap_or(None)
5277            {
5278                let state_id = state_row.id.get().copied().unwrap_or_default();
5279                // Current task (when in_progress).
5280                if let Some(current) = state_row
5281                    .current_task_id
5282                    .and_then(|tid| tasks.iter().find(|t| t.id.get().copied() == Some(tid)))
5283                {
5284                    workflow_current_task_ctx = Some(serde_json::json!({
5285                        "id": current.id.get().copied(),
5286                        "name": current.name,
5287                        "role_id": current.role_id,
5288                    }));
5289                    if let Some(viewer) = session_user.as_ref() {
5290                        let viewer_id = viewer.id.get().copied().unwrap_or_default();
5291                        workflow_viewer_can_decide = viewer.is_superuser
5292                            || user_is_in_role(pool, viewer_id, current.role_id)
5293                                .await
5294                                .unwrap_or(false);
5295                    }
5296                }
5297                workflow_state_ctx = Some(serde_json::json!({
5298                    "id": state_id,
5299                    "status": state_row.status,
5300                    "requested_by": state_row.requested_by,
5301                    "requested_at": state_row.requested_at.get().copied(),
5302                    "finished_at": state_row.finished_at,
5303                }));
5304                // Decision history — flatten task name + reviewer username.
5305                if let Ok(history) = crate::workflow::history_for_page(pool, id).await {
5306                    // Pre-resolve user ids to usernames in one batch.
5307                    let reviewer_ids: Vec<i64> =
5308                        history.iter().filter_map(|h| h.decided_by).collect();
5309                    let reviewers: std::collections::HashMap<i64, String> =
5310                        if reviewer_ids.is_empty() {
5311                            std::collections::HashMap::new()
5312                        } else {
5313                            rustango::tenancy::auth::User::objects()
5314                                .where_(rustango::tenancy::auth::User::id.is_in(reviewer_ids))
5315                                .fetch(pool)
5316                                .await
5317                                .unwrap_or_default()
5318                                .into_iter()
5319                                .filter_map(|u| u.id.get().copied().map(|uid| (uid, u.username)))
5320                                .collect()
5321                        };
5322                    let task_name_by_id: std::collections::HashMap<i64, String> = tasks
5323                        .iter()
5324                        .filter_map(|t| t.id.get().copied().map(|tid| (tid, t.name.clone())))
5325                        .collect();
5326                    workflow_history_ctx = history
5327                        .iter()
5328                        .map(|h| {
5329                            serde_json::json!({
5330                                "task_name": task_name_by_id
5331                                    .get(&h.task_id)
5332                                    .cloned()
5333                                    .unwrap_or_else(|| format!("task #{}", h.task_id)),
5334                                "status": h.status,
5335                                "comment": h.comment,
5336                                "decided_by_username": h
5337                                    .decided_by
5338                                    .and_then(|uid| reviewers.get(&uid).cloned()),
5339                                "decided_at": h.decided_at,
5340                            })
5341                        })
5342                        .collect();
5343                }
5344            }
5345        }
5346    }
5347    // #73 PR 3 — workflow-driven lock. When the page is in_progress
5348    // AND the viewer is not authorized for the current task (and not
5349    // a superuser), the form is read-only — the page belongs to
5350    // whoever is reviewing it right now. Submitter waits for the
5351    // verdict; non-reviewers can't sneak edits in mid-review.
5352    let workflow_locked = workflow_state_ctx
5353        .as_ref()
5354        .and_then(|s| s.get("status"))
5355        .and_then(|v| v.as_str())
5356        .map(|s| s == crate::workflow::WorkflowStatus::InProgress.as_str())
5357        .unwrap_or(false)
5358        && !workflow_viewer_can_decide;
5359    ctx.insert("workflow_slug", &workflow_slug);
5360    ctx.insert("workflow", &workflow_ctx);
5361    ctx.insert("workflow_state", &workflow_state_ctx);
5362    ctx.insert("workflow_current_task", &workflow_current_task_ctx);
5363    ctx.insert("workflow_history", &workflow_history_ctx);
5364    ctx.insert("workflow_viewer_can_decide", &workflow_viewer_can_decide);
5365    ctx.insert("workflow_locked", &workflow_locked);
5366    let review_required = !session_user.as_ref().is_some_and(|u| u.is_superuser)
5367        && crate::workflow::review_workflow_for_type(pool, page.page_type_id).await?.is_some();
5368    ctx.insert("review_required", &review_required);
5369    if let Some(c) = conflict.as_ref() {
5370        ctx.insert("page", &c.page);
5371        ctx.insert("edit_conflicts", &c.conflicts);
5372    } else if let (Some(held), Some(form)) = (pending.as_ref(), pending_form.as_ref()) {
5373        ctx.insert("page", &overlay_pending_page(&page, form));
5374        let by = match held.created_by {
5375            Some(uid) => rustango::tenancy::auth::User::objects()
5376                .where_(rustango::tenancy::auth::User::id.eq(uid))
5377                .first(pool)
5378                .await?
5379                .map(|u| u.username),
5380            None => None,
5381        };
5382        ctx.insert(
5383            "pending_change",
5384            &serde_json::json!({ "by": by, "updated_at": held.updated_at.get().copied() }),
5385        );
5386    }
5387
5388    // #76 — view-restriction context for the Privacy widget.
5389    let view_restriction = crate::view_restriction::direct_for_page(pool, id)
5390        .await
5391        .unwrap_or(None);
5392    let restriction_kind = view_restriction
5393        .as_ref()
5394        .map(|r| r.kind.clone())
5395        .unwrap_or_else(|| "none".to_owned());
5396    let restriction_groups = view_restriction
5397        .as_ref()
5398        .map(|r| r.parsed_groups())
5399        .unwrap_or_default();
5400    let restriction_groups_str = restriction_groups
5401        .iter()
5402        .map(i64::to_string)
5403        .collect::<Vec<_>>()
5404        .join(",");
5405    // For the role picker dropdown — reuses the `all_roles` list already
5406    // fetched once above for the Permissions tab.
5407    let role_choices: Vec<serde_json::Value> = all_roles
5408        .iter()
5409        .map(|r| {
5410            serde_json::json!({
5411                "id": r.id.get().copied(),
5412                "name": r.name,
5413                "checked": r.id.get().copied().is_some_and(|rid| restriction_groups.contains(&rid)),
5414            })
5415        })
5416        .collect();
5417    // #members — permission-codename picker (the permission-engine gate).
5418    let restriction_codenames = view_restriction
5419        .as_ref()
5420        .map(|r| r.parsed_codenames())
5421        .unwrap_or_default();
5422    let restriction_codenames_str = restriction_codenames.join(",");
5423    let codename_choices: Vec<serde_json::Value> = super::resources::membership_codenames()
5424        .into_iter()
5425        .map(|(codename, label)| {
5426            serde_json::json!({
5427                "codename": codename,
5428                "label": label,
5429                "checked": restriction_codenames.contains(&codename),
5430            })
5431        })
5432        .collect();
5433    ctx.insert("restriction_kind", &restriction_kind);
5434    ctx.insert("restriction_groups_str", &restriction_groups_str);
5435    ctx.insert("restriction_role_choices", &role_choices);
5436    ctx.insert("restriction_codenames_str", &restriction_codenames_str);
5437    ctx.insert("restriction_codename_choices", &codename_choices);
5438    ctx.insert(
5439        "restriction_has_password",
5440        &view_restriction
5441            .as_ref()
5442            .map(|r| !r.password_hash.is_empty())
5443            .unwrap_or(false),
5444    );
5445
5446    // #81 PR 1 — comments side panel. Fetch every thread on this
5447    // page + every reply in one batched query, group per thread,
5448    // resolve author usernames, and surface as JSON for the panel
5449    // template. Threads with `resolved_at` set render in a
5450    // collapsed "Resolved" bucket client-side.
5451    let threads = crate::comment::threads_for_page(pool, id)
5452        .await
5453        .unwrap_or_default();
5454    let thread_ids: Vec<i64> = threads.iter().filter_map(|c| c.id.get().copied()).collect();
5455    let replies_by_thread = crate::comment::replies_for_threads(pool, &thread_ids)
5456        .await
5457        .unwrap_or_default();
5458    let mut comment_user_ids: std::collections::BTreeSet<i64> =
5459        threads.iter().map(|c| c.author_id).collect();
5460    for replies in replies_by_thread.values() {
5461        for r in replies {
5462            comment_user_ids.insert(r.author_id);
5463        }
5464    }
5465    let comment_users: std::collections::HashMap<i64, String> = if comment_user_ids.is_empty() {
5466        std::collections::HashMap::new()
5467    } else {
5468        rustango::tenancy::auth::User::objects()
5469            .where_(rustango::tenancy::auth::User::id.is_in(comment_user_ids.iter().copied()))
5470            .fetch(pool)
5471            .await
5472            .unwrap_or_default()
5473            .into_iter()
5474            .filter_map(|u| u.id.get().copied().map(|uid| (uid, u.username)))
5475            .collect()
5476    };
5477    let comment_threads: Vec<serde_json::Value> = threads
5478        .iter()
5479        .map(|c| {
5480            let tid = c.id.get().copied().unwrap_or_default();
5481            let replies = replies_by_thread.get(&tid).cloned().unwrap_or_default();
5482            let rendered_replies: Vec<serde_json::Value> = replies
5483                .iter()
5484                .map(|r| {
5485                    serde_json::json!({
5486                        "id": r.id.get().copied(),
5487                        "author_username": comment_users.get(&r.author_id).cloned(),
5488                        "body": r.body,
5489                        "created_at": r.created_at.get().copied(),
5490                    })
5491                })
5492                .collect();
5493            serde_json::json!({
5494                "id": tid,
5495                "field_path": c.field_path,
5496                "author_username": comment_users.get(&c.author_id).cloned(),
5497                "body": c.body,
5498                "created_at": c.created_at.get().copied(),
5499                "resolved_at": c.resolved_at,
5500                "replies": rendered_replies,
5501                "reply_count": replies.len(),
5502            })
5503        })
5504        .collect();
5505    ctx.insert("comment_threads", &comment_threads);
5506    ctx.insert(
5507        "comment_open_count",
5508        &comment_threads
5509            .iter()
5510            .filter(|t| t.get("resolved_at").map(|v| v.is_null()).unwrap_or(true))
5511            .count(),
5512    );
5513    ctx.insert(
5514        "comment_resolved_count",
5515        &comment_threads
5516            .iter()
5517            .filter(|t| t.get("resolved_at").map(|v| !v.is_null()).unwrap_or(false))
5518            .count(),
5519    );
5520    // For the field-picker dropdown when adding a new comment.
5521    ctx.insert(
5522        "comment_field_choices",
5523        &serde_json::json!([
5524            {"value": "title", "label": "Title"},
5525            {"value": "slug", "label": "Slug"},
5526            {"value": "seo_title", "label": "SEO title"},
5527            {"value": "seo_description", "label": "SEO description"},
5528            {"value": "body", "label": "Body / stream content"},
5529            {"value": "general", "label": "General — whole page"},
5530        ]),
5531    );
5532
5533    let mut response = render_with_csrf(state, headers, "rcms_admin/page_form.html", &mut ctx)?;
5534    if conflict.is_some() {
5535        *response.status_mut() = axum::http::StatusCode::CONFLICT;
5536    }
5537    Ok(response)
5538}
5539
5540/// POST /cms-admin/pages/{id}/edit — apply edits.
5541/// POST /cms-admin/pages/{id}/autosave — silent revision capture.
5542/// Takes the same form payload as
5543/// `page_edit_submit` but:
5544///   - Skips status-promotion logic (draft → published doesn't fire).
5545///   - Captures a revision row tagged `autosave: true` so the
5546///     timeline distinguishes autosaves from manual saves.
5547///   - Does NOT cascade slug / url_path recomputation, redirects,
5548///     workflow events, cache invalidation, or page_subscription
5549///     notifications — autosaves are scratch state, not publish
5550///     events.
5551///   - Returns 204 No Content so the editor JS treats success as a
5552///     quiet acknowledgement (no flash banner).
5553pub async fn page_autosave_submit(
5554    State(_state): State<super::AdminState>,
5555    tenant: Tenant,
5556    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
5557    Path(id): Path<i64>,
5558    Form(form_map): Form<std::collections::HashMap<String, String>>,
5559) -> Result<Response, AdminError> {
5560    autosave_page(tenant.pool(), &tenant.org.slug, session_user.as_ref(), id, &form_map).await
5561}
5562
5563/// [`page_autosave_submit`] from the tenant's pool and slug.
5564async fn autosave_page(
5565    pool: &rustango::sql::Pool,
5566    tenant_slug: &str,
5567    session_user: Option<&rustango::tenancy::auth::User>,
5568    id: i64,
5569    form_map: &std::collections::HashMap<String, String>,
5570) -> Result<Response, AdminError> {
5571    use rustango::sql::FetcherPool as _;
5572    let mut page = Page::objects()
5573        .where_(Page::id.eq(id))
5574        .first(pool)
5575        .await?
5576        .ok_or(AdminError::NotFound(id))?;
5577    // Lock-respect — same as the regular save path. Refuse the
5578    // autosave when someone else holds the lock; the editor JS
5579    // surfaces this by suspending future autosaves until the user
5580    // reloads.
5581    if let Some(viewer_id) = session_user.and_then(|u| u.id.get().copied()) {
5582        if let Ok(Some(lock)) = crate::lock::current(pool, id).await {
5583            if lock.user_id != viewer_id {
5584                return Ok((axum::http::StatusCode::CONFLICT, "locked").into_response());
5585            }
5586        }
5587    }
5588    // Autosave writes the page row itself, so it only touches drafts:
5589    // on a live (or scheduled) page it would publish half-typed edits,
5590    // skipping the publish right and any review. The real Save handles
5591    // those pages; here nothing is written. 202, not 204, so the editor
5592    // doesn't report "Auto-saved" for a save that didn't happen (#903).
5593    if page.status != crate::page::PageStatus::Draft.as_str() {
5594        return Ok((axum::http::StatusCode::ACCEPTED, "not saved: use Save on a live or scheduled page").into_response());
5595    }
5596    if let Some(u) = session_user {
5597        if read_only_under_review(pool, id, u).await? {
5598            return Ok((axum::http::StatusCode::CONFLICT, "under review").into_response());
5599        }
5600    }
5601    // Overlay mutable fields. Tree placement (parent / path /
5602    // url_path / depth / sort_order) intentionally left alone —
5603    // autosaves never move the page. That includes the slug: writing it
5604    // here without url_path made the next real save see "no slug change",
5605    // so the rename never cascaded to url_path, children or a 301 (#679).
5606    // The edited slug stays in the form and the real save applies it.
5607    //
5608    // #903 — with a baseline, a field is written only when this editor
5609    // changed it and nobody else did; one changed on both sides waits for
5610    // the real save's conflict screen. The written fields join the
5611    // baseline returned in `x-rcms-baseline`, or the next save would take
5612    // the editor's own autosave for someone else's change.
5613    let mut baseline = crate::page_baseline::Baseline::from_form(form_map, tenant_slug, id);
5614    let mut written: Vec<&'static str> = Vec::new();
5615    for field in ["title", "seo_title", "seo_description"] {
5616        let Some(v) = form_map.get(field) else { continue };
5617        if let Some(b) = baseline.as_ref() {
5618            let current = crate::page_baseline::value(&page, field);
5619            if b.matches(field, v) || (!b.matches(field, &current) && *v != current) {
5620                continue;
5621            }
5622        }
5623        match field {
5624            "title" => page.title.clone_from(v),
5625            "seo_title" => page.seo_title.clone_from(v),
5626            _ => page.seo_description.clone_from(v),
5627        }
5628        written.push(field);
5629    }
5630    // Skip status promotion. If the editor changed status, we
5631    // record it for the diff but don't fire any publish-side
5632    // effects.
5633    let posted_status = form_map.get("status").cloned();
5634    page.save(pool).await?;
5635    // Persist extension fields via handler (idempotent upserts).
5636    let pts: Vec<PageType> = PageType::objects()
5637        .where_(PageType::id.eq(page.page_type_id))
5638        .fetch(pool)
5639        .await?;
5640    if let Some(pt) = pts.into_iter().next() {
5641        if let Some(handler) = find_handler(&pt.type_name) {
5642            let ext_form =
5643                sanitized_extension_form(handler.as_ref(), pool, id, form_map).await;
5644            handler.save_extension(pool, id, &ext_form).await?;
5645        }
5646    }
5647    // #564 — page-builder body values (additive to any code handler).
5648    save_page_builder_values(pool, page.page_type_id, id, form_map).await?;
5649    // Capture an autosave-flagged revision. Failure here is
5650    // best-effort.
5651    let by = session_user.and_then(|u| u.id.get().copied());
5652    if let Ok(mut rev) = crate::revision::capture(pool, &page, by).await {
5653        // Inject the autosave marker into the snapshot before
5654        // re-saving the row. The snapshot column is a plain
5655        // serde_json::Value so we can mutate + re-persist.
5656        if let serde_json::Value::Object(ref mut map) = rev.snapshot {
5657            map.insert("__autosave".to_owned(), serde_json::Value::Bool(true));
5658            if let Some(status) = posted_status {
5659                map.insert(
5660                    "__autosave_posted_status".to_owned(),
5661                    serde_json::Value::String(status),
5662                );
5663            }
5664            rev.save(pool).await.log_warn("autosave revision not stored");
5665        }
5666    }
5667    let mut response = (axum::http::StatusCode::NO_CONTENT, "").into_response();
5668    if let Some(b) = baseline.as_mut() {
5669        b.rebase(&page, &written);
5670        if let Ok(v) = axum::http::HeaderValue::from_str(&b.token()) {
5671            response
5672                .headers_mut()
5673                .insert(crate::page_baseline::BASELINE_HEADER, v);
5674        }
5675    }
5676    Ok(response)
5677}
5678
5679/// Allow-list of POST keys that `page_edit_submit` re-feeds into
5680/// [`PageForm`]. The submit handler filters the incoming form map
5681/// through this list to drop extension-field entries the page type
5682/// handler owns. Every field [`PageForm`] consumes — and every field
5683/// the body of `page_edit_submit` reads off the parsed form — MUST
5684/// be listed here, or the value is silently dropped on save.
5685///
5686/// `page_type_id` is intentionally absent: type is assigned at
5687/// create-time and is permanent (see comment in the handler).
5688/// Page fields the editor shows as text, overlaid from a held change.
5689const PENDING_TEXT_KEYS: &[&str] = &[
5690    "title",
5691    "slug",
5692    "seo_title",
5693    "seo_description",
5694    "og_title",
5695    "og_description",
5696    "preview_path",
5697];
5698
5699/// `page` as the editor shows it with a held change on top: its text
5700/// fields take the proposed values.
5701fn overlay_pending_page(
5702    page: &Page,
5703    form: &std::collections::HashMap<String, String>,
5704) -> serde_json::Value {
5705    let mut value = serde_json::to_value(page).unwrap_or_default();
5706    if let Some(obj) = value.as_object_mut() {
5707        for key in PENDING_TEXT_KEYS {
5708            if let Some(v) = form.get(*key) {
5709                obj.insert((*key).to_owned(), serde_json::Value::String(v.clone()));
5710            }
5711        }
5712    }
5713    value
5714}
5715
5716/// Give each widget its value from a held change. An unticked checkbox
5717/// isn't posted, so a Boolean the form lacks is off.
5718fn overlay_pending_widgets(
5719    widgets: &mut [crate::widget::Widget],
5720    form: &std::collections::HashMap<String, String>,
5721) {
5722    for w in widgets {
5723        match form.get(&w.name) {
5724            Some(v) => w.value.clone_from(v),
5725            None if matches!(w.kind, crate::widget::WidgetKind::Boolean) => w.value.clear(),
5726            None => {}
5727        }
5728    }
5729}
5730
5731const PAGE_FORM_CANONICAL_KEYS: &[&str] = &[
5732    "title",
5733    "slug",
5734    "status",
5735    "seo_title",
5736    "seo_description",
5737    "robots_index",
5738    "sitemap_priority",
5739    "parent_id",
5740    "theme_id",
5741    // #207 — schedule + auto-archive.
5742    "go_live_at",
5743    "expire_at",
5744    // #22 — surface in navigation editor.
5745    "show_in_menus",
5746    // Headless preview — per-page frontend route override.
5747    "preview_path",
5748    // Per-page template, overriding the page type's.
5749    "template_override",
5750    // #183 — social sharing.
5751    "og_title",
5752    "og_description",
5753    "og_image_media_id",
5754    "twitter_card",
5755    // #189 — page tags (comma-separated).
5756    "tags",
5757];
5758
5759/// `posted`, unless it names the same moment as `stored` at the
5760/// precision it was posted with: then the stored value, so an untouched
5761/// input changes nothing. `minutes` is set when the posted text carried
5762/// no seconds (the admin's schedule inputs); otherwise the comparison is
5763/// to the second, so a script moving a time by seconds is not ignored.
5764fn same_instant_or(
5765    stored: Option<chrono::DateTime<chrono::Utc>>,
5766    posted: Option<chrono::DateTime<chrono::Utc>>,
5767    minutes: bool,
5768) -> Option<chrono::DateTime<chrono::Utc>> {
5769    use chrono::{SubsecRound as _, Timelike as _};
5770    match (stored, posted) {
5771        (Some(s), Some(p)) => {
5772            let s_at_precision = if minutes {
5773                s.trunc_subsecs(0).with_second(0).unwrap_or(s)
5774            } else if p.nanosecond() == 0 {
5775                s.trunc_subsecs(0)
5776            } else {
5777                s
5778            };
5779            if s_at_precision == p {
5780                stored
5781            } else {
5782                posted
5783            }
5784        }
5785        _ => posted,
5786    }
5787}
5788
5789/// The form-owned `cms_page` columns that differ between `stored` and
5790/// the edited `page`, with their new values. Never a tree column
5791/// (`path`, `depth`, `parent_id`, `sort_order`, `locale_variant_of`,
5792/// `alias_of`) or a publish timestamp; `url_path` only moves with the
5793/// slug.
5794fn page_form_changes(stored: &Page, page: &Page) -> Vec<(&'static str, rustango::core::SqlValue)> {
5795    let mut out: Vec<(&'static str, rustango::core::SqlValue)> = Vec::new();
5796    macro_rules! diff {
5797        ($($field:ident),+ $(,)?) => {$(
5798            if stored.$field != page.$field {
5799                out.push((stringify!($field), page.$field.clone().into()));
5800            }
5801        )+};
5802    }
5803    diff!(
5804        title,
5805        slug,
5806        url_path,
5807        status,
5808        seo_title,
5809        seo_description,
5810        robots_index,
5811        theme_id,
5812        go_live_at,
5813        expire_at,
5814        show_in_menus,
5815        preview_path,
5816        template_override,
5817        og_title,
5818        og_description,
5819        og_image_media_id,
5820        twitter_card,
5821        notification_pre_published_sent,
5822    );
5823    // An f32 read back from the database need not equal the posted one
5824    // to the last bit.
5825    if (stored.sitemap_priority - page.sitemap_priority).abs() > 1e-4 {
5826        out.push(("sitemap_priority", page.sitemap_priority.into()));
5827    }
5828    out
5829}
5830
5831/// Stamp a save that changed something: `updated_at`, and on a published
5832/// page `last_published_at` (the sitemap and fragment cache read it as
5833/// "public content changed") plus `published_at` on the first publish.
5834fn stamp_page_change(
5835    page: &mut Page,
5836    set: &mut Vec<(&'static str, rustango::core::SqlValue)>,
5837    now: chrono::DateTime<chrono::Utc>,
5838) {
5839    if page.status == crate::page::PageStatus::Published.as_str() {
5840        if page.published_at.is_none() {
5841            page.published_at = Some(now);
5842            set.push(("published_at", now.into()));
5843        }
5844        page.last_published_at = Some(now);
5845        set.push(("last_published_at", now.into()));
5846    }
5847    page.updated_at = rustango::sql::Auto::Set(now);
5848    set.push(("updated_at", now.into()));
5849}
5850
5851/// A page's type-specific content as stored — extension row, inline
5852/// panels saved with the page, page-builder values — for telling whether
5853/// a save changed it. `None` when it can't be read: treated as changed.
5854async fn type_content_snapshot(
5855    pool: &rustango::sql::Pool,
5856    page_type: Option<&PageType>,
5857    page_id: i64,
5858) -> Option<serde_json::Value> {
5859    let mut panels = serde_json::Map::new();
5860    let mut extension = serde_json::Value::Null;
5861    if let Some(handler) = page_type.and_then(|pt| find_handler(&pt.type_name)) {
5862        extension = handler.load_extension(pool, page_id).await.ok()?;
5863        for spec in handler.inline_panels(pool, page_id).await.ok()? {
5864            if spec.per_row {
5865                continue;
5866            }
5867            let rows = handler.load_inline_panel(pool, page_id, &spec.name).await.ok()?;
5868            panels.insert(spec.name.clone(), serde_json::to_value(rows).ok()?);
5869        }
5870    }
5871    let builder = crate::page_builder::model::data_for_page(pool, page_id)
5872        .await
5873        .ok()?
5874        .map(|row| serde_json::json!([row.schema_version, row.component_versions, row.data]));
5875    Some(serde_json::json!({ "extension": extension, "panels": panels, "builder": builder }))
5876}
5877
5878/// Whether a save held for review would change the page's tags,
5879/// categories or type content — judged without writing, since a held
5880/// save writes none of them. Content is compared as posted (see
5881/// [`crate::page_form::content_matches`]): a field the save would
5882/// normalise counts as changed, and the save is held as before.
5883async fn held_save_changes(
5884    pool: &rustango::sql::Pool,
5885    page: &Page,
5886    form_map: &std::collections::HashMap<String, String>,
5887) -> Result<bool, AdminError> {
5888    let id = page.id.get().copied().unwrap_or_default();
5889    if let Some(raw) = form_map.get("tags") {
5890        let names: Vec<String> = if raw.is_empty() {
5891            Vec::new()
5892        } else {
5893            raw.split(',').map(str::to_owned).collect()
5894        };
5895        if crate::page_tag::tags_differ(pool, id, &names).await? {
5896            return Ok(true);
5897        }
5898    }
5899    if let Some(raw) = form_map.get(crate::category::assign::FORM_KEY) {
5900        if crate::category::assign::form_differs(pool, id, raw).await? {
5901            return Ok(true);
5902        }
5903    }
5904    Ok(!crate::page_form::content_matches(pool, page, form_map).await)
5905}
5906
5907/// The acting user for [`apply_page_edit`] — carries exactly what the
5908/// lock / workflow / attribution logic needs, decoupled from the HTTP
5909/// session type so the MCP tools can act as a key's owner.
5910pub(crate) struct PageEditActor {
5911    pub id: i64,
5912    pub username: String,
5913    pub is_superuser: bool,
5914}
5915
5916/// A save refused for a *policy* reason (not an error): the caller
5917/// renders it in its own shape — the HTTP handler as a flash+redirect,
5918/// an MCP tool as a structured tool error.
5919pub(crate) enum PageEditRefusal {
5920    /// Page is mid-review on a workflow step the actor can't edit.
5921    WorkflowReview { task_name: String },
5922    /// Another editor holds the edit lock.
5923    LockedBy { holder: String },
5924    /// Archived pages can't be unpublished in place.
5925    ArchivedUnpublish,
5926    /// The save would put the page live and the actor lacks the publish
5927    /// right.
5928    PublishDenied,
5929    /// The save would put the page live, but pages of its type go live
5930    /// through the named review workflow.
5931    ReviewRequired { workflow: String },
5932    /// Fields this editor changed were changed by someone else too since
5933    /// the form loaded (#903). Nothing was written; `page` is the stored
5934    /// row with this editor's changes on top, for showing the form again.
5935    Conflict {
5936        conflicts: Vec<crate::page_baseline::FieldConflict>,
5937        page: Box<Page>,
5938    },
5939}
5940
5941/// What a successful [`apply_page_edit`] produced, for caller messaging.
5942pub(crate) struct PageEditOutcome {
5943    pub page: Page,
5944    pub redirects_created: usize,
5945    pub reapproval_kicked: bool,
5946    /// The save was kept for review; the live page is unchanged.
5947    pub held_for_review: bool,
5948    /// The posted form matched the stored page: nothing was written.
5949    pub unchanged: bool,
5950}
5951
5952/// Apply one page edit end-to-end from a canonical+extension form map —
5953/// the single write path behind both `page_edit_submit` (HTTP) and the
5954/// MCP `update_page`/`publish_page` tools. Covers: workflow + editor
5955/// lock policy, the canonical-key overlay (`PAGE_FORM_CANONICAL_KEYS`),
5956/// scheduled-status derivation + publish timestamps, the atomic tree
5957/// save with url-path cascade + on-commit cache purges, tags, revision
5958/// capture (attributed to `actor`), reference reindex, search sync,
5959/// publish hooks + page log, extension + inline-panel + page-builder
5960/// value persistence, auto-301s on slug moves, redirect auto-disable on
5961/// unpublish, and reapproval-on-edit. `notify = false` skips the
5962/// publish subscription mail (MCP v1). Flash/redirect rendering stays
5963/// with the HTTP handler.
5964/// The request tenant as the page cache keys it; resolved orgs always have an id.
5965pub(crate) fn tenant_key(org: &rustango::tenancy::Org) -> Result<rustango::tenancy::TenantSlug, AdminError> {
5966    rustango::tenancy::TenantSlug::of(org)
5967        .ok_or_else(|| AdminError::Validation(format!("tenant `{}` has no id", org.slug)))
5968}
5969
5970#[allow(clippy::too_many_arguments)]
5971pub(crate) async fn apply_page_edit(
5972    pool: &rustango::sql::Pool,
5973    tenant: &rustango::tenancy::TenantSlug,
5974    invalidator: &std::sync::Arc<dyn crate::cache_invalidate::PageCacheInvalidator>,
5975    mailer: Option<&dyn rustango::email::Mailer>,
5976    mailer_from: &str,
5977    notify: bool,
5978    id: i64,
5979    form_map: &std::collections::HashMap<String, String>,
5980    actor: Option<&PageEditActor>,
5981) -> Result<Result<PageEditOutcome, PageEditRefusal>, AdminError> {
5982    // #73 PR 3 — workflow lock. While the page is in_progress on a
5983    // workflow, only members of the current task's role (and
5984    // superusers) can save edits. Submitter waits for the verdict;
5985    // non-reviewers can't sneak fixes in mid-review. Checked BEFORE
5986    // the editor lock — workflow restrictions outrank concurrency.
5987    if let Some(actor) = actor {
5988        if let Some(active) = crate::workflow::active_state_for_page(pool, id).await? {
5989            if active.status == crate::workflow::WorkflowStatus::InProgress.as_str()
5990                && !actor.is_superuser
5991            {
5992                let tasks = crate::workflow::tasks_for(pool, active.workflow_id).await?;
5993                if let Some(current_task) = active
5994                    .current_task_id
5995                    .and_then(|tid| tasks.iter().find(|t| t.id.get().copied() == Some(tid)))
5996                {
5997                    if !user_is_in_role(pool, actor.id, current_task.role_id).await? {
5998                        return Ok(Err(PageEditRefusal::WorkflowReview {
5999                            task_name: current_task.name.clone(),
6000                        }));
6001                    }
6002                }
6003            }
6004        }
6005    }
6006
6007    // #72 — refuse the write if the page is locked by someone else.
6008    // The GET path acquires the lock for the viewer; if they got
6009    // through, this is a no-op. If a second editor saves anyway
6010    // (race or curl), they hit a 409-flavored redirect with a flash
6011    // explaining who holds the lock. Force-unlock is a separate
6012    // POST so accidental clobbers stay impossible.
6013    if let Some(actor) = actor {
6014        match crate::lock::current(pool, id).await {
6015            Ok(Some(lock)) if lock.user_id != actor.id => {
6016                let holder = rustango::tenancy::auth::User::objects()
6017                    .where_(rustango::tenancy::auth::User::id.eq(lock.user_id))
6018                    .fetch(pool)
6019                    .await
6020                    .ok()
6021                    .and_then(|v| v.into_iter().next())
6022                    .map(|u| u.username)
6023                    .unwrap_or_else(|| format!("user#{}", lock.user_id));
6024                return Ok(Err(PageEditRefusal::LockedBy { holder }));
6025            }
6026            _ => {}
6027        }
6028    }
6029
6030    // Re-deserialize as PageForm using only the canonical keys. The
6031    // form map also carries extension-field entries (typed body /
6032    // hero / etc.) the type's handler is interested in; we hand that
6033    // raw HashMap to `save_extension` after the canonical save.
6034    //
6035    // `page_type_id` is *not* in this list — page type is assigned at
6036    // create-time and is permanent. Any value posted is ignored. The
6037    // template hides the selector and the handler defensively drops
6038    // the key here. Caller scenarios that *must* change a page's
6039    // type can delete + recreate (preserves slug history via
6040    // `cms_redirect`).
6041    let canonical_keys = PAGE_FORM_CANONICAL_KEYS;
6042    let mut canonical_only: std::collections::HashMap<&str, String> = form_map
6043        .iter()
6044        .filter(|(k, _)| canonical_keys.contains(&k.as_str()))
6045        .map(|(k, v)| (k.as_str(), v.clone()))
6046        .collect();
6047
6048    let mut page = Page::objects()
6049        .where_(Page::id.eq(id))
6050        .first(pool)
6051        .await?
6052        .ok_or(AdminError::NotFound(id))?;
6053
6054    // Re-inject the immutable `page_type_id` from the persisted row
6055    // so `PageForm`'s deserializer is satisfied without trusting
6056    // anything the client posted.
6057    let frozen_type_id = page.page_type_id.to_string();
6058    canonical_only.insert("page_type_id", frozen_type_id);
6059    let canonical_view: std::collections::HashMap<&str, &str> = canonical_only
6060        .iter()
6061        .map(|(k, v)| (*k, v.as_str()))
6062        .collect();
6063    let form: PageForm = serde_urlencoded::from_str(
6064        &serde_urlencoded::to_string(&canonical_view).unwrap_or_default(),
6065    )
6066    .map_err(|e| AdminError::Validation(format!("canonical form: {e}")))?;
6067
6068    // #903 — the row as stored: only the columns this save changes are
6069    // written, and a save that changes nothing writes nothing.
6070    let stored = page.clone();
6071    page.title = form.title.clone();
6072    // #703 — the same normalisation a new page gets, and no two siblings
6073    // on one slug (checked below): they would share a URL and serve
6074    // whichever row the driver returned. The pattern attribute alone is
6075    // bypassed by any direct POST (and by MCP update_page).
6076    page.slug = if form.slug.trim().is_empty() {
6077        String::new()
6078    } else {
6079        slugify(&form.slug)
6080    };
6081    // page.page_type_id stays as-is — see comment on `canonical_keys`.
6082    page.status = form.parsed_status().as_str().to_owned();
6083    page.seo_title = form.seo_title.clone();
6084    page.seo_description = form.seo_description.clone();
6085    page.robots_index = form.parsed_robots_index();
6086    page.sitemap_priority = form.parsed_sitemap_priority();
6087    // The editor has no theme input: keep the stored theme unless the
6088    // request carries the field (#902).
6089    if let Some(theme_id) = form.theme_id {
6090        page.theme_id = theme_id;
6091    }
6092    page.go_live_at = same_instant_or(stored.go_live_at, form.parsed_go_live_at(), form.go_live_at_in_minutes());
6093    page.expire_at = same_instant_or(stored.expire_at, form.parsed_expire_at(), form.expire_at_in_minutes());
6094    page.show_in_menus = form.parsed_show_in_menus();
6095    page.preview_path = form.preview_path.trim().to_owned();
6096    page.template_override = form.template_override.trim().to_owned();
6097    // #183 — social sharing fields.
6098    page.og_title = form.og_title.clone();
6099    page.og_description = form.og_description.clone();
6100    page.og_image_media_id = form.og_image_media_id;
6101    if let Some(tc) = form.twitter_card.as_deref() {
6102        if matches!(tc, "summary" | "summary_large_image") {
6103            page.twitter_card = tc.to_owned();
6104        }
6105    }
6106    // #903 phase 2 — the form says what it loaded: a field this editor
6107    // left alone keeps what is stored now (another editor's save, the
6108    // scheduler's publish), and a field both changed is refused rather
6109    // than overwritten. A save with no actor (an approved held change)
6110    // has nobody to ask, so its values win.
6111    if let Some(baseline) = crate::page_baseline::Baseline::from_form(form_map, &tenant.slug, id) {
6112        let conflicts = baseline.merge(&stored, &mut page, &form.status);
6113        if !conflicts.is_empty() && actor.is_some() {
6114            return Ok(Err(PageEditRefusal::Conflict { conflicts, page: Box::new(page) }));
6115        }
6116    }
6117    let slug_changed = page.slug != stored.slug;
6118    if slug_changed && !page.slug.is_empty() {
6119        let sibling = Page::objects()
6120            .where_(Page::slug.eq(page.slug.clone()))
6121            .where_(Page::id.ne(id));
6122        let sibling = match page.parent_id {
6123            Some(pid) => sibling.where_(Page::parent_id.eq(pid)),
6124            None => sibling.where_(Page::parent_id.is_null()),
6125        };
6126        if sibling.first(pool).await?.is_some() {
6127            return Err(AdminError::Validation(format!(
6128                "another page under the same parent already uses the slug “{}”",
6129                page.slug
6130            )));
6131        }
6132    }
6133    // Capture the OLD url_path BEFORE the recomputation block below
6134    // overwrites it. Used after commit to evict the now-stale cache
6135    // entry under the page's previous URL.
6136    let old_url_path = page.url_path.clone();
6137    // #553 — remember whether this save takes the page out of
6138    // Published, so linked redirect rules can be auto-disabled below.
6139    let was_published = stored.status == crate::page::PageStatus::Published.as_str();
6140    // #556 — remember whether it was archived, to block an unpublish
6141    // (archived → draft) below. Archived → published is the unarchive
6142    // path and stays allowed.
6143    let was_archived = stored.status == crate::page::PageStatus::Archived.as_str();
6144    let old_status = stored.status.clone();
6145    // #207 — clear the pre-publish reminder flag when go_live_at
6146    // moves so a fresh schedule horizon gets a fresh reminder.
6147    if page.go_live_at != stored.go_live_at {
6148        page.notification_pre_published_sent = false;
6149    }
6150    // #264 — derive scheduled state from go_live_at AFTER the form's
6151    // chosen status has been applied above, so picking "Draft" +
6152    // setting a future go-live still parks the row in the sweep's
6153    // pickup queue.
6154    page.status = derive_scheduled_status(&page.status, page.go_live_at);
6155    // #903 — the scheduler published this page while the editor had it
6156    // open, so the form still says "scheduled" with a go-live in the
6157    // past: keep it published rather than step it back.
6158    if old_status == crate::page::PageStatus::Published.as_str()
6159        && page.status == crate::page::PageStatus::Scheduled.as_str()
6160        && !page.go_live_at.is_some_and(|t| t > chrono::Utc::now())
6161    {
6162        page.status = old_status.clone();
6163    }
6164    // #556 — an archived page can't be unpublished to Draft in place;
6165    // it must be revived (→ Published) or explicitly unarchived first.
6166    // This runs before any DB mutation below.
6167    if was_archived && page.status == crate::page::PageStatus::Draft.as_str() {
6168        return Ok(Err(PageEditRefusal::ArchivedUnpublish));
6169    }
6170    // #761 — judged on the status this save actually lands on, after
6171    // `derive_scheduled_status`, so neither `archived` nor Draft plus a
6172    // go-live date gets a draft public without the publish right. Here so
6173    // the admin form and MCP share one rule. A save with no actor is the
6174    // CMS's own.
6175    if let Some(actor) = actor {
6176        if crate::page::PageStatus::str_goes_live(&old_status, &page.status) {
6177            // A workflow on the page type is only a promise if nobody can
6178            // publish around it: only its approval (or a superuser) puts
6179            // such a page live. Asked first — "submit it for review" is
6180            // the useful answer whatever the actor's rights.
6181            if !actor.is_superuser {
6182                if let Some(wf) = crate::workflow::review_workflow_for_type(pool, page.page_type_id).await? {
6183                    return Ok(Err(PageEditRefusal::ReviewRequired { workflow: wf.name }));
6184                }
6185            }
6186            let req = super::route_perms::Requirement {
6187                codename: "cms_page.publish".to_owned(),
6188                page: Some((id, crate::permissions::Action::Publish)),
6189            };
6190            if !super::route_perms::allows_id(pool, actor.id, actor.is_superuser, &req).await {
6191                return Ok(Err(PageEditRefusal::PublishDenied));
6192            }
6193        }
6194    }
6195
6196    // Recompute the materialized `url_path` when the
6197    // slug changes, and cascade the recomputation to
6198    // every descendant so deep trees stay correct after an ancestor
6199    // rename.
6200    if slug_changed {
6201        let parent_url_path = match page.parent_id {
6202            None => None,
6203            Some(pid) => Page::objects()
6204                .where_(Page::id.eq(pid))
6205                .first(pool)
6206                .await?
6207                .map(|p| p.url_path),
6208        };
6209        page.url_path = crate::tree_ops::compute_url_path(parent_url_path.as_deref(), &page.slug);
6210    }
6211
6212    // #903 — the columns the form owns that this save changes. The tree
6213    // columns (path, depth, parent, order, locale/alias links) are never
6214    // written here, so a move made while the page was open survives.
6215    let mut changes = page_form_changes(&stored, &page);
6216    let core_changed = !changes.is_empty();
6217
6218    // A live page of a type whose review workflow asks for re-approval
6219    // on edit: a non-superuser's save waits for that review instead of
6220    // changing what visitors see. The final approval applies it (a save
6221    // with no actor, so it isn't held again). Nothing is written above
6222    // this point.
6223    if let Some(actor) = actor.filter(|a| !a.is_superuser) {
6224        if stored.status == crate::page::PageStatus::Published.as_str() {
6225            if let Some(wf) = crate::workflow::review_workflow_for_type(pool, stored.page_type_id)
6226                .await?
6227                .filter(|wf| wf.require_reapproval_on_edit)
6228            {
6229                // #903 — a save that changes nothing starts no review of
6230                // nothing. Judged without writing; see `held_save_changes`.
6231                if !core_changed && !held_save_changes(pool, &stored, form_map).await? {
6232                    return Ok(Ok(PageEditOutcome {
6233                        page: stored,
6234                        redirects_created: 0,
6235                        reapproval_kicked: false,
6236                        held_for_review: false,
6237                        unchanged: true,
6238                    }));
6239                }
6240                crate::pending_change::hold(pool, id, form_map, Some(actor.id)).await?;
6241                let mut started = false;
6242                if crate::workflow::active_state_for_page(pool, id).await?.is_none() {
6243                    let tasks =
6244                        crate::workflow::tasks_for(pool, wf.id.get().copied().unwrap_or_default())
6245                            .await?;
6246                    crate::workflow::submit_for_review(pool, id, &wf, &tasks, actor.id).await?;
6247                    started = true;
6248                }
6249                return Ok(Ok(PageEditOutcome {
6250                    page: stored,
6251                    redirects_created: 0,
6252                    reapproval_kicked: started,
6253                    held_for_review: true,
6254                    unchanged: false,
6255                }));
6256            }
6257        }
6258    }
6259    let now = chrono::Utc::now();
6260    if core_changed {
6261        stamp_page_change(&mut page, &mut changes, now);
6262    }
6263
6264    // Wrap self-save + cascade in one atomic_tree block so the tree
6265    // never observes a mixed state (own page updated but children
6266    // stale). The #78 purge of the affected URLs — this page's new
6267    // URL, plus (on a slug change) its old URL and every descendant —
6268    // is registered via on_commit, so it fires only once the save
6269    // commits (never on rollback) and runs detached. #317.
6270    let purge_invalidator = invalidator.clone();
6271    let purge_tenant = tenant.clone();
6272    let mut purge_new = page.url_path.clone();
6273    let mut purge_old = old_url_path.clone();
6274    let renamed = if !core_changed {
6275        Ok((page, Vec::new(), old_url_path))
6276    } else {
6277        crate::tree_ops::atomic_tree(pool, move |tx| {
6278            Box::pin(async move {
6279                let mut changes = changes;
6280                if slug_changed {
6281                    // The page may have moved since it was read: rename it
6282                    // where it is now, under its current parent.
6283                    let current = Page::objects()
6284                        .where_(Page::id.eq(id))
6285                        .select_for_update()
6286                        .silent_on_sqlite()
6287                        .fetch_tx(tx)
6288                        .await?
6289                        .into_iter()
6290                        .next()
6291                        .ok_or(crate::tree_ops::TreeError::NotFound(id))?;
6292                    page.parent_id = current.parent_id;
6293                    page.path = current.path;
6294                    page.depth = current.depth;
6295                    purge_old = current.url_path;
6296                    if !page.slug.is_empty() {
6297                        let sibling = Page::objects()
6298                            .where_(Page::slug.eq(page.slug.clone()))
6299                            .where_(Page::id.ne(id));
6300                        let sibling = match page.parent_id {
6301                            Some(pid) => sibling.where_(Page::parent_id.eq(pid)),
6302                            None => sibling.where_(Page::parent_id.is_null()),
6303                        };
6304                        if !sibling.fetch_tx(tx).await?.is_empty() {
6305                            return Ok(Err(page.slug.clone()));
6306                        }
6307                    }
6308                    let parent_url_path = match page.parent_id {
6309                        None => None,
6310                        Some(pid) => Page::objects()
6311                            .where_(Page::id.eq(pid))
6312                            .fetch_tx(tx)
6313                            .await?
6314                            .into_iter()
6315                            .next()
6316                            .map(|p| p.url_path),
6317                    };
6318                    page.url_path = crate::tree_ops::compute_url_path(parent_url_path.as_deref(), &page.slug);
6319                    purge_new = page.url_path.clone();
6320                    changes.retain(|(column, _)| *column != "url_path");
6321                    if page.url_path != purge_old {
6322                        changes.push(("url_path", page.url_path.clone().into()));
6323                    }
6324                }
6325                let mut update = Page::objects().where_(Page::id.eq(id)).update();
6326                for (column, value) in changes {
6327                    update = update.set(column, value);
6328                }
6329                rustango::sql::update_tx(tx, &update.compile()?).await?;
6330                let descendants: Vec<Page> = if slug_changed {
6331                    crate::tree_ops::cascade_url_path_to_descendants(tx, &page).await?;
6332                    Page::objects()
6333                        .where_(Page::path.like(crate::tree::descendants_like(&page.path)))
6334                        .where_(Page::path.ne(page.path.clone()))
6335                        .fetch_tx(tx)
6336                        .await?
6337                } else {
6338                    Vec::new()
6339                };
6340                // A rename moves this page and everything under it: keep the
6341                // old addresses of the public ones working (redirects that
6342                // follow the page).
6343                if slug_changed {
6344                    let public = |p: &Page| matches!(p.status.as_str(), "published" | "archived");
6345                    let mut moves = Vec::with_capacity(1 + descendants.len());
6346                    if public(&page) {
6347                        moves.push((page.id.get().copied().unwrap_or_default(), purge_old.clone(), purge_new.clone()));
6348                    }
6349                    for d in descendants.iter().filter(|d| public(d)) {
6350                        if let Some(old) = crate::redirect::rebase_path(&d.url_path, &purge_new, &purge_old) {
6351                            moves.push((d.id.get().copied().unwrap_or_default(), old, d.url_path.clone()));
6352                        }
6353                    }
6354                    crate::redirect::record_renames_tx(tx, &moves).await?;
6355                }
6356                let descendant_urls: Vec<String> = descendants.into_iter().map(|d| d.url_path).collect();
6357                let mut urls = Vec::with_capacity(2 + descendant_urls.len());
6358                urls.push(purge_new.clone());
6359                if slug_changed && purge_old != purge_new && !purge_old.is_empty() {
6360                    urls.push(purge_old.clone());
6361                }
6362                urls.extend(descendant_urls.iter().cloned());
6363                crate::cache_invalidate::invalidate_urls_on_commit(purge_invalidator, purge_tenant, urls);
6364                Ok(Ok((page, descendant_urls, purge_old)))
6365            })
6366        })
6367        .await?
6368    };
6369    let (mut page, descendant_urls, old_url_path) = match renamed {
6370        Ok(saved) => saved,
6371        Err(slug) => {
6372            return Err(AdminError::Validation(format!(
6373                "another page under the same parent already uses the slug “{slug}”"
6374            )));
6375        }
6376    };
6377    let new_url_path = page.url_path.clone();
6378    // #705 — the page's content goes in straight after the core row, and
6379    // before anything announces the save: the revision, the reference
6380    // index, search, publish hooks, subscriber mail and the page log all
6381    // describe this content. A failed write is returned to the caller,
6382    // not logged and swallowed behind a "Saved" flash. (The writes can't
6383    // join the core row's transaction yet — the handler hooks take a
6384    // pool — so the core row stays committed; resubmitting is safe, the
6385    // upserts are idempotent.)
6386    //
6387    // #189 — tags from the comma-separated `tags` field. Missing → left
6388    // alone; posted empty → cleared.
6389    let mut tags_changed = false;
6390    if let Some(tags_raw) = form_map.get("tags") {
6391        let names: Vec<String> = if tags_raw.is_empty() {
6392            Vec::new()
6393        } else {
6394            tags_raw.split(',').map(|s| s.to_owned()).collect()
6395        };
6396        tags_changed = crate::page_tag::replace_tags(pool, id, &names).await?;
6397    }
6398    // #842 — categories, same missing/empty rule as tags.
6399    let categories_changed = crate::category::assign::save_from_form(
6400        pool,
6401        id,
6402        form_map.get(crate::category::assign::FORM_KEY).map(String::as_str),
6403    )
6404    .await?;
6405    let pt_opt: Option<PageType> = PageType::objects()
6406        .where_(PageType::id.eq(page.page_type_id))
6407        .first(pool)
6408        .await?;
6409    // #903 — the type's content as stored before and after its write:
6410    // the same reads on both sides, so the comparison needs no
6411    // knowledge of how each field normalises what was posted.
6412    let content_before = type_content_snapshot(pool, pt_opt.as_ref(), id).await;
6413    save_type_content(pool, pt_opt.as_ref(), page.page_type_id, id, form_map).await?;
6414    let content_changed = match content_before {
6415        Some(before) => {
6416            type_content_snapshot(pool, pt_opt.as_ref(), id).await != Some(before)
6417        }
6418        None => true,
6419    };
6420
6421    // #903 — nothing changed: no revision, page-log entry, hooks, mail,
6422    // cache purge or review restart, and the row keeps its timestamps.
6423    if !(core_changed || tags_changed || categories_changed || content_changed) {
6424        if actor.is_some() {
6425            crate::pending_change::discard(pool, id).await?;
6426        }
6427        return Ok(Ok(PageEditOutcome {
6428            page,
6429            redirects_created: 0,
6430            reapproval_kicked: false,
6431            held_for_review: false,
6432            unchanged: true,
6433        }));
6434    }
6435    if !core_changed {
6436        // Only the tags, categories or the type's content changed: the
6437        // row still records when, and the cached page goes.
6438        let mut stamp = Vec::new();
6439        stamp_page_change(&mut page, &mut stamp, now);
6440        let mut update = Page::objects().where_(Page::id.eq(id)).update();
6441        for (column, value) in stamp {
6442            update = update.set(column, value);
6443        }
6444        rustango::sql::UpdaterPool::execute_pool(update, pool).await?;
6445        crate::task_queue::purge_urls(invalidator.clone(), tenant.clone(), vec![new_url_path.clone()]).await;
6446    }
6447
6448    // Capture revision after commit so the committed
6449    // page row is visible to the sequence SELECT inside capture.
6450    crate::revision::capture(pool, &page, actor.map(|a| a.id))
6451        .await
6452        .log_warn("revision not captured; the history has a gap");
6453
6454    reindex_from_form(pool, &tenant.slug, id, form_map).await;
6455
6456    // #408 — keep an external search index (Elasticsearch) in sync:
6457    // published → indexed, otherwise removed. No-op when no backend is
6458    // installed (the Postgres FTS path needs no maintained index).
6459    crate::task_queue::sync_page_search(&tenant.slug, &page).await;
6460
6461    // #107 — fan out to plugin `after_publish_page` hooks. Only when this
6462    // save takes the page live (#903): re-saving a live page used to log
6463    // "Published", re-email every subscriber and re-fire the hooks.
6464    let actor_id = actor.map(|a| a.id);
6465    if page.status == crate::page::PageStatus::Published.as_str() && !was_published {
6466        crate::hooks::fire_after_publish_page(crate::hooks::HookCtx::new(pool, &tenant.slug, actor_id), &page).await;
6467        // #115 — notify-on-publish subscribers.
6468        if notify {
6469            let actor_name = actor.map(|a| a.username.as_str());
6470            crate::page_subscription::notify_publish(
6471                mailer,
6472                mailer_from,
6473                pool,
6474                &tenant.slug,
6475                page.id.get().copied().unwrap_or_default(),
6476                &page.title,
6477                &page.url_path,
6478                actor_name,
6479            )
6480            .await;
6481        }
6482        // #192 — record the publish in the audit log.
6483        crate::page_log::record_or_warn(
6484            pool,
6485            id,
6486            crate::page_log::ACTION_PUBLISH,
6487            actor_id,
6488            format!("Published “{}”.", page.title),
6489            None,
6490        )
6491        .await;
6492    } else {
6493        // #192 — log the edit even when the new status isn't Published.
6494        crate::page_log::record_or_warn(
6495            pool,
6496            id,
6497            crate::page_log::ACTION_EDIT,
6498            actor_id,
6499            format!("Edited “{}”.", page.title),
6500            Some(serde_json::json!({ "status": page.status })),
6501        )
6502        .await;
6503    }
6504
6505
6506    // #64 — auto-create 301 redirects from old paths to new ones
6507    // when a slug change cascades through the URL tree. Editors
6508    // rename pages all the time; keeping the old URL alive prevents
6509    // external links + SEO rank from going dead.
6510    let mut redirects_created = 0usize;
6511    if slug_changed && old_url_path != new_url_path && !old_url_path.is_empty() {
6512        // Capture the descendant before/after pairs alongside the
6513        // page itself. The cascade already updated every descendant's
6514        // url_path in the same transaction; rebuild the OLD → NEW
6515        // map from the path prefix relationship: a descendant whose
6516        // new url_path begins with `new_url_path` had its OLD url at
6517        // `old_url_path + suffix`.
6518        let new_prefix = if new_url_path == "/" {
6519            String::new()
6520        } else {
6521            new_url_path.clone()
6522        };
6523        let old_prefix = if old_url_path == "/" {
6524            String::new()
6525        } else {
6526            old_url_path.clone()
6527        };
6528        let mut pairs: Vec<(String, String)> = vec![(old_url_path.clone(), new_url_path.clone())];
6529        for new_d in &descendant_urls {
6530            if let Some(suffix) = new_d.strip_prefix(new_prefix.as_str()) {
6531                let old_d = format!("{old_prefix}{suffix}");
6532                if old_d != *new_d {
6533                    pairs.push((old_d, new_d.clone()));
6534                }
6535            }
6536        }
6537        // Upsert each pair. If an existing redirect already targets the
6538        // old path (e.g. from a previous rename), update its `to_path`
6539        // so the chain compresses to one hop instead of `foo → bar →
6540        // baz`. New rows land with is_permanent=true (301) + a stamped
6541        // note for auditability.
6542        let now = chrono::Utc::now().to_rfc3339();
6543        for (old_path, new_path) in pairs {
6544            // Look up any existing row keyed on the old URL.
6545            let existing: Vec<crate::redirect::Redirect> = crate::redirect::Redirect::objects()
6546                .where_(crate::redirect::Redirect::from_path.eq(old_path.clone()))
6547                .fetch(pool)
6548                .await
6549                .unwrap_or_default();
6550            if let Some(mut r) = existing.into_iter().next() {
6551                // Compress chain: rewrite the existing row's target
6552                // unless it already points at the new URL.
6553                if r.to_path != new_path {
6554                    r.to_path = new_path.clone();
6555                    r.is_permanent = true;
6556                    r.note = format!("auto-updated on page rename at {now}");
6557                    // #553 — link the source page so the rule
6558                    // auto-disables if the page is later removed.
6559                    if r.from_page_id.is_none() {
6560                        r.from_page_id = Some(id);
6561                    }
6562                    r.save(pool).await.log_warn("redirect not linked to its source page");
6563                }
6564                continue;
6565            }
6566            // Compress incoming chain: if an OLD existing row was
6567            // pointing TO old_path, redirect it straight to new_path
6568            // instead so the chain stays one hop.
6569            let stale_chain: Vec<crate::redirect::Redirect> = crate::redirect::Redirect::objects()
6570                .where_(crate::redirect::Redirect::to_path.eq(old_path.clone()))
6571                .fetch(pool)
6572                .await
6573                .unwrap_or_default();
6574            for mut r in stale_chain {
6575                // #708 — renaming back (A → B, then B → A) would chain
6576                // A → B into A → A. The page lives at A again, so the
6577                // rule has nothing left to do.
6578                if r.from_path == new_path {
6579                    r.delete(pool)
6580                        .await
6581                        .log_warn("self-redirect left after a rename back not deleted");
6582                    continue;
6583                }
6584                r.to_path = new_path.clone();
6585                r.note = format!("auto-chained on page rename at {now}");
6586                r.save(pool).await.log_warn("redirect chain not updated after a rename");
6587            }
6588            // Insert the fresh old → new row.
6589            let mut row = crate::redirect::Redirect {
6590                id: rustango::sql::Auto::Unset,
6591                from_path: old_path,
6592                to_path: new_path,
6593                is_permanent: true,
6594                note: format!("auto-created on page rename at {now}"),
6595                hit_count: 0,
6596                overrides_live: false,
6597                // Link the renamed page so the rule auto-disables if the
6598                // page is later deleted/unpublished (#553).
6599                from_page_id: Some(id),
6600                to_page_id: None,
6601                is_active: true,
6602                disabled_reason: String::new(),
6603                last_hit_at: None,
6604                created_at: rustango::sql::Auto::Unset,
6605                updated_at: rustango::sql::Auto::Unset,
6606            };
6607            if row.insert(pool).await.is_ok() {
6608                redirects_created += 1;
6609            }
6610        }
6611    }
6612
6613    // #78 cache invalidation for the affected URLs is registered via
6614    // `on_commit` inside the save block above (#317), so it fires only
6615    // once the save commits and doesn't block this response.
6616
6617    // #73 PR 3 — reapproval-on-edit. When the page type is bound to
6618    // a workflow whose `require_reapproval_on_edit` flag is set, and
6619    // the page has previously been through review (any approved
6620    // WorkflowState in its history), restart the workflow on this
6621    // save. The page stays at its current status; a fresh
6622    // WorkflowState pinned to task #1 kicks off a new approval
6623    // cycle. No-op when no active workflow exists for the type, or
6624    // when the page hasn't been approved yet (first-time submitters
6625    // explicitly submit via the action bar).
6626    let mut reapproval_kicked = false;
6627    if let (Some(viewer_id), Some(pt)) = (actor.map(|a| a.id), pt_opt.as_ref()) {
6628        if let Some(slug) = pt.workflow_name() {
6629            if let Some(workflow) = crate::workflow::find_by_name(pool, &slug).await? {
6630                if workflow.require_reapproval_on_edit
6631                    && crate::workflow::active_state_for_page(pool, id)
6632                        .await?
6633                        .is_none()
6634                    && crate::workflow::has_prior_approval(pool, id).await?
6635                {
6636                    let tasks = crate::workflow::tasks_for(
6637                        pool,
6638                        workflow.id.get().copied().unwrap_or_default(),
6639                    )
6640                    .await?;
6641                    if !tasks.is_empty() {
6642                        crate::workflow::submit_for_review(
6643                            pool, id, &workflow, &tasks, viewer_id,
6644                        )
6645                        .await?;
6646                        reapproval_kicked = true;
6647                    }
6648                }
6649            }
6650        }
6651    }
6652
6653    // Public render cache (rustango::cache_page::CachePageLayer)
6654    // is TTL-based; the new/old/descendant URLs propagate after the
6655    // configured TTL elapses.
6656    let _ = (&new_url_path, slug_changed, &old_url_path, &descendant_urls);
6657    // #553 — this save took the page out of Published: redirect rules
6658    // linked to it must not keep serving (a dead source URL, or a
6659    // destination that now 404s). Best-effort; the save itself stands.
6660    if was_published && page.status != crate::page::PageStatus::Published.as_str() {
6661        match crate::redirect::disable_for_page(
6662            pool,
6663            id,
6664            &format!("Linked page “{}” was unpublished", page.title),
6665        )
6666        .await
6667        {
6668            Ok(0) => {}
6669            Ok(n) => {
6670                tracing::info!(
6671                    page_id = id,
6672                    disabled = n,
6673                    "disabled redirects for unpublished page"
6674                );
6675            }
6676            Err(e) => {
6677                tracing::warn!(page_id = id, error = %e, "failed to disable redirects for unpublished page");
6678            }
6679        }
6680    }
6681
6682    // A save that went through directly (a superuser's) supersedes a
6683    // change held for review; the editor showed it pre-filled.
6684    if actor.is_some() {
6685        crate::pending_change::discard(pool, id).await?;
6686    }
6687
6688    Ok(Ok(PageEditOutcome {
6689        page,
6690        redirects_created,
6691        reapproval_kicked,
6692        held_for_review: false,
6693        unchanged: false,
6694    }))
6695}
6696
6697pub async fn page_edit_submit(
6698    State(_state): State<super::AdminState>,
6699    tenant: Tenant,
6700    headers: HeaderMap,
6701    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
6702    Path(id): Path<i64>,
6703    Form(form_map): Form<std::collections::HashMap<String, String>>,
6704) -> Result<Response, AdminError> {
6705    let actor = session_user.as_ref().map(|u| PageEditActor {
6706        id: u.id.get().copied().unwrap_or_default(),
6707        username: u.username.clone(),
6708        is_superuser: u.is_superuser,
6709    });
6710    let outcome = apply_page_edit(
6711        tenant.pool(),
6712        &tenant_key(&tenant.org)?,
6713        &_state.cache_invalidator,
6714        _state.mailer.as_deref(),
6715        &_state.mailer_from,
6716        true,
6717        id,
6718        &form_map,
6719        actor.as_ref(),
6720    )
6721    .await?;
6722    let PageEditOutcome {
6723        page,
6724        redirects_created,
6725        reapproval_kicked,
6726        held_for_review,
6727        unchanged,
6728    } = match outcome {
6729        Ok(o) => o,
6730        Err(PageEditRefusal::WorkflowReview { task_name }) => {
6731            return redirect_named_with_params_and_message_args(
6732                "rcms-admin:pages:edit",
6733                &[("id", id.to_string())],
6734                MsgLevel::Error,
6735                "Couldn't save — page is under review on “{name}”. Only reviewers of that step can edit during review.",
6736                &[("name", task_name.as_str())],
6737                &headers,
6738            );
6739        }
6740        Err(PageEditRefusal::LockedBy { holder }) => {
6741            return redirect_named_with_params_and_message_args(
6742                "rcms-admin:pages:edit",
6743                &[("id", id.to_string())],
6744                MsgLevel::Error,
6745                "Couldn't save — “{holder}” is editing this page right now. Force-unlock to take over.",
6746                &[("holder", holder.as_str())],
6747                &headers,
6748            );
6749        }
6750        Err(PageEditRefusal::ArchivedUnpublish) => {
6751            return redirect_named_with_params_and_message_args(
6752                "rcms-admin:pages:edit",
6753                &[("id", id.to_string())],
6754                MsgLevel::Error,
6755                "Can't unpublish an archived page. Set it back to Published to unarchive, or delete it after unarchiving.",
6756                &[],
6757                &headers,
6758            );
6759        }
6760        Err(PageEditRefusal::PublishDenied) => {
6761            return redirect_named_with_params_and_message(
6762                "rcms-admin:pages:edit",
6763                &[("id", id.to_string())],
6764                MsgLevel::Error,
6765                "You don't have permission to publish this page — save it as a draft or submit it for review.",
6766                &headers,
6767            );
6768        }
6769        Err(PageEditRefusal::ReviewRequired { workflow }) => {
6770            return redirect_named_with_params_and_message_args(
6771                "rcms-admin:pages:edit",
6772                &[("id", id.to_string())],
6773                MsgLevel::Error,
6774                "Pages of this type go live after review (“{workflow}”). Save it as a draft and click Submit for review.",
6775                &[("workflow", workflow.as_str())],
6776                &headers,
6777            );
6778        }
6779        Err(PageEditRefusal::Conflict { conflicts, page }) => {
6780            let conflict = EditConflict { conflicts, page: *page, form: form_map };
6781            return render_page_edit_form(
6782                &_state,
6783                tenant.pool(),
6784                &tenant.org,
6785                &headers,
6786                session_user,
6787                id,
6788                EditQuery::default(),
6789                Some(conflict),
6790            )
6791            .await;
6792        }
6793    };
6794    if unchanged {
6795        return redirect_after_page_save_with_level(
6796            form_map.get("_action").map_or("save", String::as_str),
6797            id,
6798            page.parent_id,
6799            &super::i18n::tr(&headers, "No changes to save.", &[]),
6800            MsgLevel::Info,
6801            &headers,
6802        );
6803    }
6804    if held_for_review {
6805        return redirect_after_page_save(
6806            form_map.get("_action").map_or("save", String::as_str),
6807            id,
6808            page.parent_id,
6809            &super::i18n::tr(
6810                &headers,
6811                "Your changes to “{title}” wait for review. Visitors see the live page until they are approved.",
6812                &[("title", page.title.as_str())],
6813            ),
6814            &headers,
6815        );
6816    }
6817    let mut message = if redirects_created > 0 {
6818        let count = redirects_created.to_string();
6819        super::i18n::tr_plural(
6820            &headers,
6821            "Saved “{title}”. Auto-created {count} redirect(s) from the old URL(s).",
6822            redirects_created as i64,
6823            &[("title", page.title.as_str()), ("count", count.as_str())],
6824        )
6825    } else {
6826        super::i18n::tr(
6827            &headers,
6828            "Saved “{title}”.",
6829            &[("title", page.title.as_str())],
6830        )
6831    };
6832    if reapproval_kicked {
6833        message.push(' ');
6834        message.push_str(&super::i18n::tr(
6835            &headers,
6836            "Workflow restarted — page enters review again.",
6837            &[],
6838        ));
6839    }
6840    redirect_after_page_save(
6841        form_map.get("_action").map_or("save", String::as_str),
6842        id,
6843        page.parent_id,
6844        &message,
6845        &headers,
6846    )
6847}
6848
6849/// POST /cms-admin/pages/{id}/translate?locale=<code> — upsert
6850/// `cms_translation` rows for the given locale. Empty values delete
6851/// the matching row so the canonical content shows through.
6852///
6853/// Accepts arbitrary field paths (the three core ones — `title`,
6854/// `seo_title`, `seo_description` — plus any custom `field_path`
6855/// referenced by the page's template, e.g. `intro`, `body`,
6856/// `nav_about`). The form sends them as `tr__<path>` keys; the
6857/// "add new key" row uses `new_field_path` + `new_field_value`.
6858/// Apply one batch of translation overrides for `(page_id, locale_id)`:
6859/// an empty value deletes the override row, a non-empty one upserts it.
6860/// Wrapped in `atomic!` so a mid-loop failure rolls back the whole batch —
6861/// callers never leave half-applied translations behind. Callers are
6862/// responsible for locale validation (in particular: never the default
6863/// locale — canonical content lives on `cms_page`).
6864pub(crate) async fn upsert_page_translations(
6865    pool: &rustango::sql::Pool,
6866    page_id: i64,
6867    locale_id: i64,
6868    updates: Vec<(String, String)>,
6869) -> Result<(), rustango::sql::ExecError> {
6870    rustango::atomic!(pool, |tx| {
6871        let mut guard = tx.lock().await?;
6872        let tx = &mut *guard;
6873        for (path, value) in updates {
6874            if value.is_empty() {
6875                let rows: Vec<crate::translation::Translation> =
6876                    crate::translation::Translation::objects()
6877                        .where_(crate::translation::Translation::page_id.eq(page_id))
6878                        .where_(crate::translation::Translation::locale_id.eq(locale_id))
6879                        .where_(crate::translation::Translation::field_path.eq(path.clone()))
6880                        .fetch_tx(tx)
6881                        .await?;
6882                for row in rows {
6883                    row.delete_tx(tx).await?;
6884                }
6885            } else {
6886                let existing: Vec<crate::translation::Translation> =
6887                    crate::translation::Translation::objects()
6888                        .where_(crate::translation::Translation::page_id.eq(page_id))
6889                        .where_(crate::translation::Translation::locale_id.eq(locale_id))
6890                        .where_(crate::translation::Translation::field_path.eq(path.clone()))
6891                        .fetch_tx(tx)
6892                        .await?;
6893                if let Some(mut row) = existing.into_iter().next() {
6894                    row.value = value;
6895                    row.save_tx(tx).await?;
6896                } else {
6897                    let mut row = crate::translation::Translation {
6898                        id: rustango::sql::Auto::Unset,
6899                        page_id,
6900                        locale_id,
6901                        field_path: path,
6902                        value,
6903                        updated_at: rustango::sql::Auto::Unset,
6904                    };
6905                    row.save_tx(tx).await?;
6906                }
6907            }
6908        }
6909        Ok::<_, rustango::sql::ExecError>(())
6910    })
6911    .await
6912}
6913
6914pub async fn page_translate_submit(
6915    State(_state): State<super::AdminState>,
6916    tenant: Tenant,
6917    Path(id): Path<i64>,
6918    Query(q): Query<EditQuery>,
6919    Form(form): Form<std::collections::HashMap<String, String>>,
6920) -> Result<Response, AdminError> {
6921    let code = q
6922        .locale
6923        .as_deref()
6924        .filter(|c| !c.is_empty())
6925        .ok_or_else(|| AdminError::Validation("translate requires ?locale=".to_owned()))?;
6926    let locale = Locale::objects()
6927        .where_(Locale::code.eq(code.to_owned()))
6928        .where_(Locale::active.eq(true))
6929        .first(tenant.pool())
6930        .await?
6931        .ok_or_else(|| AdminError::Validation(format!("unknown locale `{code}`")))?;
6932    if locale.is_default {
6933        return Ok((
6934            axum::http::StatusCode::BAD_REQUEST,
6935            "cannot translate INTO the default locale; canonical content lives on cms_page",
6936        )
6937            .into_response());
6938    }
6939    let locale_id = locale
6940        .id
6941        .get()
6942        .copied()
6943        .ok_or_else(|| AdminError::Validation("locale row missing id".to_owned()))?;
6944    // Verify the page exists; cheap one-row select.
6945    let _page = Page::objects()
6946        .where_(Page::id.eq(id))
6947        .first(tenant.pool())
6948        .await?
6949        .ok_or(AdminError::NotFound(id))?;
6950
6951    // Collect updates from the form. Keys starting with `tr__` are
6952    // existing-row edits; `new_field_path` + `new_field_value` is the
6953    // single "add new key" row at the bottom of the editor.
6954    let mut updates: Vec<(String, String)> = Vec::new();
6955    for (k, v) in &form {
6956        if let Some(path) = k.strip_prefix("tr__") {
6957            if path.is_empty() {
6958                continue;
6959            }
6960            updates.push((path.to_owned(), v.clone()));
6961        }
6962    }
6963    let new_path = form
6964        .get("new_field_path")
6965        .map(|s| s.trim().to_owned())
6966        .unwrap_or_default();
6967    if !new_path.is_empty() {
6968        let new_value = form.get("new_field_value").cloned().unwrap_or_default();
6969        // Validate shape via the shared guard (≤255, alphanumeric + `_`
6970        // `.` `-`) — allows dotted block-UUID paths into StreamFields.
6971        if let Ok(path) = crate::translation::validate_field_path(&new_path) {
6972            updates.push((path, new_value));
6973        }
6974    }
6975
6976    upsert_page_translations(tenant.pool(), id, locale_id, updates).await?;
6977
6978    // Invalidate cache for both the canonical and `?lang=` keys so
6979    // the next public hit re-renders with the updated translations.
6980    let page = Page::objects()
6981        .where_(Page::id.eq(id))
6982        .first(tenant.pool())
6983        .await?
6984        .ok_or(AdminError::NotFound(id))?;
6985    // Public render cache (rustango::cache_page::CachePageLayer)
6986    // expires on TTL; translation edits propagate after the
6987    // configured timeout.
6988    let _ = (page, &code);
6989
6990    Ok(Redirect::to(&format!("/cms-admin/pages/{id}/edit?locale={code}")).into_response())
6991}
6992
6993/// POST /cms-admin/pages/{id}/delete — refuse if page has children,
6994/// otherwise delete the row. Cascade-delete-with-children deferred.
6995pub async fn page_delete_submit(
6996    State(_state): State<super::AdminState>,
6997    tenant: Tenant,
6998    headers: HeaderMap,
6999    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
7000    Path(id): Path<i64>,
7001) -> Result<Response, AdminError> {
7002    let page = Page::objects()
7003        .where_(Page::id.eq(id))
7004        .first(tenant.pool())
7005        .await?
7006        .ok_or(AdminError::NotFound(id))?;
7007
7008    // #556 — archived pages are frozen against deletion (archive is a
7009    // preservation lock, not a step toward removal). The editor must
7010    // unarchive first.
7011    if page.status == crate::page::PageStatus::Archived.as_str() {
7012        return redirect_named_with_message_args(
7013            "rcms-admin:pages:list",
7014            MsgLevel::Error,
7015            "Can't delete “{title}” while archived — unarchive it first.",
7016            &[("title", page.title.as_str())],
7017            &headers,
7018        );
7019    }
7020
7021    let child_count: Vec<Page> = Page::objects()
7022        .where_(Page::parent_id.eq(id))
7023        .fetch(tenant.pool())
7024        .await?;
7025    if !child_count.is_empty() {
7026        let count = child_count.len().to_string();
7027        return redirect_named_with_message_plural(
7028            "rcms-admin:pages:list",
7029            MsgLevel::Error,
7030            "Can't delete “{title}” — it has {count} child page(s). Delete or move them first.",
7031            child_count.len() as i64,
7032            &[("title", page.title.as_str()), ("count", count.as_str())],
7033            &headers,
7034        );
7035    }
7036
7037    // A hostname pointing at this root has a foreign key to it, so the
7038    // delete would fail with an opaque FK error. Refuse with the names
7039    // instead — and refuse rather than dropping the mapping, because a
7040    // live domain quietly falling back to a different site is a change
7041    // only visitors would notice.
7042    let serving_hosts = crate::site::hosts_for_root(tenant.pool(), id).await?;
7043    if !serving_hosts.is_empty() {
7044        let hosts = serving_hosts.join(", ");
7045        return redirect_named_with_message_args(
7046            "rcms-admin:pages:list",
7047            MsgLevel::Error,
7048            "Can't delete “{title}” — it is the root served by {hosts}. Change that on the Sites screen first.",
7049            &[("title", page.title.as_str()), ("hosts", hosts.as_str())],
7050            &headers,
7051        );
7052    }
7053
7054    // #75 — promote any aliases of this page to standalone pages
7055    // before deleting the source. Each alias inherits a snapshot of
7056    // the source's content (title / SEO / status / theme) so its
7057    // public URL keeps rendering coherent content after the source
7058    // is gone. Without this step the FK guard would refuse the
7059    // delete, or worse — aliases would point at a dead row.
7060    let aliases: Vec<Page> = Page::objects()
7061        .where_(Page::alias_of.eq(id))
7062        .fetch(tenant.pool())
7063        .await?;
7064    let alias_count = aliases.len();
7065    let title = page.title.clone();
7066    let url_path = page.url_path.clone();
7067
7068    // #317 — alias promotion + the delete run in one `atomic!` block,
7069    // so a failure can't leave aliases promoted against a still-present
7070    // source. The #78 cache purge is registered via `on_commit`, so it
7071    // fires only once the delete commits — a rollback never evicts a
7072    // still-valid public render. The purge runs detached, so the next
7073    // visitor sees a 404, not a stale 200, without blocking this
7074    // response on the cache round-trip.
7075    let invalidator = _state.cache_invalidator.clone();
7076    let tenant_slug = tenant_key(&tenant.org)?;
7077    let purge_url = url_path.clone();
7078    rustango::atomic!(tenant.pool(), |tx| {
7079        let mut guard = tx.lock().await?;
7080        let tx = &mut *guard;
7081        for mut alias in aliases {
7082            alias.alias_of = None;
7083            alias.title = page.title.clone();
7084            alias.seo_title = page.seo_title.clone();
7085            alias.seo_description = page.seo_description.clone();
7086            alias.status = page.status.clone();
7087            alias.published_at = page.published_at;
7088            alias.last_published_at = page.last_published_at;
7089            alias.theme_id = page.theme_id;
7090            alias.show_in_menus = page.show_in_menus;
7091            alias.save_tx(tx).await?;
7092        }
7093        // Revisions, tags, logs… point at the page with no ON DELETE
7094        // action; clear them first or the delete fails.
7095        crate::page_delete::clear_page_references_tx(tx, id).await?;
7096        page.delete_tx(tx).await?;
7097        crate::cache_invalidate::invalidate_urls_on_commit(
7098            invalidator,
7099            tenant_slug,
7100            vec![purge_url],
7101        );
7102        Ok(())
7103    })
7104    .await?;
7105    // #408 — drop the deleted page from the external search index
7106    // (no-op when no backend is installed).
7107    crate::task_queue::remove_page_search(&tenant.org.slug, id).await;
7108    // #553 — redirect rules linked to this page must not keep serving.
7109    // Best-effort; the delete already committed.
7110    if let Err(e) = crate::redirect::disable_for_page(
7111        tenant.pool(),
7112        id,
7113        &format!("Linked page “{title}” was deleted"),
7114    )
7115    .await
7116    {
7117        tracing::warn!(page_id = id, error = %e, "failed to disable redirects for deleted page");
7118    }
7119    if alias_count > 0 {
7120        redirect_named_with_message_plural(
7121            "rcms-admin:pages:list",
7122            MsgLevel::Success,
7123            "Deleted “{title}”. Promoted {count} alias(es) to standalone page(s) with the source's last content.",
7124            alias_count as i64,
7125            &[("title", title.as_str()), ("count", &alias_count.to_string())],
7126            &headers,
7127        )
7128    } else {
7129        redirect_named_with_message_args(
7130            "rcms-admin:pages:list",
7131            MsgLevel::Success,
7132            "Deleted “{title}”.",
7133            &[("title", title.as_str())],
7134            &headers,
7135        )
7136    }
7137}
7138
7139// =====================================================================
7140// Slice 6 — drag-reorder + locale variants
7141// =====================================================================
7142
7143/// Form payload for `POST /cms-admin/pages/{id}/move` — emitted by
7144/// the tree view's drag-and-drop JS.
7145#[derive(Debug, Deserialize)]
7146pub struct MoveForm {
7147    /// The drop target's page id. The moved page becomes a child of
7148    /// this row (appended at the bottom of its existing children).
7149    /// Negative or zero values mean "move to root".
7150    pub new_parent: i64,
7151}
7152
7153/// POST /cms-admin/pages/{id}/move — change a page's parent +
7154/// sort_order via the existing `Page::move_to`. Wraps the cascade so
7155/// every descendant's `url_path` is re-materialized.
7156pub async fn page_move_submit(
7157    State(_state): State<super::AdminState>,
7158    tenant: Tenant,
7159    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
7160    Path(id): Path<i64>,
7161    Form(form): Form<MoveForm>,
7162) -> Result<Response, AdminError> {
7163    let mut page = Page::objects()
7164        .where_(Page::id.eq(id))
7165        .first(tenant.pool())
7166        .await?
7167        .ok_or(AdminError::NotFound(id))?;
7168    let new_parent: Option<Page> = if form.new_parent > 0 {
7169        Page::objects()
7170            .where_(Page::id.eq(form.new_parent))
7171            .first(tenant.pool())
7172            .await?
7173    } else {
7174        None
7175    };
7176    let old_url_path = page.url_path.clone();
7177    let old_descendant_urls: Vec<String> =
7178        page.descendants(tenant.pool()).await?.into_iter().map(|d| d.url_path).collect();
7179    // One transaction moves the tree and its URLs together (#706).
7180    page.move_to(&tenant, new_parent.as_ref()).await?;
7181    let new_url_path = page.url_path.clone();
7182
7183    // #78 — purge the old and new URL of the page and every descendant,
7184    // now that the move has committed; detached so the response isn't
7185    // blocked on the cache round-trips.
7186    let mut urls = old_descendant_urls;
7187    urls.push(old_url_path.clone());
7188    urls.push(new_url_path.clone());
7189    urls.extend(page.descendants(tenant.pool()).await?.into_iter().map(|d| d.url_path));
7190    let invalidator = _state.cache_invalidator.clone();
7191    let tenant_slug = tenant_key(&tenant.org)?;
7192    rustango::__private_runtime::tokio::spawn(async move {
7193        crate::task_queue::purge_urls(invalidator, tenant_slug, urls).await;
7194    });
7195
7196    // #192 — audit-log the move.
7197    let actor_id = session_user.as_ref().and_then(|u| u.id.get().copied());
7198    crate::page_log::record_or_warn(
7199        tenant.pool(),
7200        id,
7201        crate::page_log::ACTION_MOVE,
7202        actor_id,
7203        format!(
7204            "Moved “{}” from {old_url_path} to {new_url_path}.",
7205            page.title
7206        ),
7207        Some(serde_json::json!({
7208            "old_url_path": old_url_path,
7209            "new_url_path": new_url_path,
7210            "new_parent_id": form.new_parent,
7211        })),
7212    )
7213    .await;
7214
7215    Ok((axum::http::StatusCode::OK, "ok").into_response())
7216}
7217
7218/// POST /cms-admin/pages/{id}/clone — duplicate the source page as a
7219/// draft sibling. The copy carries everything the page stores —
7220/// core fields (SEO, OG/Twitter, theme, template override), tags, the
7221/// extension row, inline panels and the page-builder body — because it
7222/// is saved through the same pipeline as an edit, from the source's
7223/// [`crate::page_form::prefill`]. The new row:
7224///
7225/// - Lives under the same parent as the source.
7226/// - Title gets a " (copy)" suffix.
7227/// - Slug gets a "-copy" suffix; on conflict with an existing
7228///   sibling slug, we suffix `-copy-2`, `-copy-3`, … until unique.
7229/// - Status forces back to Draft, with no schedule, so editors review
7230///   before publishing.
7231/// - Locale-variant pointer cleared (variants stay independent of
7232///   any single source).
7233///
7234/// Subtree clone (source + all descendants) is not supported yet.
7235pub async fn page_clone_submit(
7236    State(state): State<super::AdminState>,
7237    tenant: Tenant,
7238    headers: HeaderMap,
7239    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
7240    Path(id): Path<i64>,
7241) -> Result<Response, AdminError> {
7242    let source = Page::objects()
7243        .where_(Page::id.eq(id))
7244        .first(tenant.pool())
7245        .await?
7246        .ok_or(AdminError::NotFound(id))?;
7247
7248    let title = format!("{} (copy)", source.title);
7249    let base_slug = source.slug.trim_matches('-').to_owned();
7250    let slug = unique_sibling_slug(
7251        tenant.pool(),
7252        source.parent_id,
7253        &format!("{base_slug}-copy"),
7254    )
7255    .await?;
7256
7257    let new = crate::tree_ops::NewPage::new(source.page_type_id, title, slug)
7258        .with_status(crate::page::PageStatus::Draft)
7259        .with_seo(source.seo_title.clone(), source.seo_description.clone());
7260
7261    let clone = match source.parent_id {
7262        Some(pid) => {
7263            let parent = Page::objects()
7264                .where_(Page::id.eq(pid))
7265                .first(tenant.pool())
7266                .await?
7267                .ok_or(AdminError::NotFound(pid))?;
7268            Page::create_child(&tenant, &parent, new).await?
7269        }
7270        None => Page::create_root(&tenant, new).await?,
7271    };
7272    let new_id = clone.id.get().copied().unwrap_or_default();
7273
7274    // Copy the content by saving the source's full form onto the new
7275    // row: the edit pipeline writes the core fields, tags, extension,
7276    // inline panels and builder body, and captures the first revision
7277    // with all of it.
7278    let mut form = crate::page_form::prefill(tenant.pool(), &source).await;
7279    form.insert("title".into(), clone.title.clone());
7280    form.insert("slug".into(), clone.slug.clone());
7281    form.insert(
7282        "status".into(),
7283        crate::page::PageStatus::Draft.as_str().to_owned(),
7284    );
7285    form.remove("go_live_at");
7286    form.remove("expire_at");
7287    let actor = session_user.as_ref().map(|u| PageEditActor {
7288        id: u.id.get().copied().unwrap_or_default(),
7289        username: u.username.clone(),
7290        is_superuser: u.is_superuser,
7291    });
7292    let saved = apply_page_edit(
7293        tenant.pool(),
7294        &tenant_key(&tenant.org)?,
7295        &state.cache_invalidator,
7296        None,
7297        "",
7298        false,
7299        new_id,
7300        &form,
7301        actor.as_ref(),
7302    )
7303    .await?;
7304    match saved {
7305        // A copy with nothing beyond its title and slug wrote nothing;
7306        // it still starts its history with a revision.
7307        Ok(o) if o.unchanged => {
7308            crate::revision::capture(tenant.pool(), &o.page, actor.as_ref().map(|a| a.id))
7309                .await
7310                .log_warn("revision not captured; the history has a gap");
7311        }
7312        Ok(_) => {}
7313        // A page created a moment ago has no workflow or editor lock.
7314        Err(_) => {
7315            return Err(AdminError::Validation(
7316                "the copy was created but its content could not be saved".to_owned(),
7317            ));
7318        }
7319    }
7320    // #192 — audit-log the clone on BOTH the new row (so the new
7321    // page's history shows where it came from) and the source (so
7322    // the source's history records its descendants).
7323    let actor_id = session_user.as_ref().and_then(|u| u.id.get().copied());
7324    crate::page_log::record_or_warn(
7325        tenant.pool(),
7326        new_id,
7327        crate::page_log::ACTION_COPY,
7328        actor_id,
7329        format!("Cloned from “{}” (page #{id}).", source.title),
7330        Some(serde_json::json!({ "source_page_id": id })),
7331    )
7332    .await;
7333    crate::page_log::record_or_warn(
7334        tenant.pool(),
7335        id,
7336        crate::page_log::ACTION_COPY,
7337        actor_id,
7338        format!("Cloned to new draft page #{new_id}."),
7339        Some(serde_json::json!({ "clone_page_id": new_id })),
7340    )
7341    .await;
7342    redirect_named_with_params_and_message_args(
7343        "rcms-admin:pages:edit",
7344        &[("id", new_id.to_string())],
7345        MsgLevel::Success,
7346        "Cloned “{title}” as a draft. Review before publishing.",
7347        &[("title", source.title.as_str())],
7348        &headers,
7349    )
7350}
7351
7352/// Form payload for `POST /cms-admin/pages/{id}/privacy`.
7353/// `kind` is one of `"none"`, `"login"`, `"groups"`, `"password"`.
7354/// `password` is the cleartext entered when `kind=password` (hashed
7355/// + discarded server-side). `group_ids` is the comma-separated list
7356/// for `kind=groups`.
7357#[derive(Deserialize)]
7358pub struct PrivacyForm {
7359    pub kind: String,
7360    #[serde(default)]
7361    pub password: String,
7362    #[serde(default)]
7363    pub group_ids: String,
7364    /// Comma-separated permission codenames — used when `kind =
7365    /// permission` (the permission-engine gate). Empty otherwise.
7366    #[serde(default)]
7367    pub codenames: String,
7368}
7369
7370pub async fn page_privacy_submit(
7371    State(_state): State<super::AdminState>,
7372    tenant: Tenant,
7373    headers: HeaderMap,
7374    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
7375    Path(id): Path<i64>,
7376    Form(form): Form<PrivacyForm>,
7377) -> Result<Response, AdminError> {
7378    use rustango::sql::Auto;
7379    let existing = crate::view_restriction::direct_for_page(tenant.pool(), id).await?;
7380    if form.kind == "none" {
7381        if let Some(row) = existing {
7382            row.delete(tenant.pool()).await?;
7383            return redirect_named_with_params_and_message(
7384                "rcms-admin:pages:edit",
7385                &[("id", id.to_string())],
7386                MsgLevel::Success,
7387                "Removed view restriction — page is now public.",
7388                &headers,
7389            );
7390        }
7391        return redirect_named_with_params_and_message(
7392            "rcms-admin:pages:edit",
7393            &[("id", id.to_string())],
7394            MsgLevel::Info,
7395            "No restriction to remove.",
7396            &headers,
7397        );
7398    }
7399    let Some(kind) = crate::view_restriction::RestrictionKind::parse(&form.kind) else {
7400        return Err(AdminError::Validation(format!(
7401            "unknown restriction kind `{}`",
7402            form.kind
7403        )));
7404    };
7405    let password_hash = match kind {
7406        crate::view_restriction::RestrictionKind::Password => {
7407            // Reuse the existing hash when the editor left the
7408            // field blank on a page that's already password-
7409            // protected — lets them flip groups/login back to
7410            // password without remembering the original.
7411            if form.password.is_empty() {
7412                if let Some(row) = &existing {
7413                    if row.kind == kind.as_str() {
7414                        row.password_hash.clone()
7415                    } else {
7416                        return redirect_named_with_params_and_message(
7417                            "rcms-admin:pages:edit",
7418                            &[("id", id.to_string())],
7419                            MsgLevel::Error,
7420                            "Password is required when switching the restriction kind to password.",
7421                            &headers,
7422                        );
7423                    }
7424                } else {
7425                    return redirect_named_with_params_and_message(
7426                        "rcms-admin:pages:edit",
7427                        &[("id", id.to_string())],
7428                        MsgLevel::Error,
7429                        "Password is required for password-protected pages.",
7430                        &headers,
7431                    );
7432                }
7433            } else {
7434                crate::passwords::hash(&form.password).await
7435                    .map_err(|e| AdminError::Validation(format!("password hash failed: {e}")))?
7436            }
7437        }
7438        _ => String::new(),
7439    };
7440    let group_ids: Vec<i64> = if matches!(kind, crate::view_restriction::RestrictionKind::Groups) {
7441        form.group_ids
7442            .split(',')
7443            .filter_map(|s| s.trim().parse::<i64>().ok())
7444            .collect()
7445    } else {
7446        Vec::new()
7447    };
7448    let group_json = serde_json::json!(group_ids);
7449    let codenames: Vec<String> =
7450        if matches!(kind, crate::view_restriction::RestrictionKind::Permission) {
7451            form.codenames
7452                .split(',')
7453                .map(str::trim)
7454                .filter(|s| !s.is_empty())
7455                .map(str::to_owned)
7456                .collect()
7457        } else {
7458            Vec::new()
7459        };
7460    let codenames_json = serde_json::json!(codenames);
7461    match existing {
7462        Some(mut row) => {
7463            row.kind = kind.as_str().to_owned();
7464            row.password_hash = password_hash;
7465            row.group_ids = group_json;
7466            row.codenames = codenames_json;
7467            row.save(tenant.pool()).await?;
7468        }
7469        None => {
7470            let mut row = crate::view_restriction::PageViewRestriction {
7471                id: Auto::Unset,
7472                page_id: id,
7473                kind: kind.as_str().to_owned(),
7474                password_hash,
7475                group_ids: group_json,
7476                codenames: codenames_json,
7477                created_at: Auto::Unset,
7478                updated_at: Auto::Unset,
7479            };
7480            row.insert(tenant.pool()).await?;
7481        }
7482    }
7483    redirect_named_with_params_and_message_args(
7484        "rcms-admin:pages:edit",
7485        &[("id", id.to_string())],
7486        MsgLevel::Success,
7487        match kind {
7488            crate::view_restriction::RestrictionKind::Login => "Only signed-in people can see this page now.",
7489            crate::view_restriction::RestrictionKind::Groups => "Only the chosen roles can see this page now.",
7490            crate::view_restriction::RestrictionKind::Permission => "Only people with the chosen permissions can see this page now.",
7491            crate::view_restriction::RestrictionKind::Password => "This page asks for a password now.",
7492        },
7493        &[],
7494        &headers,
7495    )
7496}
7497
7498// =====================================================================
7499// Inline comments (#81 PR 1)
7500// =====================================================================
7501
7502#[derive(Debug, Deserialize)]
7503pub struct CommentNewForm {
7504    pub field_path: String,
7505    pub body: String,
7506}
7507
7508pub async fn comment_new_submit(
7509    State(_state): State<super::AdminState>,
7510    tenant: Tenant,
7511    headers: HeaderMap,
7512    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
7513    Path(id): Path<i64>,
7514    Form(form): Form<CommentNewForm>,
7515) -> Result<Response, AdminError> {
7516    let Some(viewer_id) = session_user.as_ref().and_then(|u| u.id.get().copied()) else {
7517        return Ok(unauthorized_no_session());
7518    };
7519    let body = form.body.trim();
7520    let field_path = form.field_path.trim();
7521    if body.is_empty() || field_path.is_empty() {
7522        return redirect_named_with_params_and_message(
7523            "rcms-admin:pages:edit",
7524            &[("id", id.to_string())],
7525            MsgLevel::Warning,
7526            "Comment body and field are both required.",
7527            &headers,
7528        );
7529    }
7530    let mut row = crate::comment::Comment {
7531        id: rustango::sql::Auto::Unset,
7532        page_id: id,
7533        field_path: field_path.to_owned(),
7534        author_id: viewer_id,
7535        body: body.to_owned(),
7536        resolved_at: None,
7537        resolved_by: None,
7538        created_at: rustango::sql::Auto::Unset,
7539    };
7540    row.insert(tenant.pool()).await?;
7541    redirect_named_with_params_and_message(
7542        "rcms-admin:pages:edit",
7543        &[("id", id.to_string())],
7544        MsgLevel::Success,
7545        "Comment posted.",
7546        &headers,
7547    )
7548}
7549
7550#[derive(Debug, Deserialize)]
7551pub struct CommentReplyForm {
7552    pub body: String,
7553}
7554
7555pub async fn comment_reply_submit(
7556    State(_state): State<super::AdminState>,
7557    tenant: Tenant,
7558    headers: HeaderMap,
7559    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
7560    Path((id, comment_id)): Path<(i64, i64)>,
7561    Form(form): Form<CommentReplyForm>,
7562) -> Result<Response, AdminError> {
7563    let Some(viewer_id) = session_user.as_ref().and_then(|u| u.id.get().copied()) else {
7564        return Ok(unauthorized_no_session());
7565    };
7566    let body = form.body.trim();
7567    if body.is_empty() {
7568        return redirect_named_with_params_and_message(
7569            "rcms-admin:pages:edit",
7570            &[("id", id.to_string())],
7571            MsgLevel::Warning,
7572            "Reply body is required.",
7573            &headers,
7574        );
7575    }
7576    let mut row = crate::comment::CommentReply {
7577        id: rustango::sql::Auto::Unset,
7578        comment_id,
7579        author_id: viewer_id,
7580        body: body.to_owned(),
7581        created_at: rustango::sql::Auto::Unset,
7582    };
7583    row.insert(tenant.pool()).await?;
7584    redirect_named_with_params_and_message(
7585        "rcms-admin:pages:edit",
7586        &[("id", id.to_string())],
7587        MsgLevel::Success,
7588        "Reply posted.",
7589        &headers,
7590    )
7591}
7592
7593pub async fn comment_resolve_submit(
7594    State(_state): State<super::AdminState>,
7595    tenant: Tenant,
7596    headers: HeaderMap,
7597    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
7598    Path((id, comment_id)): Path<(i64, i64)>,
7599) -> Result<Response, AdminError> {
7600    let Some(viewer_id) = session_user.as_ref().and_then(|u| u.id.get().copied()) else {
7601        return Ok(unauthorized_no_session());
7602    };
7603    let mut row = crate::comment::Comment::objects()
7604        .where_(crate::comment::Comment::id.eq(comment_id))
7605        .where_(crate::comment::Comment::page_id.eq(id))
7606        .first(tenant.pool())
7607        .await?
7608        .ok_or(AdminError::NotFound(comment_id))?;
7609    row.resolved_at = Some(chrono::Utc::now());
7610    row.resolved_by = Some(viewer_id);
7611    row.save(tenant.pool()).await?;
7612    redirect_named_with_params_and_message(
7613        "rcms-admin:pages:edit",
7614        &[("id", id.to_string())],
7615        MsgLevel::Success,
7616        "Comment resolved.",
7617        &headers,
7618    )
7619}
7620
7621pub async fn comment_reopen_submit(
7622    State(_state): State<super::AdminState>,
7623    tenant: Tenant,
7624    headers: HeaderMap,
7625    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
7626    Path((id, comment_id)): Path<(i64, i64)>,
7627) -> Result<Response, AdminError> {
7628    let mut row = crate::comment::Comment::objects()
7629        .where_(crate::comment::Comment::id.eq(comment_id))
7630        .where_(crate::comment::Comment::page_id.eq(id))
7631        .first(tenant.pool())
7632        .await?
7633        .ok_or(AdminError::NotFound(comment_id))?;
7634    row.resolved_at = None;
7635    row.resolved_by = None;
7636    row.save(tenant.pool()).await?;
7637    redirect_named_with_params_and_message(
7638        "rcms-admin:pages:edit",
7639        &[("id", id.to_string())],
7640        MsgLevel::Info,
7641        "Comment reopened.",
7642        &headers,
7643    )
7644}
7645
7646/// POST /cms-admin/pages/{id}/alias — create a live alias of this
7647/// page as a sibling. The alias is a real tree row at a
7648/// distinct URL but its content fields proxy to the source. Edits
7649/// to the source propagate instantly; edits to the alias redirect
7650/// the editor to the source.
7651///
7652/// Differentiation from sibling actions:
7653///   * Clone (`/clone`)         — deep copy, divergent content
7654///   * Alias (this)             — one source, multiple URLs
7655///
7656/// Localization uses the `cms_translation` per-field override table
7657/// (see [`crate::translation`]); the legacy structural-variant flow
7658/// was removed.
7659pub async fn page_alias_submit(
7660    State(state): State<super::AdminState>,
7661    tenant: Tenant,
7662    headers: HeaderMap,
7663    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
7664    Path(id): Path<i64>,
7665) -> Result<Response, AdminError> {
7666    let source = Page::objects()
7667        .where_(Page::id.eq(id))
7668        .first(tenant.pool())
7669        .await?
7670        .ok_or(AdminError::NotFound(id))?;
7671
7672    // Refuse to alias an alias — the chain would be impossible to
7673    // resolve without cycle detection, and there's no editorial use
7674    // case for it. Authors should alias the underlying source.
7675    if let Some(src_id) = source.alias_of {
7676        let src_id_str = src_id.to_string();
7677        return redirect_named_with_params_and_message_args(
7678            "rcms-admin:pages:edit",
7679            &[("id", id.to_string())],
7680            MsgLevel::Error,
7681            "Can't alias an alias — point your new alias at the underlying source page (#{source_id}) instead.",
7682            &[("source_id", src_id_str.as_str())],
7683            &headers,
7684        );
7685    }
7686
7687    let base_slug = source.slug.trim_matches('-').to_owned();
7688    let slug = unique_sibling_slug(
7689        tenant.pool(),
7690        source.parent_id,
7691        &if base_slug.is_empty() {
7692            "alias".to_owned()
7693        } else {
7694            format!("{base_slug}-alias")
7695        },
7696    )
7697    .await?;
7698
7699    // tree_ops::NewPage carries title/slug/page_type but the title
7700    // gets shadowed by the source on render. Use the source's title
7701    // verbatim so the admin lists still show something meaningful.
7702    let new = crate::tree_ops::NewPage::new(source.page_type_id, source.title.clone(), slug)
7703        .with_status(crate::page::PageStatus::Draft)
7704        .with_seo(source.seo_title.clone(), source.seo_description.clone());
7705
7706    let mut alias = match source.parent_id {
7707        Some(pid) => {
7708            let parent = Page::objects()
7709                .where_(Page::id.eq(pid))
7710                .first(tenant.pool())
7711                .await?
7712                .ok_or(AdminError::NotFound(pid))?;
7713            Page::create_child(&tenant, &parent, new).await?
7714        }
7715        None => Page::create_root(&tenant, new).await?,
7716    };
7717    alias.alias_of = Some(id);
7718    // Aliases inherit publish status from the source on render —
7719    // the underlying status column on the alias row is irrelevant
7720    // for live viewing, but setting it here keeps the admin list
7721    // visually accurate.
7722    alias.status = source.status.clone();
7723    alias.published_at = source.published_at;
7724    alias.last_published_at = source.last_published_at;
7725    alias.theme_id = source.theme_id;
7726    alias.show_in_menus = source.show_in_menus;
7727    alias.save(tenant.pool()).await?;
7728
7729    crate::revision::capture(tenant.pool(), &alias, None)
7730        .await
7731        .log_warn("revision not captured; the history has a gap");
7732    let new_id = alias.id.get().copied().unwrap_or_default();
7733    let _ = state;
7734    // #192 — audit log on both source + alias.
7735    let actor_id = session_user.as_ref().and_then(|u| u.id.get().copied());
7736    crate::page_log::record_or_warn(
7737        tenant.pool(),
7738        new_id,
7739        crate::page_log::ACTION_ALIAS_CREATE,
7740        actor_id,
7741        format!("Alias of “{}” (page #{id}).", source.title),
7742        Some(serde_json::json!({ "alias_of": id })),
7743    )
7744    .await;
7745    crate::page_log::record_or_warn(
7746        tenant.pool(),
7747        id,
7748        crate::page_log::ACTION_ALIAS_CREATE,
7749        actor_id,
7750        format!("New alias #{new_id} pointing here."),
7751        Some(serde_json::json!({ "alias_page_id": new_id })),
7752    )
7753    .await;
7754    redirect_named_with_params_and_message_args(
7755        "rcms-admin:pages:list",
7756        // Land on the page list (alias's edit form proxies to the
7757        // source, so /edit just bounces; the list is the right
7758        // landing). Include the alias's parent if available so the
7759        // editor sees the new alias in context.
7760        &[],
7761        MsgLevel::Success,
7762        "Created alias of “{title}”. Edits to the source will propagate to every alias's URL.",
7763        &[("title", source.title.as_str())],
7764        &headers,
7765    )
7766}
7767
7768/// Canonical fields seeded into `cms_translation` by the
7769/// copy-to-locale bulk action: the page's `title`, `seo_title`, and
7770/// `seo_description`, skipping empties. The source text gives
7771/// translators a starting point.
7772fn copy_fields_for(p: &Page) -> Vec<(&'static str, String)> {
7773    copy_translatable_fields(&p.title, &p.seo_title, &p.seo_description)
7774}
7775
7776/// Pure core of [`copy_fields_for`] — selects the non-empty canonical
7777/// fields. Split out so the selection is unit-testable without a full
7778/// `Page`.
7779fn copy_translatable_fields(
7780    title: &str,
7781    seo_title: &str,
7782    seo_description: &str,
7783) -> Vec<(&'static str, String)> {
7784    [
7785        ("title", title),
7786        ("seo_title", seo_title),
7787        ("seo_description", seo_description),
7788    ]
7789    .into_iter()
7790    .filter(|(_, v)| !v.trim().is_empty())
7791    .map(|(k, v)| (k, v.to_owned()))
7792    .collect()
7793}
7794
7795/// POST /cms-admin/pages/bulk — multi-select dispatcher for the
7796/// page list. Body shape (urlencoded):
7797/// `action=<verb>&ids=<id>&ids=<id>[&new_parent=<id>]`.
7798///
7799/// Verbs:
7800///   - `publish`     → flips every selected page's `status` to
7801///                     Published (no-op for already-published rows).
7802///   - `unpublish`   → flips to Draft (no-op for already-draft rows).
7803///   - `delete`      → bulk delete. Rejects atomically if ANY selected
7804///                     page has children — matches the per-row guard.
7805///   - `move`        → reparent every selected page under `new_parent`
7806///                     (or to root when `new_parent=0`); cascades
7807///                     `url_path` to descendants. Filters out rows
7808///                     that would form a self-loop (you can't move a
7809///                     page under itself or one of its descendants).
7810///
7811/// All four are wrapped in a single transaction so a partial failure
7812/// rolls back the entire batch. The response is a redirect back to
7813/// the page list with a flash message summarizing how many rows were
7814/// touched + which were skipped (with reason).
7815pub async fn page_bulk_submit(
7816    State(_state): State<super::AdminState>,
7817    tenant: Tenant,
7818    headers: HeaderMap,
7819    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
7820    Form(form): Form<Vec<(String, String)>>,
7821) -> Result<Response, AdminError> {
7822    let action = form
7823        .iter()
7824        .find(|(k, _)| k == "action")
7825        .map(|(_, v)| v.clone())
7826        .unwrap_or_default();
7827    let ids: Vec<i64> = form
7828        .iter()
7829        .filter(|(k, _)| k == "ids" || k == "id")
7830        .filter_map(|(_, v)| v.parse::<i64>().ok())
7831        .collect();
7832    let new_parent_raw = form
7833        .iter()
7834        .find(|(k, _)| k == "new_parent")
7835        .and_then(|(_, v)| v.parse::<i64>().ok());
7836    // #556 — archive cascade: mark every descendant's own row, not just
7837    // rely on inheritance. Accepts the checkbox/select truthy forms.
7838    let archive_cascade = form.iter().any(|(k, v)| {
7839        k == "archive_cascade" && matches!(v.as_str(), "1" | "on" | "subtree" | "true")
7840    });
7841
7842    if action.is_empty() || ids.is_empty() {
7843        return redirect_named_with_message(
7844            "rcms-admin:pages:list",
7845            MsgLevel::Warning,
7846            "Pick at least one row + an action before submitting.",
7847            &headers,
7848        );
7849    }
7850
7851    // Load the selected rows up front (one read per chunk, #631) so
7852    // per-id validation runs before any mutation; keep the posted order.
7853    let pool = tenant.pool();
7854    let pages: Vec<Page> = {
7855        let mut by_id: std::collections::HashMap<i64, Page> = std::collections::HashMap::new();
7856        for chunk in ids.chunks(500) {
7857            for p in Page::objects().where_(Page::id.is_in(chunk.to_vec())).fetch(pool).await? {
7858                if let Some(id) = p.id.get().copied() {
7859                    by_id.insert(id, p);
7860                }
7861            }
7862        }
7863        ids.iter().filter_map(|id| by_id.remove(id)).collect()
7864    };
7865    if pages.is_empty() {
7866        return redirect_named_with_message(
7867            "rcms-admin:pages:list",
7868            MsgLevel::Warning,
7869            "None of the selected ids matched a live page.",
7870            &headers,
7871        );
7872    }
7873
7874    // #672 — the route gate only knows this is a page edit; the action
7875    // posted decides what it really needs, on every selected page.
7876    let needs = match action.as_str() {
7877        "publish" | "unpublish" => crate::permissions::Action::Publish,
7878        "delete" => crate::permissions::Action::Delete,
7879        _ => crate::permissions::Action::Edit,
7880    };
7881    if let Some(user) = session_user.as_ref() {
7882        for p in &pages {
7883            let req = super::route_perms::Requirement {
7884                codename: format!("cms_page.{}", needs.as_str()),
7885                page: p.id.get().copied().map(|id| (id, needs)),
7886            };
7887            if !super::route_perms::allows(pool, user, &req).await {
7888                return redirect_named_with_message_args(
7889                    "rcms-admin:pages:list",
7890                    MsgLevel::Error,
7891                    "You don't have permission to {action} “{title}”.",
7892                    &[("action", action.as_str()), ("title", p.title.as_str())],
7893                    &headers,
7894                );
7895            }
7896        }
7897    }
7898
7899    match action.as_str() {
7900        "publish" | "unpublish" => {
7901            let target = if action == "publish" {
7902                crate::page::PageStatus::Published
7903            } else {
7904                crate::page::PageStatus::Draft
7905            };
7906            let invalidator = _state.cache_invalidator.clone();
7907            let tenant_slug = tenant_key(&tenant.org)?;
7908            let purge_urls: Vec<String> = pages.iter().map(|p| p.url_path.clone()).collect();
7909            let pages_for_tx = pages.clone();
7910            // #317 — flip the batch's status in one atomic! block and
7911            // register the #78 per-URL purge via on_commit, so it fires
7912            // only once the batch commits (detached; dropped on rollback).
7913            let touched = rustango::atomic!(pool, |tx| {
7914                let mut guard = tx.lock().await?;
7915                let tx = &mut *guard;
7916                let mut touched = 0usize;
7917                for mut p in pages_for_tx {
7918                    // #556 — archived pages are frozen against unpublish;
7919                    // they must be explicitly unarchived. Skip them in a
7920                    // bulk unpublish (bulk publish still revives them).
7921                    if matches!(target, crate::page::PageStatus::Draft)
7922                        && p.status == crate::page::PageStatus::Archived.as_str()
7923                    {
7924                        continue;
7925                    }
7926                    if p.status != target.as_str() {
7927                        p.status = target.as_str().to_owned();
7928                        if matches!(target, crate::page::PageStatus::Published) {
7929                            let now = chrono::Utc::now();
7930                            if p.published_at.is_none() {
7931                                p.published_at = Some(now);
7932                            }
7933                            // #251 — bulk publish also bumps last-publish.
7934                            p.last_published_at = Some(now);
7935                        }
7936                        p.save_tx(tx).await?;
7937                        touched += 1;
7938                    }
7939                }
7940                crate::cache_invalidate::invalidate_urls_on_commit(
7941                    invalidator,
7942                    tenant_slug,
7943                    purge_urls,
7944                );
7945                Ok::<usize, rustango::sql::ExecError>(touched)
7946            })
7947            .await?;
7948            // Capture revisions outside the transaction; failure here
7949            // only affects history bookkeeping.
7950            for p in &pages {
7951                crate::revision::capture(pool, p, None)
7952                    .await
7953                    .log_warn("revision not captured; the history has a gap");
7954            }
7955            // #553 — bulk unpublish: rules linked to pages leaving
7956            // Published must not keep serving. `pages` holds the
7957            // pre-flip rows, so filter on the OLD status.
7958            if !matches!(target, crate::page::PageStatus::Published) {
7959                for p in &pages {
7960                    if p.status != crate::page::PageStatus::Published.as_str() {
7961                        continue;
7962                    }
7963                    let pid = p.id.get().copied().unwrap_or_default();
7964                    if let Err(e) = crate::redirect::disable_for_page(
7965                        pool,
7966                        pid,
7967                        &format!("Linked page “{}” was unpublished", p.title),
7968                    )
7969                    .await
7970                    {
7971                        tracing::warn!(page_id = pid, error = %e, "failed to disable redirects for unpublished page");
7972                    }
7973                }
7974            }
7975            // #107 — plugin after_publish_page on bulk publish only.
7976            if matches!(target, crate::page::PageStatus::Published) {
7977                let hook_ctx = crate::hooks::HookCtx::new(
7978                    pool,
7979                    &tenant.org.slug,
7980                    session_user.as_ref().and_then(|u| u.id.get().copied()),
7981                );
7982                for p in &pages {
7983                    crate::hooks::fire_after_publish_page(hook_ctx, p).await;
7984                }
7985                // #115 — notify-on-publish subscribers (per page).
7986                let actor = session_user.as_ref().map(|u| u.username.as_str());
7987                for p in &pages {
7988                    crate::page_subscription::notify_publish(
7989                        _state.mailer.as_deref(),
7990                        &_state.mailer_from,
7991                        pool,
7992                        &tenant.org.slug,
7993                        p.id.get().copied().unwrap_or_default(),
7994                        &p.title,
7995                        &p.url_path,
7996                        actor,
7997                    )
7998                    .await;
7999                }
8000            }
8001            let already = (pages.len() - touched).to_string();
8002            let key = if action == "publish" {
8003                "Published {count} page(s) ({already} already in the target state)."
8004            } else {
8005                "Unpublished {count} page(s) ({already} already in the target state)."
8006            };
8007            redirect_named_with_message_plural(
8008                "rcms-admin:pages:list",
8009                MsgLevel::Success,
8010                key,
8011                touched as i64,
8012                &[("count", &touched.to_string()), ("already", already.as_str())],
8013                &headers,
8014            )
8015        }
8016        "delete" => {
8017            // #556 — archived pages are a preservation lock: they can't
8018            // be deleted until explicitly unarchived. Reject the whole
8019            // batch if any selected page is archived (mirrors the child
8020            // guard's all-or-nothing rule).
8021            let archived_names: Vec<String> = pages
8022                .iter()
8023                .filter(|p| p.status == crate::page::PageStatus::Archived.as_str())
8024                .map(|p| format!("“{}”", p.title))
8025                .collect();
8026            if !archived_names.is_empty() {
8027                let list = archived_names.join(", ");
8028                return redirect_named_with_message_args(
8029                    "rcms-admin:pages:list",
8030                    MsgLevel::Error,
8031                    "Can't delete archived page(s) {names} — unarchive them first.",
8032                    &[("names", list.as_str())],
8033                    &headers,
8034                );
8035            }
8036            // Atomic guard: if ANY selected page has children, the
8037            // whole batch fails. Matches the per-row delete rule and
8038            // the acceptance criterion on the issue.
8039            let id_set: std::collections::HashSet<i64> =
8040                pages.iter().filter_map(|p| p.id.get().copied()).collect();
8041            let mut offenders: Vec<String> = Vec::new();
8042            for p in &pages {
8043                let pid = p.id.get().copied().unwrap_or_default();
8044                let children: Vec<Page> = Page::objects()
8045                    .where_(Page::parent_id.eq(pid))
8046                    .fetch(pool)
8047                    .await?;
8048                // Children that are themselves part of this batch
8049                // don't count as blockers — they'll be deleted in
8050                // the same transaction.
8051                let external_children = children
8052                    .iter()
8053                    .filter(|c| !id_set.contains(&c.id.get().copied().unwrap_or_default()))
8054                    .count();
8055                if external_children > 0 {
8056                    offenders.push(format!("#{pid} “{}” ({external_children})", p.title));
8057                }
8058            }
8059            if !offenders.is_empty() {
8060                let offenders_list = offenders.join(", ");
8061                return redirect_named_with_message_args(
8062                    "rcms-admin:pages:list",
8063                    MsgLevel::Error,
8064                    "Bulk delete blocked — these page(s) still have external children: {offenders}.",
8065                    &[("offenders", offenders_list.as_str())],
8066                    &headers,
8067                );
8068            }
8069            // Delete deepest-first so child rows go before parents
8070            // and FK guards stay green. Every row that points at a page
8071            // (revisions, tags, logs, host extension rows…) is cleared
8072            // first: those FKs have no ON DELETE action.
8073            let mut ordered = pages.clone();
8074            ordered.sort_by(|a, b| b.depth.cmp(&a.depth));
8075            let invalidator = _state.cache_invalidator.clone();
8076            let tenant_slug = tenant_key(&tenant.org)?;
8077            // #78 — purge every deleted URL so the next visitor sees a
8078            // 404, not a stale 200. #317 — registered via on_commit so
8079            // it fires only once the whole batch delete commits.
8080            let purge_urls: Vec<String> = pages.iter().map(|p| p.url_path.clone()).collect();
8081            rustango::atomic!(pool, |tx| {
8082                let mut guard = tx.lock().await?;
8083                let tx = &mut *guard;
8084                for p in &ordered {
8085                    let pid = p.id.get().copied().unwrap_or_default();
8086                    crate::page_delete::clear_page_references_tx(tx, pid).await?;
8087                }
8088                for p in ordered {
8089                    p.delete_tx(tx).await?;
8090                }
8091                crate::cache_invalidate::invalidate_urls_on_commit(
8092                    invalidator,
8093                    tenant_slug,
8094                    purge_urls,
8095                );
8096                Ok::<(), rustango::sql::ExecError>(())
8097            })
8098            .await?;
8099            // #553 — disable redirect rules linked to any deleted page.
8100            for p in &pages {
8101                let pid = p.id.get().copied().unwrap_or_default();
8102                if let Err(e) = crate::redirect::disable_for_page(
8103                    pool,
8104                    pid,
8105                    &format!("Linked page “{}” was deleted", p.title),
8106                )
8107                .await
8108                {
8109                    tracing::warn!(page_id = pid, error = %e, "failed to disable redirects for deleted page");
8110                }
8111            }
8112            redirect_named_with_message_plural(
8113                "rcms-admin:pages:list",
8114                MsgLevel::Success,
8115                "Deleted {count} page(s).",
8116                pages.len() as i64,
8117                &[("count", &pages.len().to_string())],
8118                &headers,
8119            )
8120        }
8121        "move" => {
8122            let Some(new_parent_id) = new_parent_raw else {
8123                return redirect_named_with_message(
8124                    "rcms-admin:pages:list",
8125                    MsgLevel::Warning,
8126                    "Bulk move requires a destination — pick a parent page.",
8127                    &headers,
8128                );
8129            };
8130            let new_parent: Option<Page> = if new_parent_id > 0 {
8131                Page::objects()
8132                    .where_(Page::id.eq(new_parent_id))
8133                    .first(pool).await?
8134            } else {
8135                None
8136            };
8137            // Self-loop guard: can't move a page under itself or any
8138            // of its descendants. Path-prefix check is cheap.
8139            if let Some(np) = &new_parent {
8140                for p in &pages {
8141                    if np.path.starts_with(&p.path) {
8142                        return redirect_named_with_message_args(
8143                            "rcms-admin:pages:list",
8144                            MsgLevel::Error,
8145                            "Can't move “{title}” under “{parent}” — destination is itself or a descendant.",
8146                            &[("title", p.title.as_str()), ("parent", np.title.as_str())],
8147                            &headers,
8148                        );
8149                    }
8150                }
8151            }
8152
8153            // Pre-validate page-type placement for every selected row
8154            // before mutating anything. If a single page rejects the
8155            // destination, the whole batch fails — matches the issue's
8156            // atomicity requirement so editors never end up with a
8157            // partial reparent.
8158            if let Some(np) = &new_parent {
8159                for p in &pages {
8160                    if let Err(e) =
8161                        crate::tree_ops::validate_child_placement(pool, np.page_type_id, p.page_type_id)
8162                            .await
8163                    {
8164                        let err = e.to_string();
8165                        return redirect_named_with_message_args(
8166                            "rcms-admin:pages:list",
8167                            MsgLevel::Error,
8168                            "Move blocked — “{title}” can't live under “{parent}”: {error}",
8169                            &[("title", p.title.as_str()), ("parent", np.title.as_str()), ("error", err.as_str())],
8170                            &headers,
8171                        );
8172                    }
8173                }
8174            }
8175
8176            // F2 / #317 — reparent the whole batch in ONE atomic_tree so a
8177            // mid-batch failure rolls back every move (no partial reparent;
8178            // placement was already pre-validated above). Each page's
8179            // subtree is pre-read on the pool *before* the transaction, so
8180            // nothing inside the tx reads the pool (which would deadlock a
8181            // single-connection SQLite pool); `move_to_in_tx` then reparents
8182            // each page within the shared tx. The #78 purge of every page's
8183            // old + new URL + descendant URLs (captured pre-cascade) is
8184            // registered via on_commit, firing only once the batch commits.
8185            let mut to_move: Vec<(Page, Vec<Page>)> = Vec::with_capacity(pages.len());
8186            for p in pages.iter().cloned() {
8187                let subtree = p.descendants(pool).await?;
8188                to_move.push((p, subtree));
8189            }
8190            let moved = to_move.len();
8191            let invalidator = _state.cache_invalidator.clone();
8192            let tenant_slug = tenant_key(&tenant.org)?;
8193            let np_for_tx = new_parent.clone();
8194            crate::tree_ops::atomic_tree(pool, move |tx| {
8195                Box::pin(async move {
8196                    let mut purge: Vec<String> = Vec::new();
8197                    for (mut p, subtree) in to_move {
8198                        let old_url = p.url_path.clone();
8199                        let descendant_old_urls: Vec<String> =
8200                            subtree.iter().map(|d| d.url_path.clone()).collect();
8201                        // Moves the URLs with the tree (#706).
8202                        p.move_to_in_tx(np_for_tx.as_ref(), subtree, tx).await?;
8203                        purge.push(old_url);
8204                        purge.push(p.url_path.clone());
8205                        purge.extend(descendant_old_urls);
8206                    }
8207                    crate::cache_invalidate::invalidate_urls_on_commit(
8208                        invalidator,
8209                        tenant_slug,
8210                        purge,
8211                    );
8212                    Ok(())
8213                })
8214            })
8215            .await?;
8216            redirect_named_with_message_plural(
8217                "rcms-admin:pages:list",
8218                MsgLevel::Success,
8219                "Moved {count} page(s) under “{parent}”.",
8220                moved as i64,
8221                &[
8222                    ("count", &moved.to_string()),
8223                    (
8224                        "parent",
8225                        &new_parent.map(|p| p.title).unwrap_or_else(|| "Root".to_owned()),
8226                    ),
8227                ],
8228                &headers,
8229            )
8230        }
8231        "copy-to-locale" => {
8232            // #438 — simple-translation bulk: seed `cms_translation`
8233            // rows for each selected page from its canonical text, so
8234            // translators start from the source rather than a blank
8235            // form. Existing translations are left untouched.
8236            let code = form
8237                .iter()
8238                .find(|(k, _)| k == "locale")
8239                .map(|(_, v)| v.as_str())
8240                .unwrap_or("");
8241            let locale = Locale::objects()
8242                .where_(Locale::code.eq(code.to_owned()))
8243                .where_(Locale::active.eq(true))
8244                .first(pool)
8245                .await?;
8246            let Some(locale) = locale.filter(|l| !l.is_default) else {
8247                return redirect_named_with_message(
8248                    "rcms-admin:pages:list",
8249                    MsgLevel::Warning,
8250                    "Copy to locale needs a target locale (and not the default — canonical content already lives there).",
8251                    &headers,
8252                );
8253            };
8254            let locale_id = locale.id.get().copied().unwrap_or_default();
8255            let pages_for_tx = pages.clone();
8256            let (seeded_pages, seeded_fields) = rustango::atomic!(pool, |tx| {
8257                let mut guard = tx.lock().await?;
8258                let tx = &mut *guard;
8259                let mut sp = 0usize;
8260                let mut sf = 0usize;
8261                for p in &pages_for_tx {
8262                    let Some(pid) = p.id.get().copied() else {
8263                        continue;
8264                    };
8265                    // Field paths already translated for this locale —
8266                    // never overwrite a translator's work.
8267                    let existing: Vec<crate::translation::Translation> =
8268                        crate::translation::Translation::objects()
8269                            .where_(crate::translation::Translation::page_id.eq(pid))
8270                            .where_(crate::translation::Translation::locale_id.eq(locale_id))
8271                            .fetch_tx(tx)
8272                            .await?;
8273                    let have: std::collections::HashSet<String> =
8274                        existing.into_iter().map(|t| t.field_path).collect();
8275                    let mut touched = false;
8276                    for (path, value) in copy_fields_for(p) {
8277                        if have.contains(path) {
8278                            continue;
8279                        }
8280                        let mut row = crate::translation::Translation {
8281                            id: rustango::sql::Auto::Unset,
8282                            page_id: pid,
8283                            locale_id,
8284                            field_path: path.to_owned(),
8285                            value,
8286                            updated_at: rustango::sql::Auto::Unset,
8287                        };
8288                        row.save_tx(tx).await?;
8289                        sf += 1;
8290                        touched = true;
8291                    }
8292                    if touched {
8293                        sp += 1;
8294                    }
8295                }
8296                Ok::<_, rustango::sql::ExecError>((sp, sf))
8297            })
8298            .await?;
8299            // Two independent counts → compose localized noun-phrases into a
8300            // localized sentence template (#528/#1102).
8301            let fields = super::i18n::tr_plural(
8302                &headers,
8303                "{count} field(s)",
8304                seeded_fields as i64,
8305                &[("count", &seeded_fields.to_string())],
8306            );
8307            let pages_ph = super::i18n::tr_plural(
8308                &headers,
8309                "{count} page(s)",
8310                seeded_pages as i64,
8311                &[("count", &seeded_pages.to_string())],
8312            );
8313            redirect_named_with_message_args(
8314                "rcms-admin:pages:list",
8315                MsgLevel::Success,
8316                "Seeded {fields} across {pages} into “{locale}”. Existing translations were left untouched.",
8317                &[
8318                    ("fields", fields.as_str()),
8319                    ("pages", pages_ph.as_str()),
8320                    ("locale", locale.name.as_str()),
8321                ],
8322                &headers,
8323            )
8324        }
8325        "archive" | "unarchive" => {
8326            // #556 — archive: preserve superseded content (serve 200,
8327            // stay searchable, frozen against delete/unpublish).
8328            // Unarchive: revive to published. Descendants inherit the
8329            // treatment at render time, so the whole public subtree is
8330            // purged; with `archive_cascade` their own rows flip too.
8331            let archive = action == "archive";
8332            let plan =
8333                crate::page::plan_archive(pool, &pages, archive, archive_cascade).await?;
8334            let invalidator = _state.cache_invalidator.clone();
8335            let tenant_slug = tenant_key(&tenant.org)?;
8336            let purge = plan.changed_urls.clone();
8337            let flips = plan.to_flip.clone();
8338            let touched = rustango::atomic!(pool, |tx| {
8339                let mut guard = tx.lock().await?;
8340                let tx = &mut *guard;
8341                let mut n = 0usize;
8342                for mut p in flips {
8343                    p.save_tx(tx).await?;
8344                    n += 1;
8345                }
8346                crate::cache_invalidate::invalidate_urls_on_commit(
8347                    invalidator,
8348                    tenant_slug,
8349                    purge,
8350                );
8351                Ok::<usize, rustango::sql::ExecError>(n)
8352            })
8353            .await?;
8354            // Bookkeeping outside the tx (best-effort): a revision per
8355            // flipped row + search-index sync (archived stays indexed;
8356            // the FTS path is query-time so this is a no-op there).
8357            for p in &plan.to_flip {
8358                crate::revision::capture(pool, p, None)
8359                    .await
8360                    .log_warn("revision not captured; the history has a gap");
8361                crate::task_queue::sync_page_search(&tenant.org.slug, p).await;
8362            }
8363            let key = if archive {
8364                "Archived {count} page(s)."
8365            } else {
8366                "Unarchived {count} page(s)."
8367            };
8368            redirect_named_with_message_plural(
8369                "rcms-admin:pages:list",
8370                MsgLevel::Success,
8371                key,
8372                touched as i64,
8373                &[("count", &touched.to_string())],
8374                &headers,
8375            )
8376        }
8377        other => Err(AdminError::Validation(format!(
8378            "unknown bulk action `{other}` (expected publish / unpublish / archive / unarchive / delete / move / copy-to-locale)"
8379        ))),
8380    }
8381}
8382
8383/// POST /cms-admin/pages/{id}/unlock — force-release the editor lock.
8384/// Anyone with Edit permission on this page can call it. The
8385/// row is deleted and an audit-log entry is written so the action is
8386/// reversible to inspect.
8387/// POST /cms-admin/pages/{id}/lock-release — the editor was left: give
8388/// up our own lock right away, not 30 minutes later, so a colleague who
8389/// opens the page next can save. Only ever releases the caller's lock.
8390pub async fn page_lock_release(
8391    tenant: Tenant,
8392    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
8393    Path(id): Path<i64>,
8394) -> Result<Response, AdminError> {
8395    let Some(viewer_id) = session_user.as_ref().and_then(|u| u.id.get().copied()) else {
8396        return Ok(unauthorized_no_session());
8397    };
8398    crate::lock::release(tenant.pool(), id, viewer_id).await?;
8399    Ok((axum::http::StatusCode::NO_CONTENT, "").into_response())
8400}
8401
8402pub async fn page_unlock_submit(
8403    State(_state): State<super::AdminState>,
8404    tenant: Tenant,
8405    headers: HeaderMap,
8406    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
8407    Path(id): Path<i64>,
8408) -> Result<Response, AdminError> {
8409    let released = crate::lock::force_release(tenant.pool(), id).await?;
8410    let actor_id = session_user.as_ref().and_then(|u| u.id.get().copied());
8411    let message = if let Some(row) = released {
8412        let holder = rustango::tenancy::auth::User::objects()
8413            .where_(rustango::tenancy::auth::User::id.eq(row.user_id))
8414            .fetch(tenant.pool())
8415            .await
8416            .ok()
8417            .and_then(|v| v.into_iter().next())
8418            .map(|u| u.username)
8419            .unwrap_or_else(|| format!("user#{}", row.user_id));
8420        // #192 — audit log the forced unlock.
8421        crate::page_log::record_or_warn(
8422            tenant.pool(),
8423            id,
8424            crate::page_log::ACTION_FORCE_UNLOCK,
8425            actor_id,
8426            format!("Force-unlocked — “{holder}” no longer holds the editor lock."),
8427            Some(serde_json::json!({ "previous_holder_user_id": row.user_id })),
8428        )
8429        .await;
8430        format!("Lock released — “{holder}” no longer holds the editor lock on this page.")
8431    } else {
8432        "Lock was already released.".to_owned()
8433    };
8434    redirect_named_with_params_and_message(
8435        "rcms-admin:pages:edit",
8436        &[("id", id.to_string())],
8437        MsgLevel::Success,
8438        &message,
8439        &headers,
8440    )
8441}
8442
8443/// POST /cms-admin/pages/{id}/subscribe — opt the current user in
8444/// to publish notifications for this page.
8445/// Idempotent — re-subscribing returns success without inserting a
8446/// duplicate row.
8447pub async fn page_subscribe_submit(
8448    State(_state): State<super::AdminState>,
8449    tenant: Tenant,
8450    headers: HeaderMap,
8451    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
8452    Path(id): Path<i64>,
8453) -> Result<Response, AdminError> {
8454    let Some(viewer) = session_user.as_ref() else {
8455        return Ok(unauthorized_no_session());
8456    };
8457    let viewer_id = viewer.id.get().copied().unwrap_or_default();
8458    crate::page_subscription::subscribe(tenant.pool(), id, viewer_id).await?;
8459    redirect_named_with_params_and_message(
8460        "rcms-admin:pages:edit",
8461        &[("id", id.to_string())],
8462        MsgLevel::Success,
8463        "Subscribed — you'll get an email when this page publishes.",
8464        &headers,
8465    )
8466}
8467
8468/// POST /cms-admin/pages/{id}/unsubscribe — opt the current user out
8469/// of publish notifications. No-op when not subscribed.
8470pub async fn page_unsubscribe_submit(
8471    State(_state): State<super::AdminState>,
8472    tenant: Tenant,
8473    headers: HeaderMap,
8474    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
8475    Path(id): Path<i64>,
8476) -> Result<Response, AdminError> {
8477    let Some(viewer) = session_user.as_ref() else {
8478        return Ok(unauthorized_no_session());
8479    };
8480    let viewer_id = viewer.id.get().copied().unwrap_or_default();
8481    crate::page_subscription::unsubscribe(tenant.pool(), id, viewer_id).await?;
8482    redirect_named_with_params_and_message(
8483        "rcms-admin:pages:edit",
8484        &[("id", id.to_string())],
8485        MsgLevel::Success,
8486        "Unsubscribed — you won't get future publish notifications for this page.",
8487        &headers,
8488    )
8489}
8490
8491/// True while the page is mid-review and `user` may not decide the
8492/// current step: the editor is read-only for them, so they must not
8493/// take (or keep) the edit lock — a submitter who reopens the page
8494/// would otherwise lock the reviewer out.
8495async fn read_only_under_review(
8496    pool: &rustango::sql::Pool,
8497    page_id: i64,
8498    user: &rustango::tenancy::auth::User,
8499) -> Result<bool, AdminError> {
8500    if user.is_superuser {
8501        return Ok(false);
8502    }
8503    let Some(state) = crate::workflow::active_state_for_page(pool, page_id).await? else {
8504        return Ok(false);
8505    };
8506    if state.status != crate::workflow::WorkflowStatus::InProgress.as_str() {
8507        return Ok(false);
8508    }
8509    let tasks = crate::workflow::tasks_for(pool, state.workflow_id).await?;
8510    let Some(task) = state
8511        .current_task_id
8512        .and_then(|tid| tasks.iter().find(|t| t.id.get().copied() == Some(tid)))
8513    else {
8514        return Ok(false);
8515    };
8516    let uid = user.id.get().copied().unwrap_or_default();
8517    Ok(!user_is_in_role(pool, uid, task.role_id).await?)
8518}
8519
8520/// POST /cms-admin/pages/{id}/lock-heartbeat — refresh the TTL on
8521/// the caller's lock. Called every
8522/// `lock::HEARTBEAT_INTERVAL_SECS` from the page-editor JS while the
8523/// tab stays open. Returns:
8524///   * 204 — heartbeat accepted (lock refreshed, or first claim).
8525///   * 409 — someone else owns the lock; the editor JS should
8526///           reload to surface the banner.
8527/// Heartbeat query: editors send `?is_editing=1` once they've
8528/// touched the form so the presence banner can show "editing" vs
8529/// "viewing" for other viewers.
8530#[derive(Debug, Deserialize)]
8531pub struct HeartbeatQuery {
8532    #[serde(default)]
8533    pub is_editing: Option<String>,
8534}
8535
8536pub async fn page_lock_heartbeat(
8537    State(_state): State<super::AdminState>,
8538    tenant: Tenant,
8539    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
8540    Path(id): Path<i64>,
8541    Query(q): Query<HeartbeatQuery>,
8542) -> Result<Response, AdminError> {
8543    let Some(viewer_id) = session_user.as_ref().and_then(|u| u.id.get().copied()) else {
8544        return Ok(unauthorized_no_session());
8545    };
8546
8547    // #106 — touch the editing-session row on every ping. Stale
8548    // rows GC lazily here so we don't need a cron.
8549    let is_editing = q.is_editing.as_deref() == Some("1");
8550    if let Err(e) = crate::editing_session::touch(tenant.pool(), id, viewer_id, is_editing).await {
8551        tracing::warn!(target: "rustango_cms::admin", page_id = id, error = %e, "editing-session touch failed (continuing)");
8552    }
8553    // GC every ~50 heartbeats to keep the table bounded without
8554    // doing the SELECT on every call. Probabilistic — fine for v1.
8555    if rand::random::<u8>() < 5 {
8556        crate::editing_session::gc_stale(tenant.pool())
8557            .await
8558            .log_warn("stale editing sessions not collected");
8559    }
8560
8561    // Read-only during someone else's review step: no lock to keep.
8562    if let Some(u) = session_user.as_ref() {
8563        if read_only_under_review(tenant.pool(), id, u).await? {
8564            return Ok((axum::http::StatusCode::NO_CONTENT, "").into_response());
8565        }
8566    }
8567    match crate::lock::acquire(tenant.pool(), id, viewer_id, false).await {
8568        Ok(crate::lock::AcquireOutcome::Acquired(_)) => {
8569            Ok((axum::http::StatusCode::NO_CONTENT, "").into_response())
8570        }
8571        Ok(crate::lock::AcquireOutcome::Held(_)) => Ok((
8572            axum::http::StatusCode::CONFLICT,
8573            "lock held by another editor",
8574        )
8575            .into_response()),
8576        Err(e) => {
8577            tracing::warn!(target: "rustango_cms::admin", page_id = id, error = %e, "lock heartbeat failed");
8578            Err(e.into())
8579        }
8580    }
8581}
8582
8583/// GET /cms-admin/pages/{id}/sessions — JSON list of OTHER active
8584/// editors / viewers on this page. Returns
8585/// `[{user_id, username, last_seen_at, is_editing}, ...]`.
8586pub async fn page_sessions_json(
8587    State(_state): State<super::AdminState>,
8588    tenant: Tenant,
8589    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
8590    Path(id): Path<i64>,
8591) -> Result<Response, AdminError> {
8592    let Some(viewer_id) = session_user.as_ref().and_then(|u| u.id.get().copied()) else {
8593        return Ok(unauthorized_no_session());
8594    };
8595    let others = crate::editing_session::others_on_page(tenant.pool(), id, viewer_id)
8596        .await
8597        .unwrap_or_default();
8598    if others.is_empty() {
8599        return Ok(([(header::CONTENT_TYPE, "application/json")], "[]").into_response());
8600    }
8601    // Resolve usernames in one batched lookup.
8602    let user_ids: Vec<i64> = others.iter().map(|s| s.user_id).collect();
8603    let users: Vec<rustango::tenancy::auth::User> = rustango::tenancy::auth::User::objects()
8604        .where_(rustango::tenancy::auth::User::id.is_in(user_ids))
8605        .fetch(tenant.pool())
8606        .await
8607        .unwrap_or_default();
8608    let username_by_id: std::collections::HashMap<i64, String> = users
8609        .into_iter()
8610        .filter_map(|u| u.id.get().copied().map(|id| (id, u.username)))
8611        .collect();
8612    let payload: Vec<serde_json::Value> = others
8613        .iter()
8614        .map(|s| {
8615            serde_json::json!({
8616                "user_id": s.user_id,
8617                "username": username_by_id.get(&s.user_id).cloned(),
8618                "last_seen_at": s.last_seen_at,
8619                "is_editing": s.is_editing,
8620            })
8621        })
8622        .collect();
8623    let body = serde_json::to_string(&payload).unwrap_or_else(|_| "[]".to_owned());
8624    Ok(([(header::CONTENT_TYPE, "application/json")], body).into_response())
8625}
8626
8627/// Pick a slug not already used by any sibling under `parent_id`.
8628/// Tries `desired`, then `desired-2`, `desired-3`, … up to 100
8629/// attempts. Returns the first available one.
8630async fn unique_sibling_slug(
8631    pool: &rustango::sql::Pool,
8632    parent_id: Option<i64>,
8633    desired: &str,
8634) -> Result<String, AdminError> {
8635    use rustango::core::Column as _;
8636    let qs = Page::objects().order_by(&[("slug", false)]);
8637    let siblings: Vec<Page> = match parent_id {
8638        Some(pid) => qs.where_(Page::parent_id.eq(pid)).fetch(pool).await?,
8639        None => qs.where_(Page::parent_id.is_null()).fetch(pool).await?,
8640    };
8641    let taken: std::collections::HashSet<String> = siblings.into_iter().map(|p| p.slug).collect();
8642    if !taken.contains(desired) {
8643        return Ok(desired.to_owned());
8644    }
8645    for n in 2..=100 {
8646        let candidate = format!("{desired}-{n}");
8647        if !taken.contains(&candidate) {
8648            return Ok(candidate);
8649        }
8650    }
8651    Err(AdminError::Validation(
8652        "Could not allocate a unique slug for the clone — over 100 siblings share the same base."
8653            .to_owned(),
8654    ))
8655}
8656
8657/// POST /cms-admin/pages/{id}/revert/{rev_id} — replace the page's
8658/// mutable fields with those from the given revision, then capture a
8659/// NEW revision recording the revert. URL-shaped fields (slug, path,
8660/// depth, parent_id, sort_order) are NOT reverted — moving the page
8661/// is a tree-ops concern, not a content concern.
8662///
8663/// Returns to the edit form afterward so the editor can verify the
8664/// state and continue editing.
8665pub async fn page_revert_submit(
8666    State(_state): State<super::AdminState>,
8667    tenant: Tenant,
8668    headers: HeaderMap,
8669    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
8670    Path((id, rev_id)): Path<(i64, i64)>,
8671) -> Result<Response, AdminError> {
8672    let mut page = Page::objects()
8673        .where_(Page::id.eq(id))
8674        .first(tenant.pool())
8675        .await?
8676        .ok_or(AdminError::NotFound(id))?;
8677    let rev = crate::revision::Revision::objects()
8678        .where_(crate::revision::Revision::id.eq(rev_id))
8679        .where_(crate::revision::Revision::page_id.eq(id))
8680        .first(tenant.pool())
8681        .await?
8682        .ok_or(AdminError::NotFound(rev_id))?;
8683
8684    // Decode the snapshot into a Page shell. Tree-shape fields
8685    // (parent_id, path, depth, sort_order, slug, url_path) are
8686    // preserved from the LIVE row — a revert restores content +
8687    // status, not tree placement.
8688    let snapshot: Page = match serde_json::from_value(rev.snapshot.clone()) {
8689        Ok(p) => p,
8690        Err(e) => {
8691            return Ok((
8692                axum::http::StatusCode::BAD_REQUEST,
8693                format!("revision snapshot could not be decoded: {e}"),
8694            )
8695                .into_response());
8696        }
8697    };
8698
8699    let old_url_path = page.url_path.clone();
8700    page.title = snapshot.title;
8701    page.page_type_id = snapshot.page_type_id;
8702    page.status = snapshot.status;
8703    page.published_at = snapshot.published_at;
8704    page.go_live_at = snapshot.go_live_at;
8705    page.expire_at = snapshot.expire_at;
8706    page.seo_title = snapshot.seo_title;
8707    page.seo_description = snapshot.seo_description;
8708    page.robots_index = snapshot.robots_index;
8709    page.sitemap_priority = snapshot.sitemap_priority;
8710
8711    let mut tx = transaction_pool(tenant.pool()).await?;
8712    page.save_tx(&mut tx).await?;
8713    tx.commit().await?;
8714    crate::revision::capture(tenant.pool(), &page, None)
8715        .await
8716        .log_warn("revision not captured; the history has a gap");
8717
8718    let _ = old_url_path; // TTL-based cache propagation per rustango::cache_page
8719                          // #192 — audit log the restore.
8720    let actor_id = session_user.as_ref().and_then(|u| u.id.get().copied());
8721    crate::page_log::record_or_warn(
8722        tenant.pool(),
8723        id,
8724        crate::page_log::ACTION_RESTORE,
8725        actor_id,
8726        format!("Reverted to revision #{}.", rev.sequence),
8727        Some(serde_json::json!({ "revision_id": rev_id, "sequence": rev.sequence })),
8728    )
8729    .await;
8730    let sequence_str = rev.sequence.to_string();
8731    redirect_named_with_params_and_message_args(
8732        "rcms-admin:pages:edit",
8733        &[("id", id.to_string())],
8734        MsgLevel::Success,
8735        "Reverted to revision #{sequence}.",
8736        &[("sequence", sequence_str.as_str())],
8737        &headers,
8738    )
8739}
8740
8741// =====================================================================
8742// Live preview
8743// =====================================================================
8744
8745/// Stamp the response with anti-cache headers so the editor's preview
8746/// iframe always renders the latest content. Browsers cache HTML
8747/// aggressively by default; the editor's "Refresh" button and the
8748/// initial load both need to hit fresh markup.
8749fn stamp_no_cache(mut response: Response) -> Response {
8750    let h = response.headers_mut();
8751    h.insert(
8752        header::CACHE_CONTROL,
8753        HeaderValue::from_static("no-store, no-cache, must-revalidate, max-age=0"),
8754    );
8755    h.insert(header::PRAGMA, HeaderValue::from_static("no-cache"));
8756    h.insert(header::EXPIRES, HeaderValue::from_static("0"));
8757    // Tell upstream caches the response varies per-request even
8758    // for the same URL (preview pulls live data on every load).
8759    h.insert(header::VARY, HeaderValue::from_static("*"));
8760    // Block embedding outside our own admin so other origins can't
8761    // frame the preview for clickjacking.
8762    h.insert(
8763        header::X_FRAME_OPTIONS,
8764        HeaderValue::from_static("SAMEORIGIN"),
8765    );
8766    response
8767}
8768
8769/// Inject the axe-core preview-glue script into the
8770/// rendered preview HTML so the editor can surface client-side
8771/// accessibility findings alongside the server-side heuristics.
8772/// Reads the response body, locates the closing `</body>`
8773/// tag (case-insensitive), and splices two `<script src="…">`
8774/// tags before it: axe-core itself, then the small glue script
8775/// that calls `axe.run()` + `postMessage`s the results back to
8776/// the editor's parent window.
8777///
8778/// Non-HTML responses pass through unchanged; pages without a
8779/// `</body>` tag (malformed templates, plain-text responses) also
8780/// pass through so the injection is best-effort + non-breaking.
8781async fn inject_axe_into_preview(response: Response) -> Response {
8782    // Only touch text/html responses.
8783    let is_html = response
8784        .headers()
8785        .get(header::CONTENT_TYPE)
8786        .and_then(|v| v.to_str().ok())
8787        .is_some_and(|ct| ct.to_ascii_lowercase().contains("text/html"));
8788    if !is_html {
8789        return response;
8790    }
8791    let (parts, body) = response.into_parts();
8792    // 4 MiB cap matches the rendition route's preview-safe upper
8793    // bound; admin preview HTML should never approach this.
8794    let bytes = match axum::body::to_bytes(body, 4 * 1024 * 1024).await {
8795        Ok(b) => b,
8796        Err(_) => {
8797            // Body read failed — return a minimal 500 since we
8798            // already consumed the original.
8799            return (
8800                axum::http::StatusCode::INTERNAL_SERVER_ERROR,
8801                "preview body read failed",
8802            )
8803                .into_response();
8804        }
8805    };
8806    let body_str = match std::str::from_utf8(&bytes) {
8807        Ok(s) => s,
8808        Err(_) => {
8809            // Non-UTF-8 HTML — rebuild without injection.
8810            return axum::http::Response::from_parts(parts, axum::body::Body::from(bytes));
8811        }
8812    };
8813    let new_body = inject_axe_into_body_str(body_str);
8814    // Rebuild the response with the patched body + a refreshed
8815    // Content-Length so axum doesn't emit the stale value.
8816    let mut resp = axum::http::Response::from_parts(parts, axum::body::Body::from(new_body));
8817    resp.headers_mut().remove(header::CONTENT_LENGTH);
8818    resp
8819}
8820
8821/// Pure string helper for [`inject_axe_into_preview`] — splice the
8822/// axe-core + glue `<script>` tags before the closing `</body>`
8823/// (case-insensitive `rfind`). Pages with no closing body tag get
8824/// the scripts appended at the end (browsers tolerate trailing
8825/// `<script>` after `</html>`). Extracted so the injection logic
8826/// is unit-testable without spinning up an axum Response stack.
8827fn inject_axe_into_body_str(body: &str) -> String {
8828    // Fingerprinted like every other admin asset (`?v=`): these are served
8829    // `immutable`, so an unversioned URL would let a year-old cached copy
8830    // mask an update.
8831    let v = super::cms_asset_version();
8832    let scripts = format!(
8833        "<script src=\"/cms-admin/static/vendor/axe-core.min.js?v={v}\" defer></script>\n\
8834         <script src=\"/cms-admin/static/cms-preview-guard.js?v={v}\" defer></script>\n\
8835         <script src=\"/cms-admin/static/cms-axe-preview.js?v={v}\" defer></script>\n"
8836    );
8837    let lower = body.to_ascii_lowercase();
8838    if let Some(idx) = lower.rfind("</body>") {
8839        let mut out = String::with_capacity(body.len() + scripts.len());
8840        out.push_str(&body[..idx]);
8841        out.push_str(&scripts);
8842        out.push_str(&body[idx..]);
8843        out
8844    } else {
8845        let mut out = String::with_capacity(body.len() + scripts.len());
8846        out.push_str(body);
8847        out.push_str(&scripts);
8848        out
8849    }
8850}
8851
8852#[cfg(test)]
8853mod axe_injection_tests {
8854    use super::inject_axe_into_body_str;
8855
8856    #[test]
8857    fn splices_before_lowercase_body_close() {
8858        let html = "<html><body><h1>hi</h1></body></html>";
8859        let out = inject_axe_into_body_str(html);
8860        assert!(out.contains("axe-core.min.js"), "axe script missing: {out}");
8861        assert!(
8862            out.contains("cms-axe-preview.js"),
8863            "glue script missing: {out}"
8864        );
8865        assert!(
8866            out.contains("cms-preview-guard.js"),
8867            "preview-guard script missing: {out}"
8868        );
8869        // Both scripts land BEFORE the body close.
8870        let close = out.find("</body>").expect("body close kept");
8871        assert!(
8872            out[..close].contains("axe-core.min.js"),
8873            "axe script should be before </body>: {out}"
8874        );
8875        assert!(
8876            out[..close].contains("cms-axe-preview.js"),
8877            "glue script should be before </body>: {out}"
8878        );
8879    }
8880
8881    #[test]
8882    fn splices_before_uppercase_body_close() {
8883        let html = "<HTML><BODY><h1>hi</h1></BODY></HTML>";
8884        let out = inject_axe_into_body_str(html);
8885        // The original close tag stays uppercase; injection is still
8886        // positioned in front of it.
8887        let close = out.find("</BODY>").expect("uppercase body close kept");
8888        assert!(out[..close].contains("axe-core.min.js"));
8889    }
8890
8891    #[test]
8892    fn appends_when_no_body_close() {
8893        let html = "<html><h1>hi</h1>";
8894        let out = inject_axe_into_body_str(html);
8895        // URLs carry a `?v=<fingerprint>` cache-bust token, so assert on the
8896        // script identity + trailing position rather than an exact URL.
8897        assert!(out.contains("cms-axe-preview.js?v="));
8898        assert!(out.trim_end().ends_with("defer></script>"));
8899        assert!(out.contains("axe-core.min.js"));
8900        // Original content preserved.
8901        assert!(out.starts_with("<html><h1>hi</h1>"));
8902    }
8903
8904    #[test]
8905    fn uses_rfind_for_nested_body_close_text() {
8906        // A template that mentions "</body>" inside a comment / text
8907        // string and ALSO has a real closing tag — we want to splice
8908        // before the LAST one, not the first.
8909        let html = "<html><body><pre>literal: &lt;/body&gt;</pre></body></html>";
8910        let out = inject_axe_into_body_str(html);
8911        let close = out.rfind("</body>").unwrap();
8912        assert!(out[..close].contains("axe-core.min.js"));
8913        // Make sure the literal in the <pre> survived.
8914        assert!(out.contains("literal: &lt;/body&gt;"));
8915    }
8916
8917    #[test]
8918    fn empty_body_renders_clean() {
8919        let out = inject_axe_into_body_str("");
8920        // Nothing to splice before; just the scripts.
8921        assert!(out.contains("axe-core.min.js"));
8922        assert!(out.contains("cms-axe-preview.js"));
8923    }
8924}
8925
8926/// Query string for the preview endpoints — carries the editing locale
8927/// when the editor is in translation mode (`?locale=fr`) so the preview
8928/// renders that locale's translation instead of the canonical content.
8929#[derive(serde::Deserialize, Default)]
8930pub struct PreviewLocaleQuery {
8931    #[serde(default)]
8932    locale: Option<String>,
8933    /// `?format=json` — show the page's API representation instead of
8934    /// its rendered HTML. This is the editor's preview switch, and it
8935    /// works for **any** page type, not just ones whose `view_mode`
8936    /// opts into a public JSON view: an authenticated editor asking to
8937    /// inspect the API shape is a different act from an anonymous
8938    /// client negotiating for it.
8939    #[serde(default)]
8940    format: Option<String>,
8941}
8942
8943/// The Tera a preview must render through: the tenant's, not the global set.
8944///
8945/// The public renderer resolves templates per tenant (`router.rs` →
8946/// [`crate::tenant_templates::TenantTemplates::for_tenant`]), so a
8947/// preview built from `state.tera` shows a page the visitor will never
8948/// get. Three ways it goes wrong, all silent: a tenant's override of a
8949/// shared template is ignored; a `Page::template_override` naming a
8950/// template that exists only as an override fails `pick_template`'s
8951/// existence check and falls back to the page type's default; and a
8952/// block whose template is a tenant override renders its
8953/// "missing template" fallback.
8954///
8955/// Falls back to the global set when no overlay is installed, which is
8956/// every single-template-set deployment.
8957fn preview_tera(state: &super::AdminState, tenant: &Tenant) -> std::sync::Arc<tera::Tera> {
8958    crate::tenant_templates::installed()
8959        .map(|tt| tt.for_tenant(&tenant.org.slug))
8960        .unwrap_or_else(|| state.tera.clone())
8961}
8962
8963/// GET /cms-admin/pages/{id}/preview — renders the saved page through
8964/// the public render pipeline (no admin chrome) so the editor's
8965/// iframe shows exactly what a visitor would see. Anti-cache headers
8966/// ensure the iframe always pulls fresh markup. `?locale=` (translation
8967/// mode) renders that locale's saved translation.
8968pub async fn page_preview(
8969    State(state): State<super::AdminState>,
8970    tenant: Tenant,
8971    Path(id): Path<i64>,
8972    axum::extract::Query(q): axum::extract::Query<PreviewLocaleQuery>,
8973) -> Result<Response, AdminError> {
8974    let page = Page::objects()
8975        .where_(Page::id.eq(id))
8976        .first(tenant.pool())
8977        .await?
8978        .ok_or(AdminError::NotFound(id))?;
8979    let response = crate::render::render(
8980        &tenant,
8981        &preview_tera(&state, &tenant),
8982        &page,
8983        "",
8984        // No site prefix: this path renders the tenant-absolute
8985        // tree, so links must stay absolute.
8986        "",
8987        q.locale.as_deref(),
8988        None,
8989        None,
8990    )
8991    .await;
8992    // #208 — splice axe-core + the iframe-glue script before the
8993    // closing </body> so the editor's accessibility panel can
8994    // surface client-side findings alongside the server-side ones.
8995    Ok(stamp_no_cache(inject_axe_into_preview(response).await))
8996}
8997
8998/// GET /cms-admin/pages/{id}/preview-token — mint a short-lived
8999/// signed preview token so a decoupled / headless frontend can fetch
9000/// this page's DRAFT via `/api/v2/pages/{id}/?preview_token=…`. Returns
9001/// JSON `{token, expires_at, api_path}`. Auth is enforced by the admin
9002/// router's login guard.
9003pub async fn page_preview_token(
9004    tenant: Tenant,
9005    Path(id): Path<i64>,
9006) -> Result<Response, AdminError> {
9007    let exists = Page::objects()
9008        .where_(Page::id.eq(id))
9009        .first(tenant.pool())
9010        .await?
9011        .is_some();
9012    if !exists {
9013        return Err(AdminError::NotFound(id));
9014    }
9015    // 1-hour token: long enough to click through + iterate, short
9016    // enough to bound exposure of an unpublished page.
9017    let expires = chrono::Utc::now().timestamp() + PREVIEW_TOKEN_TTL_SECS;
9018    let token = crate::preview_token::mint(&tenant_key(&tenant.org)?, id, expires);
9019    Ok(Json(serde_json::json!({
9020        "token": token,
9021        "expires_at": expires,
9022        "api_path": format!("/api/v2/pages/{id}/?preview_token={token}"),
9023    }))
9024    .into_response())
9025}
9026
9027/// POST /cms-admin/pages/{id}/preview — same as the GET variant, but
9028/// renders a *virtual* page assembled from the posted form values so
9029/// the editor can preview unsaved changes. Nothing is persisted. Anti-cache
9030/// headers + same-origin frame policy mirror the GET handler.
9031pub async fn page_preview_draft(
9032    State(state): State<super::AdminState>,
9033    tenant: Tenant,
9034    Path(id): Path<i64>,
9035    axum::extract::Query(q): axum::extract::Query<PreviewLocaleQuery>,
9036    headers: HeaderMap,
9037    Form(form_map): Form<std::collections::HashMap<String, String>>,
9038) -> Result<Response, AdminError> {
9039    let mut page = Page::objects()
9040        .where_(Page::id.eq(id))
9041        .first(tenant.pool())
9042        .await?
9043        .ok_or(AdminError::NotFound(id))?;
9044
9045    // Overlay the canonical form fields onto the virtual page. The
9046    // tree placement (parent / path / url_path) stays as-saved so
9047    // breadcrumb + ancestor lookups still work.
9048    if let Some(v) = form_map.get("title") {
9049        page.title = v.clone();
9050    }
9051    if let Some(v) = form_map.get("slug") {
9052        page.slug = v.clone();
9053    }
9054    if let Some(v) = form_map
9055        .get("page_type_id")
9056        .and_then(|s| s.parse::<i64>().ok())
9057    {
9058        page.page_type_id = v;
9059    }
9060    if let Some(v) = form_map.get("status") {
9061        page.status = v.clone();
9062    }
9063    if let Some(v) = form_map.get("seo_title") {
9064        page.seo_title = v.clone();
9065    }
9066    if let Some(v) = form_map.get("seo_description") {
9067        page.seo_description = v.clone();
9068    }
9069    // Checkboxes submit `on` when checked, absent when unchecked.
9070    page.robots_index = form_map
9071        .get("robots_index")
9072        .map(|v| matches!(v.as_str(), "on" | "true" | "1"))
9073        .unwrap_or(page.robots_index);
9074    if let Some(v) = form_map
9075        .get("sitemap_priority")
9076        .and_then(|s| s.parse::<f32>().ok())
9077    {
9078        page.sitemap_priority = v;
9079    }
9080    if let Some(raw) = form_map.get("theme_id") {
9081        page.theme_id = if raw.is_empty() || raw == "0" {
9082            None
9083        } else {
9084            raw.parse::<i64>().ok()
9085        };
9086    }
9087
9088    // The editor's JSON pane sends `Accept: application/json`, so the
9089    // same renderer that answers the public URL answers the preview —
9090    // which is what makes the pane show the real response body rather
9091    // than an admin-side reconstruction of it.
9092    let accept = crate::page_view::parse_accept(
9093        headers
9094            .get(axum::http::header::ACCEPT)
9095            .and_then(|v| v.to_str().ok()),
9096    );
9097    let force_json = q.format.as_deref() == Some("json");
9098    let response = crate::render::render_preview(
9099        &tenant,
9100        &preview_tera(&state, &tenant),
9101        &page,
9102        "",
9103        // Preview renders tenant-absolute paths — see the GET twin.
9104        "",
9105        q.locale.as_deref(),
9106        &form_map,
9107        accept,
9108        force_json,
9109    )
9110    .await;
9111    // #208 — same axe splice as the GET preview handler above. It gates
9112    // on `text/html`, so a JSON preview passes through untouched and
9113    // never pulls axe-core into the pane.
9114    Ok(stamp_no_cache(inject_axe_into_preview(response).await))
9115}
9116
9117// =====================================================================
9118// Library tab
9119// =====================================================================
9120
9121/// GET /cms-admin/library — placeholder until a real
9122/// `register_library_type!` macro lands. Shows the registered
9123/// PageTypeHandlers as a stand-in so the chrome demos cleanly.
9124/// Query for the paginated, filtered, folder-scoped snippet list.
9125#[derive(Debug, Deserialize, Default)]
9126pub struct LibraryListQuery {
9127    /// When set, focuses the list to one library type. When absent,
9128    /// the overview (one card per registered type with counts) shows.
9129    #[serde(default)]
9130    pub r#type: Option<String>,
9131    /// Folder prefix to scope the list to. Empty / unset = root.
9132    #[serde(default)]
9133    pub folder: Option<String>,
9134    /// Free-text query — matched against the type handler's
9135    /// `search_fields()`.
9136    #[serde(default)]
9137    pub q: Option<String>,
9138    /// 1-based page number.
9139    #[serde(default)]
9140    pub page: Option<u32>,
9141    /// Rows per page. Named so it is consumed here rather than falling
9142    /// into `raw_filters` and being read as a filter chip.
9143    #[serde(default)]
9144    pub per_page: Option<usize>,
9145    /// Catch-all bucket for `filter_<key>=<value>` filter chips. Any
9146    /// query parameter starting with `filter_` lands here.
9147    #[serde(flatten)]
9148    pub raw_filters: std::collections::HashMap<String, String>,
9149}
9150
9151pub async fn library_list(
9152    State(state): State<super::AdminState>,
9153    tenant: Tenant,
9154    headers: HeaderMap,
9155    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
9156    Query(q): Query<LibraryListQuery>,
9157    axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
9158) -> Result<Response, AdminError> {
9159    // Sidebar / overview data — all types + total counts. Forms are excluded:
9160    // they have their own dedicated area (`/cms-admin/forms`, sidebar "Forms")
9161    // with per-form submission counts, so listing them here would be a second,
9162    // weaker path to the same thing. Direct `?type=form` URLs still work.
9163    let types: Vec<crate::library::LibraryType> = crate::library::LibraryType::objects()
9164        .order_by(&[("type_name", false)])
9165        .fetch(tenant.pool())
9166        .await?
9167        .into_iter()
9168        .filter(|t| t.type_name != "form")
9169        .collect();
9170    let all_snippets: Vec<crate::snippet::Snippet> = crate::snippet::Snippet::objects()
9171        .fetch(tenant.pool())
9172        .await?;
9173    let mut counts_by_type: std::collections::HashMap<String, i64> =
9174        std::collections::HashMap::new();
9175    for s in &all_snippets {
9176        *counts_by_type.entry(s.type_name.clone()).or_default() += 1;
9177    }
9178
9179    let mut ctx = Context::new();
9180    add_chrome(&mut ctx, &tenant, "library", session_user.as_ref()).await;
9181    add_admin_theme(&mut ctx, tenant.pool()).await;
9182    // #316 — raw query string for the `| querystring(page=…)` filter in
9183    // the pagination links (preserves type/folder/q/filter_* + sets page).
9184    ctx.insert("query_string", &raw_query.unwrap_or_default());
9185    ctx.insert("types", &types);
9186    ctx.insert("counts_by_type", &counts_by_type);
9187
9188    // Overview mode — no `?type=`, show one card per registered type.
9189    let Some(type_name) = q.r#type.as_deref().filter(|s| !s.is_empty()) else {
9190        ctx.insert("mode", "overview");
9191        return render_with_csrf(&state, &headers, "rcms_admin/library_list.html", &mut ctx);
9192    };
9193
9194    // Resolve the handler so we can call list_display / search_fields
9195    // / list_filter / render_cell.
9196    let handler = crate::library::find_handler(type_name);
9197    let list_display = handler
9198        .as_ref()
9199        .map(|h| h.list_display())
9200        .unwrap_or_else(|| {
9201            vec![
9202                crate::library::ListColumn::Field {
9203                    column: "title",
9204                    label: "Title",
9205                },
9206                crate::library::ListColumn::Field {
9207                    column: "slug",
9208                    label: "Slug",
9209                },
9210                crate::library::ListColumn::Field {
9211                    column: "updated_at",
9212                    label: "Updated",
9213                },
9214            ]
9215        });
9216    let search_fields = handler
9217        .as_ref()
9218        .map(|h| h.search_fields())
9219        .unwrap_or_else(|| vec!["title", "slug"]);
9220    let filter_keys = handler
9221        .as_ref()
9222        .map(|h| h.list_filter())
9223        .unwrap_or_default();
9224
9225    // Folder scoping. Snippets with `folder_path = <current>` are
9226    // direct contents; we also surface the immediate sub-folder
9227    // names so the user can drill in.
9228    let folder = crate::snippet::normalize_folder(q.folder.as_deref().unwrap_or(""));
9229    let child_folders = crate::snippet::child_folders(tenant.pool(), &folder)
9230        .await
9231        .unwrap_or_default();
9232
9233    // Apply filters — type, folder, then per-data.<key> chips +
9234    // per-row `can_view` (#21 phase 1) so handler-supplied hooks
9235    // suppress rows from the list.
9236    let mut filtered: Vec<crate::snippet::Snippet> = all_snippets
9237        .iter()
9238        .filter(|s| s.type_name == type_name && s.folder_path == folder)
9239        .filter(|s| handler.as_ref().map(|h| h.can_view(s)).unwrap_or(true))
9240        .cloned()
9241        .collect();
9242
9243    // Search — ILIKE pattern on each search_field, ANY match wins.
9244    let search_q = q.q.as_deref().map(|s| s.trim()).filter(|s| !s.is_empty());
9245    if let Some(needle) = search_q {
9246        let needle_lower = needle.to_lowercase();
9247        filtered.retain(|s| {
9248            search_fields.iter().any(|field| {
9249                let hay = match *field {
9250                    "title" => s.title.to_lowercase(),
9251                    "slug" => s.slug.to_lowercase(),
9252                    "body_markdown" => s.body_markdown.to_lowercase(),
9253                    other => s
9254                        .data
9255                        .get(other)
9256                        .and_then(serde_json::Value::as_str)
9257                        .map(str::to_lowercase)
9258                        .unwrap_or_default(),
9259                };
9260                hay.contains(&needle_lower)
9261            })
9262        });
9263    }
9264
9265    // `filter_<key>=<value>` chips — flatten raw_filters into a
9266    // typed map first so we don't carry useless keys into context.
9267    let mut active_filters: std::collections::HashMap<String, String> =
9268        std::collections::HashMap::new();
9269    for (k, v) in &q.raw_filters {
9270        if let Some(stripped) = k.strip_prefix("filter_") {
9271            if !v.is_empty() {
9272                active_filters.insert(stripped.to_owned(), v.clone());
9273            }
9274        }
9275    }
9276    if !active_filters.is_empty() {
9277        filtered.retain(|s| {
9278            active_filters.iter().all(|(key, want)| {
9279                let got = s
9280                    .data
9281                    .get(key)
9282                    .map(|v| match v {
9283                        serde_json::Value::String(s) => s.clone(),
9284                        other => other.to_string(),
9285                    })
9286                    .unwrap_or_default();
9287                got == *want
9288            })
9289        });
9290    }
9291
9292    // Filter chip options (distinct values per filterable key).
9293    let filter_options: std::collections::HashMap<String, Vec<String>> = filter_keys
9294        .iter()
9295        .map(|k| {
9296            let mut opts: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
9297            for s in &all_snippets {
9298                if s.type_name != type_name {
9299                    continue;
9300                }
9301                if let Some(v) = s.data.get(*k) {
9302                    let s = match v {
9303                        serde_json::Value::String(s) => s.clone(),
9304                        other => other.to_string(),
9305                    };
9306                    if !s.is_empty() {
9307                        opts.insert(s);
9308                    }
9309                }
9310            }
9311            ((*k).to_owned(), opts.into_iter().collect())
9312        })
9313        .collect();
9314
9315    // Pagination — driven by `rustango::pagination::Paginator`.
9316    // `get_page()` never errors; out-of-range numbers clamp to the
9317    // last page (or 1 when empty). The slice indices come from
9318    // `start_index() - 1 .. end_index()` (the paginator returns
9319    // 1-based inclusive indices for "Showing X–Y" UI lines).
9320    let total = filtered.len();
9321    let page_size = crate::admin::pagination::clamp_per_page(q.per_page);
9322    let paginator = rustango::pagination::Paginator::new(total, page_size);
9323    let requested_page = q.page.unwrap_or(1).max(1) as i64;
9324    let page_obj = paginator.get_page(requested_page);
9325    let page = page_obj.number;
9326    let total_pages = paginator.num_pages().max(1);
9327    let page_rows: Vec<crate::snippet::Snippet> = if total == 0 {
9328        Vec::new()
9329    } else {
9330        let start = page_obj.start_index().saturating_sub(1);
9331        let end = page_obj.end_index();
9332        filtered[start..end].to_vec()
9333    };
9334
9335    // Pre-render each row's cells so the template doesn't need to
9336    // know about ListColumn variants. Each row → Vec<String> of
9337    // pre-escaped HTML strings (cells), aligned with `column_headers`.
9338    let column_headers: Vec<serde_json::Value> = list_display
9339        .iter()
9340        .map(|c| {
9341            serde_json::json!({
9342                "key": c.key(),
9343                "label": c.label(),
9344            })
9345        })
9346        .collect();
9347    let rows_html: Vec<serde_json::Value> = page_rows
9348        .iter()
9349        .map(|row| {
9350            let cells: Vec<String> = list_display
9351                .iter()
9352                .map(|c| render_list_cell(c, row, handler.as_deref()))
9353                .collect();
9354            serde_json::json!({
9355                "id": row.id.get().copied().unwrap_or_default(),
9356                "slug": row.slug,
9357                "cells": cells,
9358            })
9359        })
9360        .collect();
9361
9362    let active_filters_json: Vec<serde_json::Value> = active_filters
9363        .iter()
9364        .map(|(k, v)| serde_json::json!({ "key": k, "value": v }))
9365        .collect();
9366
9367    // Handler-declared bulk + row actions (#21 phase 2). Serialize
9368    // the structs into the JSON shape the template iterates.
9369    let bulk_actions: Vec<serde_json::Value> = handler
9370        .as_ref()
9371        .map(|h| h.bulk_actions())
9372        .unwrap_or_default()
9373        .iter()
9374        .map(serialize_bulk_action)
9375        .collect();
9376    let row_actions: Vec<serde_json::Value> = handler
9377        .as_ref()
9378        .map(|h| h.row_actions())
9379        .unwrap_or_default()
9380        .iter()
9381        .map(serialize_bulk_action)
9382        .collect();
9383
9384    // #134 — plugin-contributed bulk actions targeting `cms_snippet`.
9385    let plugin_bulk_actions: Vec<serde_json::Value> = crate::hooks::bulk_actions_for("cms_snippet")
9386        .into_iter()
9387        .map(|a| {
9388            serde_json::json!({
9389                "key": a.key,
9390                "label": a.label,
9391                "icon": a.icon,
9392                "danger": a.danger,
9393                "confirm_message": a.confirm_message,
9394                "action_url": a.action_url,
9395            })
9396        })
9397        .collect();
9398
9399    // #196 — full folder tree for the left rail. Flat list of every
9400    // folder_path (including derived intermediates), sorted; the
9401    // template renders each row with depth-based indentation based
9402    // on the slash count.
9403    let folder_tree_paths = crate::snippet::folder_tree_for_type(tenant.pool(), type_name)
9404        .await
9405        .unwrap_or_default();
9406    let folder_tree: Vec<serde_json::Value> = folder_tree_paths
9407        .iter()
9408        .map(|p| {
9409            let depth = p.matches('/').count(); // root="" → 0; "a/" → 1; "a/b/" → 2
9410            let display = if p.is_empty() {
9411                "Root".to_owned()
9412            } else {
9413                // Last non-empty segment is the displayed name.
9414                p.trim_end_matches('/')
9415                    .rsplit('/')
9416                    .next()
9417                    .unwrap_or("")
9418                    .to_owned()
9419            };
9420            serde_json::json!({
9421                "path": p,
9422                "name": display,
9423                "depth": depth,
9424                "active": *p == folder,
9425            })
9426        })
9427        .collect();
9428
9429    ctx.insert("mode", "type");
9430    ctx.insert("active_type", type_name);
9431    ctx.insert("folder", &folder);
9432    ctx.insert("child_folders", &child_folders);
9433    ctx.insert("folder_tree", &folder_tree);
9434    ctx.insert("column_headers", &column_headers);
9435    ctx.insert("rows", &rows_html);
9436    ctx.insert("plugin_bulk_actions", &plugin_bulk_actions);
9437    ctx.insert("page", &page);
9438    ctx.insert("total_pages", &total_pages);
9439    // Shared control row (`rcms_admin/_pagination.html`); the bespoke
9440    // vars above stay for the rest of the template.
9441    ctx.insert(
9442        "pagination",
9443        &crate::admin::pagination::context(page as i64, page_size, total),
9444    );
9445    ctx.insert("total", &total);
9446    ctx.insert("page_size", &page_size);
9447    ctx.insert("search_q", &search_q.unwrap_or(""));
9448    ctx.insert("filter_keys", &filter_keys);
9449    ctx.insert("filter_options", &filter_options);
9450    ctx.insert("active_filters", &active_filters_json);
9451    ctx.insert("bulk_actions", &bulk_actions);
9452    ctx.insert("row_actions", &row_actions);
9453    render_with_csrf(&state, &headers, "rcms_admin/library_list.html", &mut ctx)
9454}
9455
9456/// Bulk-action button shape the library_list template iterates.
9457fn serialize_bulk_action(a: &crate::library::BulkAction) -> serde_json::Value {
9458    use crate::library::BulkActionStyle;
9459    let style_class = match a.style {
9460        BulkActionStyle::Primary => "btn",
9461        BulkActionStyle::Outlined => "btn btn-outlined",
9462        BulkActionStyle::Danger => "btn btn-danger",
9463    };
9464    serde_json::json!({
9465        "name": a.name,
9466        "label": a.label,
9467        "icon": a.icon,
9468        "confirm_message": a.confirm_message,
9469        "style_class": style_class,
9470    })
9471}
9472
9473/// POST /cms-admin/library/{type}/bulk — dispatch a bulk action
9474/// to the registered LibraryTypeHandler. Body shape:
9475/// `action=<name>&ids=<id>&ids=<id>...`. Returns the editor back
9476/// to the type's list view with a flash message reporting how many
9477/// rows the handler processed.
9478pub async fn library_bulk_submit(
9479    State(_state): State<super::AdminState>,
9480    tenant: Tenant,
9481    headers: HeaderMap,
9482    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
9483    Path(type_name): Path<String>,
9484    Form(form): Form<Vec<(String, String)>>,
9485) -> Result<Response, AdminError> {
9486    let action = form
9487        .iter()
9488        .find(|(k, _)| k == "action")
9489        .map(|(_, v)| v.clone())
9490        .unwrap_or_default();
9491    let ids: Vec<i64> = form
9492        .iter()
9493        .filter(|(k, _)| k == "ids" || k == "id")
9494        .filter_map(|(_, v)| v.parse::<i64>().ok())
9495        .collect();
9496    if action.is_empty() || ids.is_empty() {
9497        return redirect_named_with_message(
9498            "rcms-admin:library:list",
9499            MsgLevel::Warning,
9500            "Pick at least one row + a bulk action before submitting.",
9501            &headers,
9502        );
9503    }
9504    let Some(handler) = crate::library::find_handler(&type_name) else {
9505        return Err(AdminError::Validation(format!(
9506            "unknown library type `{type_name}`"
9507        )));
9508    };
9509    // Validate that the named action is in the handler's declared
9510    // set — guards against forged form posts.
9511    let declared: std::collections::HashSet<&'static str> = handler
9512        .bulk_actions()
9513        .iter()
9514        .chain(handler.row_actions().iter())
9515        .map(|a| a.name)
9516        .collect();
9517    if !declared.contains(action.as_str()) {
9518        return Err(AdminError::Validation(format!(
9519            "library type `{type_name}` doesn't declare bulk action `{action}`"
9520        )));
9521    }
9522    let touched = handler
9523        .handle_bulk_action(tenant.pool(), &action, &ids)
9524        .await?;
9525    let count = touched.to_string();
9526    redirect_named_with_message_plural(
9527        "rcms-admin:library:list",
9528        MsgLevel::Success,
9529        "{action}: touched {count} row(s) in `{type_name}`.",
9530        touched as i64,
9531        &[
9532            ("action", action.as_str()),
9533            ("count", count.as_str()),
9534            ("type_name", type_name.as_str()),
9535        ],
9536        &headers,
9537    )
9538}
9539
9540/// Render one cell for a [`ListColumn`] / row pair into pre-escaped
9541/// HTML. Handles type-aware formatting: booleans → ✓/✗, datetimes →
9542/// 10-char prefix, FK-ish text → escape, JSON lookups → kind-driven
9543/// formatting, method fields → handler-supplied HTML (trusted —
9544/// caller is responsible for escaping).
9545fn render_list_cell(
9546    col: &crate::library::ListColumn,
9547    row: &crate::snippet::Snippet,
9548    handler: Option<&dyn crate::library::LibraryTypeHandler>,
9549) -> String {
9550    use crate::library::{ListColumn, ListColumnKind};
9551    match col {
9552        ListColumn::Field { column, .. } => match *column {
9553            "id" => row.id.get().copied().unwrap_or_default().to_string(),
9554            "type_name" => html_escape(&row.type_name),
9555            "slug" => format!("<code>{}</code>", html_escape(&row.slug)),
9556            "folder_path" => html_escape(&row.folder_path),
9557            "title" => format!("<strong>{}</strong>", html_escape(&row.title)),
9558            "body_markdown" => {
9559                let preview: String = row.body_markdown.chars().take(80).collect();
9560                format!("<span>{}</span>", html_escape(&preview))
9561            }
9562            "created_at" => row
9563                .created_at
9564                .get()
9565                .map(|d| d.format("%Y-%m-%d").to_string())
9566                .unwrap_or_default(),
9567            "updated_at" => row
9568                .updated_at
9569                .get()
9570                .map(|d| d.format("%Y-%m-%d").to_string())
9571                .unwrap_or_default(),
9572            other => format!("<em>(unknown field: {})</em>", html_escape(other)),
9573        },
9574        ListColumn::JsonField { key, kind, .. } => {
9575            let val = row.data.get(*key);
9576            match (kind, val) {
9577                (ListColumnKind::Bool, Some(serde_json::Value::Bool(b))) => bool_checkbox_html(*b),
9578                (_, Some(serde_json::Value::Bool(b))) => bool_checkbox_html(*b),
9579                (ListColumnKind::Integer, Some(serde_json::Value::Number(n)))
9580                | (ListColumnKind::Float, Some(serde_json::Value::Number(n))) => {
9581                    html_escape(&n.to_string())
9582                }
9583                (_, Some(serde_json::Value::String(s))) => html_escape(s),
9584                (_, Some(other)) => html_escape(&other.to_string()),
9585                (_, None) => String::new(),
9586            }
9587        }
9588        ListColumn::Method { name, .. } | ListColumn::Computed { name, .. } => handler
9589            .map(|h| h.render_cell(name, row))
9590            .unwrap_or_default(),
9591    }
9592}
9593
9594fn html_escape(s: &str) -> String {
9595    s.replace('&', "&amp;")
9596        .replace('<', "&lt;")
9597        .replace('>', "&gt;")
9598        .replace('"', "&quot;")
9599}
9600
9601fn bool_checkbox_html(b: bool) -> String {
9602    if b {
9603        r#"<span class="material-symbols-rounded sm filled" style="color: var(--accent);" aria-label="true">check_box</span>"#.to_owned()
9604    } else {
9605        r#"<span class="material-symbols-rounded sm" style="color: var(--muted-2);" aria-label="false">check_box_outline_blank</span>"#.to_owned()
9606    }
9607}
9608
9609/// GET /cms-admin/library/new?type=<type_name> — render the create
9610/// form for a new snippet. The type pre-selects from the query string
9611/// so the "+ New <Type>" CTA on the list page lands here.
9612#[derive(Debug, Deserialize)]
9613pub struct SnippetNewQuery {
9614    #[serde(default)]
9615    pub r#type: Option<String>,
9616    #[serde(default)]
9617    pub folder: Option<String>,
9618}
9619
9620pub async fn snippet_new_form(
9621    State(state): State<super::AdminState>,
9622    tenant: Tenant,
9623    headers: HeaderMap,
9624    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
9625    Query(q): Query<SnippetNewQuery>,
9626) -> Result<Response, AdminError> {
9627    let types: Vec<crate::library::LibraryType> = crate::library::LibraryType::objects()
9628        .order_by(&[("type_name", false)])
9629        .fetch(tenant.pool())
9630        .await?;
9631    let mut ctx = Context::new();
9632    add_chrome(&mut ctx, &tenant, "library", session_user.as_ref()).await;
9633    add_admin_theme(&mut ctx, tenant.pool()).await;
9634    ctx.insert("mode", "new");
9635    ctx.insert("types", &types);
9636    ctx.insert("preselect_type", &q.r#type.unwrap_or_default());
9637    let folder = q.folder.unwrap_or_default();
9638    ctx.insert(
9639        "snippet",
9640        &serde_json::json!({
9641            "type_name": "",
9642            "slug": "",
9643            "title": "",
9644            "body_markdown": "",
9645            "folder_path": folder,
9646        }),
9647    );
9648    render_with_csrf(&state, &headers, "rcms_admin/snippet_form.html", &mut ctx)
9649}
9650
9651pub async fn snippet_edit_form(
9652    State(state): State<super::AdminState>,
9653    tenant: Tenant,
9654    headers: HeaderMap,
9655    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
9656    Path(id): Path<i64>,
9657    Query(q): Query<EditQuery>,
9658) -> Result<Response, AdminError> {
9659    let snippet = crate::snippet::Snippet::objects()
9660        .where_(crate::snippet::Snippet::id.eq(id))
9661        .first(tenant.pool())
9662        .await?
9663        .ok_or(AdminError::NotFound(id))?;
9664    // FB-04 (#537) — forms are edited in the dedicated visual builder, not
9665    // the generic snippet form. The list's Edit link lands here; bounce to
9666    // the builder so the entry point "just works".
9667    if snippet.type_name == "form" {
9668        let url = rustango::urls::reverse_owned(
9669            "rcms-admin:forms:build",
9670            &std::collections::HashMap::from([("id".to_owned(), id.to_string())]),
9671        )
9672        .map_err(|e| AdminError::Validation(format!("url reversal failed: {e}")))?;
9673        return Ok(axum::response::Redirect::to(&url).into_response());
9674    }
9675    // Permission gate (#21 phase 3) — `can_view = false` denies
9676    // the edit page entirely (404 rather than 403 to avoid leaking
9677    // existence). `can_edit = false` lets the page render read-only
9678    // — we surface it via a `read_only` context var.
9679    let handler = crate::library::find_handler(&snippet.type_name);
9680    if let Some(h) = handler.as_ref() {
9681        if !h.can_view(&snippet) {
9682            return Err(AdminError::NotFound(id));
9683        }
9684    }
9685    let read_only = handler
9686        .as_ref()
9687        .map(|h| !h.can_edit(&snippet))
9688        .unwrap_or(false);
9689    let can_delete = handler
9690        .as_ref()
9691        .map(|h| h.can_delete(&snippet))
9692        .unwrap_or(true);
9693    // Optional custom edit template — falls back to the default
9694    // `snippet_form.html` when not overridden.
9695    let template_path = handler
9696        .as_ref()
9697        .and_then(|h| h.edit_template())
9698        .unwrap_or("rcms_admin/snippet_form.html");
9699
9700    let types: Vec<crate::library::LibraryType> = crate::library::LibraryType::objects()
9701        .order_by(&[("type_name", false)])
9702        .fetch(tenant.pool())
9703        .await?;
9704    let mut ctx = Context::new();
9705    add_chrome(&mut ctx, &tenant, "library", session_user.as_ref()).await;
9706    add_admin_theme(&mut ctx, tenant.pool()).await;
9707    ctx.insert("mode", "edit");
9708    ctx.insert("types", &types);
9709    ctx.insert("snippet", &snippet);
9710    ctx.insert("read_only", &read_only);
9711    ctx.insert("can_delete", &can_delete);
9712    // Types that let each element name its own template get the field;
9713    // for every other type the concept doesn't exist and the form
9714    // shouldn't imply it does.
9715    ctx.insert(
9716        "allows_element_template",
9717        &handler
9718            .as_ref()
9719            .map(|h| h.allows_element_template())
9720            .unwrap_or(false),
9721    );
9722    // #123 — surface revision history + preview opt-in flags so the
9723    // edit template can render a History card + Preview link only
9724    // for types that opted in.
9725    let revisions_enabled = handler.as_ref().is_some_and(|h| h.revisions_enabled());
9726    let preview_enabled = handler.as_ref().is_some_and(|h| h.preview_enabled());
9727    let revisions: Vec<crate::snippet::SnippetRevision> = if revisions_enabled {
9728        crate::snippet::revisions_for(tenant.pool(), id)
9729            .await
9730            .unwrap_or_default()
9731    } else {
9732        Vec::new()
9733    };
9734    ctx.insert("revisions_enabled", &revisions_enabled);
9735    ctx.insert("preview_enabled", &preview_enabled);
9736    ctx.insert("snippet_revisions", &revisions);
9737    // #409 — snippet translation mode. `?locale=<code>` (a non-default
9738    // active locale) shows a per-field translation editor beside the
9739    // canonical content, mirroring the page translate flow.
9740    let locales: Vec<crate::locale::Locale> = crate::locale::Locale::objects()
9741        .where_(crate::locale::Locale::active.eq(true))
9742        .order_by(&[("sort_order", false), ("code", false)])
9743        .fetch(tenant.pool())
9744        .await?;
9745    let editing_locale = q
9746        .locale
9747        .as_deref()
9748        .filter(|c| !c.is_empty())
9749        .and_then(|code| locales.iter().find(|l| l.code == code).cloned());
9750    let translation_mode = editing_locale.as_ref().is_some_and(|l| !l.is_default);
9751    let mut core_translations: std::collections::HashMap<String, String> =
9752        std::collections::HashMap::new();
9753    let mut extra_translations: Vec<(String, String)> = Vec::new();
9754    if translation_mode {
9755        let lid = editing_locale
9756            .as_ref()
9757            .and_then(|l| l.id.get().copied())
9758            .unwrap_or_default();
9759        let existing = crate::snippet_translation::fetch_for(tenant.pool(), id, lid)
9760            .await
9761            .unwrap_or_default();
9762        let core_keys = ["title", "body_markdown"];
9763        core_translations = core_keys
9764            .iter()
9765            .map(|k| {
9766                (
9767                    (*k).to_owned(),
9768                    existing.get(*k).cloned().unwrap_or_default(),
9769                )
9770            })
9771            .collect();
9772        extra_translations = existing
9773            .iter()
9774            .filter(|(k, _)| !core_keys.contains(&k.as_str()))
9775            .map(|(k, v)| (k.clone(), v.clone()))
9776            .collect();
9777    }
9778    ctx.insert("locales", &locales);
9779    ctx.insert("editing_locale", &editing_locale);
9780    ctx.insert("translation_mode", &translation_mode);
9781    ctx.insert("core_translations", &core_translations);
9782    ctx.insert("extra_translations", &extra_translations);
9783    render_with_csrf(&state, &headers, template_path, &mut ctx)
9784}
9785
9786/// POST `/cms-admin/library/{id}/translate?locale=<code>` —
9787/// upsert per-field snippet translations for a non-default locale.
9788/// Mirrors [`page_translate_submit`]: `tr__<field>` keys edit existing
9789/// fields, `new_field_path` + `new_field_value` adds one; an empty
9790/// value deletes the row (canonical shows through). Atomic batch.
9791pub async fn snippet_translate_submit(
9792    State(_state): State<super::AdminState>,
9793    tenant: Tenant,
9794    Path(id): Path<i64>,
9795    Query(q): Query<EditQuery>,
9796    Form(form): Form<std::collections::HashMap<String, String>>,
9797) -> Result<Response, AdminError> {
9798    use crate::snippet_translation::SnippetTranslation;
9799    let code = q
9800        .locale
9801        .as_deref()
9802        .filter(|c| !c.is_empty())
9803        .ok_or_else(|| AdminError::Validation("translate requires ?locale=".to_owned()))?;
9804    let locale = crate::locale::Locale::objects()
9805        .where_(crate::locale::Locale::code.eq(code.to_owned()))
9806        .where_(crate::locale::Locale::active.eq(true))
9807        .first(tenant.pool())
9808        .await?
9809        .ok_or_else(|| AdminError::Validation(format!("unknown locale `{code}`")))?;
9810    if locale.is_default {
9811        return Ok((
9812            axum::http::StatusCode::BAD_REQUEST,
9813            "cannot translate INTO the default locale; canonical content lives on cms_snippet",
9814        )
9815            .into_response());
9816    }
9817    let locale_id = locale
9818        .id
9819        .get()
9820        .copied()
9821        .ok_or_else(|| AdminError::Validation("locale row missing id".to_owned()))?;
9822    // Verify the snippet exists.
9823    let snippet = crate::snippet::Snippet::objects()
9824        .where_(crate::snippet::Snippet::id.eq(id))
9825        .first(tenant.pool())
9826        .await?
9827        .ok_or(AdminError::NotFound(id))?;
9828
9829    // Collect `tr__<field>` edits + an optional new-field row.
9830    let mut updates: Vec<(String, String)> = Vec::new();
9831    for (k, v) in &form {
9832        if let Some(path) = k.strip_prefix("tr__") {
9833            if !path.is_empty() {
9834                updates.push((path.to_owned(), v.clone()));
9835            }
9836        }
9837    }
9838    let new_path_raw = form.get("new_field_path").map(String::as_str).unwrap_or("");
9839    if !new_path_raw.trim().is_empty() {
9840        // Reuse the model's validator; silently skip a malformed path
9841        // rather than 400 the whole batch.
9842        if let Ok(path) = crate::snippet_translation::validate_field_path(new_path_raw) {
9843            let value = form.get("new_field_value").cloned().unwrap_or_default();
9844            updates.push((path, value));
9845        }
9846    }
9847
9848    // Empty value → delete; non-empty → upsert. Atomic batch.
9849    rustango::atomic!(tenant.pool(), |tx| {
9850        let mut guard = tx.lock().await?;
9851        let tx = &mut *guard;
9852        for (path, value) in updates {
9853            let existing: Vec<SnippetTranslation> = SnippetTranslation::objects()
9854                .where_(SnippetTranslation::snippet_id.eq(id))
9855                .where_(SnippetTranslation::locale_id.eq(locale_id))
9856                .where_(SnippetTranslation::field_path.eq(path.clone()))
9857                .fetch_tx(tx)
9858                .await?;
9859            if value.is_empty() {
9860                for row in existing {
9861                    row.delete_tx(tx).await?;
9862                }
9863            } else if let Some(mut row) = existing.into_iter().next() {
9864                row.value = value;
9865                row.save_tx(tx).await?;
9866            } else {
9867                let mut row = SnippetTranslation {
9868                    id: rustango::sql::Auto::Unset,
9869                    snippet_id: id,
9870                    locale_id,
9871                    field_path: path,
9872                    value,
9873                    updated_at: rustango::sql::Auto::Unset,
9874                };
9875                row.save_tx(tx).await?;
9876            }
9877        }
9878        Ok::<_, rustango::sql::ExecError>(())
9879    })
9880    .await?;
9881
9882    // A form is translated on its own screen; its library edit page
9883    // forwards to the builder and would drop the language.
9884    let back = if snippet.type_name == "form" {
9885        format!("/cms-admin/forms/{id}/build?locale={code}")
9886    } else {
9887        format!("/cms-admin/library/{id}/edit?locale={code}")
9888    };
9889    Ok(Redirect::to(&back).into_response())
9890}
9891
9892/// POST /cms-admin/library/snippets/{id}/revert/{seq} — restore a
9893/// snippet to the snapshot stored in the named revision. Captures a
9894/// fresh revision after the revert so the timeline stays linear.
9895pub async fn snippet_revert_submit(
9896    State(_state): State<super::AdminState>,
9897    tenant: Tenant,
9898    headers: HeaderMap,
9899    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
9900    Path((id, sequence)): Path<(i64, i32)>,
9901) -> Result<Response, AdminError> {
9902    let Some(rev) = crate::snippet::revision_by_sequence(tenant.pool(), id, sequence).await? else {
9903        return Err(AdminError::NotFound(id));
9904    };
9905    let mut snippet = crate::snippet::Snippet::objects()
9906        .where_(crate::snippet::Snippet::id.eq(id))
9907        .first(tenant.pool())
9908        .await?
9909        .ok_or(AdminError::NotFound(id))?;
9910    // Re-hydrate from the snapshot — title / body / slug / data /
9911    // folder_path / type_name. Skip primary key + audit timestamps.
9912    let snap = &rev.snapshot;
9913    if let Some(v) = snap.get("title").and_then(|v| v.as_str()) {
9914        snippet.title = v.to_owned();
9915    }
9916    if let Some(v) = snap.get("slug").and_then(|v| v.as_str()) {
9917        snippet.slug = v.to_owned();
9918    }
9919    if let Some(v) = snap.get("body_markdown").and_then(|v| v.as_str()) {
9920        snippet.body_markdown = v.to_owned();
9921    }
9922    if let Some(v) = snap.get("folder_path").and_then(|v| v.as_str()) {
9923        snippet.folder_path = v.to_owned();
9924    }
9925    if let Some(v) = snap.get("type_name").and_then(|v| v.as_str()) {
9926        snippet.type_name = v.to_owned();
9927    }
9928    if let Some(v) = snap.get("data") {
9929        snippet.data = v.clone();
9930    }
9931    snippet.save(tenant.pool()).await?;
9932    // Capture the revert itself so the timeline shows it.
9933    if let Some(handler) = crate::library::find_handler(&snippet.type_name) {
9934        if handler.revisions_enabled() {
9935            let captured_by = session_user.as_ref().and_then(|u| u.id.get().copied());
9936            crate::snippet::capture_revision(tenant.pool(), &snippet, captured_by)
9937                .await
9938                .log_warn("revision not captured; the history has a gap");
9939        }
9940    }
9941    let sequence_str = sequence.to_string();
9942    redirect_named_with_params_and_message_args(
9943        "rcms-admin:library:edit",
9944        &[("id", id.to_string())],
9945        MsgLevel::Success,
9946        "Reverted to revision #{sequence}.",
9947        &[("sequence", sequence_str.as_str())],
9948        &headers,
9949    )
9950}
9951
9952pub async fn snippet_create_submit(
9953    State(_state): State<super::AdminState>,
9954    tenant: Tenant,
9955    headers: HeaderMap,
9956    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
9957    Form(form): Form<std::collections::HashMap<String, String>>,
9958) -> Result<Response, AdminError> {
9959    let type_name = form.get("type_name").cloned().unwrap_or_default();
9960    let slug = form.get("slug").cloned().unwrap_or_default();
9961    let title = form.get("title").cloned().unwrap_or_default();
9962    let body = form.get("body_markdown").cloned().unwrap_or_default();
9963    let folder_path = form
9964        .get("folder_path")
9965        .map(|s| crate::snippet::normalize_folder(s))
9966        .unwrap_or_default();
9967    if type_name.is_empty() || slug.is_empty() || title.is_empty() {
9968        return Err(AdminError::Validation(
9969            "type, slug, and title are all required".to_owned(),
9970        ));
9971    }
9972    let mut row = crate::snippet::Snippet {
9973        id: rustango::sql::Auto::Unset,
9974        type_name,
9975        slug,
9976        folder_path,
9977        title,
9978        body_markdown: body,
9979        data: serde_json::Value::Object(serde_json::Map::new()),
9980        created_at: rustango::sql::Auto::Unset,
9981        updated_at: rustango::sql::Auto::Unset,
9982    };
9983    row.save(tenant.pool()).await?;
9984    // A new form is empty until its fields are built — go straight to the
9985    // Form Builder rather than back to the Library list.
9986    if row.type_name == "form" {
9987        let id = row.id.get().copied().unwrap_or_default();
9988        return redirect_named_with_params_and_message(
9989            "rcms-admin:forms:build",
9990            &[("id", id.to_string())],
9991            MsgLevel::Success,
9992            &super::i18n::tr(
9993                &headers,
9994                "Created snippet “{title}”.",
9995                &[("title", row.title.as_str())],
9996            ),
9997            &headers,
9998        );
9999    }
10000    redirect_named_with_message_args(
10001        "rcms-admin:library:list",
10002        MsgLevel::Success,
10003        "Created snippet “{title}”.",
10004        &[("title", row.title.as_str())],
10005        &headers,
10006    )
10007}
10008
10009pub async fn snippet_edit_submit(
10010    State(_state): State<super::AdminState>,
10011    tenant: Tenant,
10012    headers: HeaderMap,
10013    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
10014    Path(id): Path<i64>,
10015    Form(form): Form<std::collections::HashMap<String, String>>,
10016) -> Result<Response, AdminError> {
10017    let mut snippet = crate::snippet::Snippet::objects()
10018        .where_(crate::snippet::Snippet::id.eq(id))
10019        .first(tenant.pool())
10020        .await?
10021        .ok_or(AdminError::NotFound(id))?;
10022    // Permission gate (#21 phase 3) — handler-declared can_edit
10023    // hook short-circuits the save. V1 default is `true`; hosts
10024    // override to wire role-aware logic.
10025    if let Some(handler) = crate::library::find_handler(&snippet.type_name) {
10026        if !handler.can_edit(&snippet) {
10027            return Err(AdminError::Validation(format!(
10028                "Library type `{}` denies edit on this row.",
10029                snippet.type_name
10030            )));
10031        }
10032        // Cross-field validation hook — surfaces field-scoped error
10033        // strings before any mutation lands.
10034        if let Err(errors) = handler.validate(&form) {
10035            let summary: Vec<String> = errors
10036                .into_iter()
10037                .map(|(field, msg)| format!("{field}: {msg}"))
10038                .collect();
10039            return Err(AdminError::Validation(summary.join("; ")));
10040        }
10041    }
10042    if let Some(v) = form.get("type_name") {
10043        if !v.is_empty() {
10044            snippet.type_name = v.clone();
10045        }
10046    }
10047    if let Some(v) = form.get("slug") {
10048        if !v.is_empty() {
10049            snippet.slug = v.clone();
10050        }
10051    }
10052    if let Some(v) = form.get("title") {
10053        snippet.title = v.clone();
10054    }
10055    if let Some(v) = form.get("body_markdown") {
10056        snippet.body_markdown = v.clone();
10057    }
10058    if let Some(v) = form.get("folder_path") {
10059        snippet.folder_path = crate::snippet::normalize_folder(v);
10060    }
10061    // Per-element template name, for types that opted in via
10062    // `allows_element_template()`. Only that one `data` key is read
10063    // here: the generic form deliberately does not own `data` (typed
10064    // extras belong to a type's own `edit_template`), so a type that
10065    // never opted in cannot have its render repointed from this form.
10066    if crate::library::find_handler(&snippet.type_name)
10067        .is_some_and(|h| h.allows_element_template())
10068    {
10069        if let Some(v) = form.get("data__template") {
10070            crate::snippet::set_element_template(&mut snippet.data, v.trim());
10071        }
10072    }
10073    snippet.save(tenant.pool()).await?;
10074    // #123 — capture a versioned snapshot when the handler opts in
10075    // via `revisions_enabled()`. Best-effort: capture failure logs
10076    // + does NOT abort the save.
10077    if let Some(handler) = crate::library::find_handler(&snippet.type_name) {
10078        if handler.revisions_enabled() {
10079            let captured_by = session_user.as_ref().and_then(|u| u.id.get().copied());
10080            if let Err(e) =
10081                crate::snippet::capture_revision(tenant.pool(), &snippet, captured_by).await
10082            {
10083                tracing::warn!(
10084                    target: "rustango_cms::admin",
10085                    snippet_id = id,
10086                    type_name = %snippet.type_name,
10087                    error = %e,
10088                    "snippet revision capture failed",
10089                );
10090            }
10091        }
10092    }
10093    // #146 — reindex references from the saved snippet form.
10094    {
10095        let mut refs: Vec<crate::reference_index::Reference> = Vec::new();
10096        for (key, value) in &form {
10097            let mut found = crate::reference_index::scan(value, key);
10098            refs.append(&mut found);
10099        }
10100        if let Err(e) = crate::reference_index::reindex_source(
10101            tenant.pool(),
10102            crate::reference_index::KIND_SNIPPET,
10103            id,
10104            refs,
10105        )
10106        .await
10107        {
10108            tracing::warn!(
10109                target: "rustango_cms::reference_index",
10110                snippet_id = id, error = %e,
10111                "snippet reindex failed (best-effort)"
10112            );
10113        }
10114    }
10115    redirect_named_with_message_args(
10116        "rcms-admin:library:list",
10117        MsgLevel::Success,
10118        "Saved snippet “{title}”.",
10119        &[("title", snippet.title.as_str())],
10120        &headers,
10121    )
10122}
10123
10124pub async fn snippet_delete_submit(
10125    State(_state): State<super::AdminState>,
10126    tenant: Tenant,
10127    headers: HeaderMap,
10128    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
10129    Path(id): Path<i64>,
10130) -> Result<Response, AdminError> {
10131    let snippet = crate::snippet::Snippet::objects()
10132        .where_(crate::snippet::Snippet::id.eq(id))
10133        .first(tenant.pool())
10134        .await?
10135        .ok_or(AdminError::NotFound(id))?;
10136    // Permission gate (#21 phase 3) — handler can deny delete.
10137    if let Some(handler) = crate::library::find_handler(&snippet.type_name) {
10138        if !handler.can_delete(&snippet) {
10139            return Err(AdminError::Validation(format!(
10140                "Library type `{}` denies delete on this row.",
10141                snippet.type_name
10142            )));
10143        }
10144    }
10145    let title = snippet.title.clone();
10146    let is_form = snippet.type_name == "form";
10147    snippet.delete(tenant.pool()).await?;
10148    // Forms are deleted from the Forms screen — go back there.
10149    if is_form {
10150        let body = super::i18n::tr(&headers, "Deleted snippet “{title}”.", &[("title", title.as_str())]);
10151        return Ok(rustango::messages::redirect_with_message(
10152            messages_secret(),
10153            &headers,
10154            MsgLevel::Success,
10155            &body,
10156            "/cms-admin/forms",
10157        ));
10158    }
10159    redirect_named_with_message_args(
10160        "rcms-admin:library:list",
10161        MsgLevel::Success,
10162        "Deleted snippet “{title}”.",
10163        &[("title", title.as_str())],
10164        &headers,
10165    )
10166}
10167
10168// =====================================================================
10169// Media + Documents tabs
10170// =====================================================================
10171
10172/// Parse a `YYYY-MM-DD` filter into the UTC instant at start-of-day.
10173/// Empty / unparseable → None.
10174fn parse_date_floor(raw: Option<&str>) -> Option<chrono::DateTime<chrono::Utc>> {
10175    let raw = raw?.trim();
10176    if raw.is_empty() {
10177        return None;
10178    }
10179    chrono::NaiveDate::parse_from_str(raw, "%Y-%m-%d")
10180        .ok()
10181        .map(|d| {
10182            chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
10183                d.and_hms_opt(0, 0, 0).unwrap_or_default(),
10184                chrono::Utc,
10185            )
10186        })
10187}
10188
10189/// Parse a `YYYY-MM-DD` filter into the UTC instant at end-of-day
10190/// (23:59:59) so the inclusive ceiling matches editor intent.
10191fn parse_date_ceil(raw: Option<&str>) -> Option<chrono::DateTime<chrono::Utc>> {
10192    let raw = raw?.trim();
10193    if raw.is_empty() {
10194        return None;
10195    }
10196    chrono::NaiveDate::parse_from_str(raw, "%Y-%m-%d")
10197        .ok()
10198        .map(|d| {
10199            chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
10200                d.and_hms_opt(23, 59, 59).unwrap_or_default(),
10201                chrono::Utc,
10202            )
10203        })
10204}
10205
10206/// Query string for the media + documents list views. All filters
10207/// optional; URL state persists so editors can bookmark filtered
10208/// views.
10209#[derive(Debug, Deserialize)]
10210pub struct MediaListQuery {
10211    /// 1-based page number. Out-of-range values clamp to the last page.
10212    #[serde(default)]
10213    pub page: Option<i64>,
10214    /// Rows per page; clamped to `admin::pagination::MAX_PER_PAGE`.
10215    #[serde(default)]
10216    pub per_page: Option<usize>,
10217    /// Filter to a specific collection. Omitted = all collections.
10218    #[serde(default)]
10219    pub collection: Option<i64>,
10220    /// Case-insensitive substring search across title, filename,
10221    /// alt_text.
10222    #[serde(default)]
10223    pub q: Option<String>,
10224    /// Date range floor — `YYYY-MM-DD`. Matches `uploaded_at >= from`.
10225    #[serde(default)]
10226    pub from: Option<String>,
10227    /// Date range ceiling — `YYYY-MM-DD`. Matches `uploaded_at <= to`
10228    /// (end of day in UTC).
10229    #[serde(default)]
10230    pub to: Option<String>,
10231}
10232
10233// =====================================================================
10234// Image hard crop (#24) — apply / clone-and-crop
10235// =====================================================================
10236
10237/// Form payload for both crop handlers. Coords are in source-image
10238/// pixel space; `mode` distinguishes apply vs clone-and-crop.
10239#[derive(Debug, Deserialize)]
10240pub struct CropForm {
10241    pub crop_x: u32,
10242    pub crop_y: u32,
10243    pub crop_w: u32,
10244    pub crop_h: u32,
10245    /// Either "apply" (destructive — overwrites source) or "clone"
10246    /// (creates a new media row from the cropped bytes).
10247    pub mode: String,
10248}
10249
10250/// POST /cms-admin/media/{id}/crop — apply the crop rect to the
10251/// source bytes. Two modes:
10252/// - `mode=apply` — replaces the row's bytes in-place, bumps
10253///   content_hash, recomputes width/height, purges every rendition
10254///   for the old hash. Destructive — the original bytes are gone.
10255/// - `mode=clone` — creates a new media row whose bytes are the
10256///   cropped output. Original row is untouched. New row inherits
10257///   title (" — crop" suffix) + alt_text + collection_id; focal
10258///   point clears so the editor re-marks on the crop.
10259pub async fn media_crop_submit(
10260    State(_state): State<super::AdminState>,
10261    tenant: Tenant,
10262    headers: HeaderMap,
10263    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
10264    Path(id): Path<i64>,
10265    Form(form): Form<CropForm>,
10266) -> Result<Response, AdminError> {
10267    use rustango::sql::Auto;
10268    let mut media = Media::objects()
10269        .where_(Media::id.eq(id))
10270        .first(tenant.pool())
10271        .await?
10272        .ok_or(AdminError::NotFound(id))?;
10273    if media.kind != "image" {
10274        return Err(AdminError::Validation(
10275            "Crop applies to images only.".to_owned(),
10276        ));
10277    }
10278
10279    let bytes = crate::media_storage::disk_for(&tenant.org.slug)
10280        .load(&crate::media_storage::key(
10281            &tenant.org.slug,
10282            &media.storage_key,
10283        ))
10284        .await
10285        .map_err(|e| AdminError::Validation(format!("read source: {e}")))?;
10286    let (cropped_bytes, out_mime) = crate::rendition::crop_image_off_runtime(
10287        bytes,
10288        media.mime.clone(),
10289        (form.crop_x, form.crop_y, form.crop_w, form.crop_h),
10290    )
10291    .await
10292    .map_err(AdminError::Validation)?;
10293
10294    let new_hash = {
10295        use sha2::Digest;
10296        let mut hasher = sha2::Sha256::new();
10297        hasher.update(&cropped_bytes);
10298        let digest = hasher.finalize();
10299        let mut hex = String::with_capacity(digest.len() * 2);
10300        for b in digest.iter() {
10301            hex.push_str(&format!("{b:02x}"));
10302        }
10303        hex
10304    };
10305
10306    match form.mode.as_str() {
10307        "apply" => {
10308            // In-place: overwrite the same storage_key. The backend
10309            // writes the object wholesale (atomic PUT on S3), which
10310            // replaces the old tmp-file + rename dance.
10311            crate::media_storage::disk_for(&tenant.org.slug)
10312                .save(
10313                    &crate::media_storage::key(&tenant.org.slug, &media.storage_key),
10314                    &cropped_bytes,
10315                )
10316                .await
10317                .map_err(|e| AdminError::Validation(format!("write crop: {e}")))?;
10318            let old_hash = media.content_hash.clone();
10319            media.content_hash = new_hash;
10320            media.size = cropped_bytes.len() as i64;
10321            media.mime = out_mime;
10322            media.width = Some(form.crop_w as i32);
10323            media.height = Some(form.crop_h as i32);
10324            // Focal point in original coords no longer maps; clear.
10325            media.focal_point_x = None;
10326            media.focal_point_y = None;
10327            media.save(tenant.pool()).await?;
10328
10329            // Purge renditions for the OLD content_hash (the route
10330            // looks them up by hash + filter spec; bytes on disk
10331            // also need cleaning).
10332            let stale = crate::rendition::MediaRendition::objects()
10333                .where_(crate::rendition::MediaRendition::content_hash.eq(old_hash))
10334                .fetch(tenant.pool())
10335                .await?;
10336            purge_renditions(tenant.pool(), &tenant.org.slug, stale).await?;
10337            let crop_w = form.crop_w.to_string();
10338            let crop_h = form.crop_h.to_string();
10339            redirect_named_with_params_and_message_args(
10340                "rcms-admin:media:edit",
10341                &[("id", id.to_string())],
10342                MsgLevel::Success,
10343                "Crop applied. New dimensions {width}×{height}; renditions purged.",
10344                &[("width", crop_w.as_str()), ("height", crop_h.as_str())],
10345                &headers,
10346            )
10347        }
10348        "clone" => {
10349            // Save as new. Fresh storage_key under the source's
10350            // content-hash prefix so the on-disk bytes are
10351            // discoverable. Suffix the title with " — crop" so the
10352            // new row reads distinctly in lists.
10353            let ext = match out_mime.as_str() {
10354                "image/jpeg" => "jpg",
10355                "image/webp" => "webp",
10356                _ => "png",
10357            };
10358            let new_key = format!("{}-crop-{}.{ext}", &new_hash[..16.min(new_hash.len())], id);
10359            crate::media_storage::disk_for(&tenant.org.slug)
10360                .save(
10361                    &crate::media_storage::key(&tenant.org.slug, &new_key),
10362                    &cropped_bytes,
10363                )
10364                .await
10365                .map_err(|e| AdminError::Validation(format!("write clone: {e}")))?;
10366
10367            let clone_title = if media.title.contains(" — crop") {
10368                media.title.clone()
10369            } else {
10370                format!("{} — crop", media.title)
10371            };
10372            let mut clone = Media {
10373                id: Auto::Unset,
10374                filename: format!(
10375                    "{}.crop.{ext}",
10376                    std::path::Path::new(&media.filename)
10377                        .file_stem()
10378                        .map(|s| s.to_string_lossy().to_string())
10379                        .unwrap_or_else(|| "crop".to_owned())
10380                ),
10381                content_hash: new_hash,
10382                mime: out_mime,
10383                size: cropped_bytes.len() as i64,
10384                kind: "image".to_owned(),
10385                width: Some(form.crop_w as i32),
10386                height: Some(form.crop_h as i32),
10387                storage_key: new_key,
10388                title: clone_title,
10389                alt_text: media.alt_text.clone(),
10390                description: media.description.clone(),
10391                uploaded_by: media.uploaded_by,
10392                collection_id: media.collection_id,
10393                focal_point_x: None,
10394                focal_point_y: None,
10395                uploaded_at: Auto::Unset,
10396            };
10397            clone.insert(tenant.pool()).await?;
10398            let new_id = clone.id.get().copied().unwrap_or_default();
10399            let new_id_str = new_id.to_string();
10400            let crop_w = form.crop_w.to_string();
10401            let crop_h = form.crop_h.to_string();
10402            redirect_named_with_params_and_message_args(
10403                "rcms-admin:media:edit",
10404                &[("id", new_id.to_string())],
10405                MsgLevel::Success,
10406                "Saved cropped clone as new media #{id} ({width}×{height}).",
10407                &[
10408                    ("id", new_id_str.as_str()),
10409                    ("width", crop_w.as_str()),
10410                    ("height", crop_h.as_str()),
10411                ],
10412                &headers,
10413            )
10414        }
10415        other => Err(AdminError::Validation(format!(
10416            "Unknown crop mode `{other}` — expected `apply` or `clone`."
10417        ))),
10418    }
10419}
10420
10421// =====================================================================
10422// Image replace (#190)
10423// =====================================================================
10424
10425/// POST /cms-admin/media/{id}/replace — re-upload bytes for an existing
10426/// media row. Keeps the row id (so every page that references it stays
10427/// linked) and the editorial metadata (title, alt_text). Updates the
10428/// physical fields: storage_key, content_hash, mime, size, width,
10429/// height, filename. Focal point survives unless the new dimensions
10430/// require it to be clamped — it's stored as a 0..1 fraction so it
10431/// already scales across resizes.
10432///
10433/// Old on-disk bytes are best-effort deleted; every cached rendition
10434/// for the old content_hash is purged so subsequent requests
10435/// regenerate from the replacement.
10436pub async fn media_replace_submit(
10437    State(_state): State<super::AdminState>,
10438    tenant: Tenant,
10439    headers: HeaderMap,
10440    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
10441    Path(id): Path<i64>,
10442    mut multipart: axum::extract::Multipart,
10443) -> Result<Response, AdminError> {
10444    use sha2::{Digest, Sha256};
10445
10446    let mut media = Media::objects()
10447        .where_(Media::id.eq(id))
10448        .first(tenant.pool())
10449        .await?
10450        .ok_or(AdminError::NotFound(id))?;
10451
10452    let mut filename = String::new();
10453    let mut bytes: Vec<u8> = Vec::new();
10454    while let Some(field) = multipart
10455        .next_field()
10456        .await
10457        .map_err(|e| AdminError::Upload(format!("multipart parse: {e}")))?
10458    {
10459        if field.name().unwrap_or("") == "file" {
10460            if let Some(fname) = field.file_name() {
10461                filename = sanitize_filename(fname);
10462            }
10463            bytes = field
10464                .bytes()
10465                .await
10466                .map_err(|e| AdminError::Upload(format!("read bytes: {e}")))?
10467                .to_vec();
10468        } else {
10469            let _ = field.bytes().await;
10470        }
10471    }
10472    if filename.is_empty() || bytes.is_empty() {
10473        return Err(AdminError::Upload("no file submitted".into()));
10474    }
10475
10476    let new_mime = mime_guess::from_path(&filename)
10477        .first_or_octet_stream()
10478        .essence_str()
10479        .to_owned();
10480    refuse_active_upload(&new_mime)?;
10481    // Replacing an image with a non-image (or vice versa) would
10482    // silently break every consumer that branches on `kind`.
10483    let new_kind = Media::classify_mime(&new_mime).to_owned();
10484    if new_kind != media.kind {
10485        return Err(AdminError::Validation(format!(
10486            "Replacement kind `{new_kind}` does not match existing `{}` — replace must keep the media type.",
10487            media.kind
10488        )));
10489    }
10490
10491    // EXIF strip + decode for dimensions, same as the upload path.
10492    let (stored, decoded_dims) =
10493        crate::rendition::strip_exif_off_runtime(bytes, new_mime.clone()).await;
10494    bytes = stored;
10495
10496    let mut hasher = Sha256::new();
10497    hasher.update(&bytes);
10498    let digest = hasher.finalize();
10499    let new_hash = digest.iter().fold(String::with_capacity(64), |mut acc, b| {
10500        use std::fmt::Write as _;
10501        let _ = write!(acc, "{b:02x}");
10502        acc
10503    });
10504
10505    let new_storage_key = format!("{}-{}", &new_hash[..16.min(new_hash.len())], filename);
10506    crate::media_storage::disk_for(&tenant.org.slug)
10507        .save(
10508            &crate::media_storage::key(&tenant.org.slug, &new_storage_key),
10509            &bytes,
10510        )
10511        .await
10512        .map_err(|e| AdminError::Upload(format!("write: {e}")))?;
10513
10514    let old_storage_key = media.storage_key.clone();
10515    let old_hash = media.content_hash.clone();
10516
10517    let (new_w, new_h): (Option<i32>, Option<i32>) = decoded_dims
10518        .map(|(w, h)| (Some(w as i32), Some(h as i32)))
10519        .unwrap_or((None, None));
10520
10521    media.filename = filename;
10522    media.storage_key = new_storage_key;
10523    media.content_hash = new_hash;
10524    media.mime = new_mime;
10525    media.size = bytes.len() as i64;
10526    media.width = new_w;
10527    media.height = new_h;
10528    media.save(tenant.pool()).await?;
10529
10530    // Best-effort cleanup of the old file on disk. Only remove when
10531    // the storage_key actually changed — content-addressed naming
10532    // means an identical replacement reuses the same path.
10533    if old_storage_key != media.storage_key {
10534        crate::media_storage::disk_for(&tenant.org.slug)
10535            .delete(&crate::media_storage::key(
10536                &tenant.org.slug,
10537                &old_storage_key,
10538            ))
10539            .await
10540            .log_warn("stored file not deleted; the blob is orphaned");
10541    }
10542
10543    // Purge renditions for the old content_hash so the next request
10544    // regenerates from the replacement bytes.
10545    if old_hash != media.content_hash {
10546        let stale = crate::rendition::MediaRendition::objects()
10547            .where_(crate::rendition::MediaRendition::content_hash.eq(old_hash))
10548            .fetch(tenant.pool())
10549            .await?;
10550        purge_renditions(tenant.pool(), &tenant.org.slug, stale).await?;
10551    }
10552
10553    redirect_named_with_params_and_message(
10554        "rcms-admin:media:edit",
10555        &[("id", id.to_string())],
10556        MsgLevel::Success,
10557        "Replaced. Old renditions purged; every page referencing this image now serves the new bytes.",
10558        &headers,
10559    )
10560}
10561
10562// =====================================================================
10563// Image focal point (#4)
10564// =====================================================================
10565
10566/// GET /cms-admin/media/{id}/edit — image detail page with the
10567/// focal-point picker and where the image is used. Image-only; other
10568/// kinds return 404.
10569pub async fn media_edit_form(
10570    State(state): State<super::AdminState>,
10571    tenant: Tenant,
10572    headers: HeaderMap,
10573    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
10574    Path(id): Path<i64>,
10575) -> Result<Response, AdminError> {
10576    let media = Media::objects()
10577        .where_(Media::id.eq(id))
10578        .first(tenant.pool())
10579        .await?
10580        .ok_or(AdminError::NotFound(id))?;
10581    if media.kind != "image" {
10582        return Err(AdminError::NotFound(id));
10583    }
10584    // #100 — per-image usage report.
10585    // Pages, library elements and settings that use this picture.
10586    let usage_rows: Vec<serde_json::Value> = crate::media_usage::uses_of(tenant.pool(), id)
10587        .await
10588        .unwrap_or_default()
10589        .into_iter()
10590        .map(|u| match u {
10591            crate::media_usage::Use::Page { id, title, url_path, status } => serde_json::json!({
10592                "kind": "page", "title": title, "where": url_path, "status": status,
10593                "href": format!("/cms-admin/pages/{id}/edit"),
10594            }),
10595            crate::media_usage::Use::Library { id, title } => serde_json::json!({
10596                "kind": "library", "title": title, "where": "Library",
10597                "href": format!("/cms-admin/library/{id}/edit"),
10598            }),
10599            crate::media_usage::Use::Setting { scope } => {
10600                let branding = scope == crate::branding::SCOPE;
10601                serde_json::json!({
10602                    "kind": "setting",
10603                    "title": if branding { "Branding".to_owned() } else { scope.clone() },
10604                    "where": if branding { "Settings" } else { "Site settings" },
10605                    "href": if branding { "/cms-admin/settings".to_owned() } else { format!("/cms-admin/site-settings/{scope}/edit") },
10606                })
10607            }
10608        })
10609        .collect();
10610    let mut ctx = Context::new();
10611    add_chrome(&mut ctx, &tenant, "media", session_user.as_ref()).await;
10612    add_admin_theme(&mut ctx, tenant.pool()).await;
10613    ctx.insert(
10614        "media",
10615        &serde_json::json!({
10616            "id": media.id.get().copied(),
10617            "title": media.title,
10618            "filename": media.filename,
10619            "alt_text": media.alt_text,
10620            "description": media.description,
10621            "mime": media.mime,
10622            "size": media.size,
10623            "width": media.width,
10624            "height": media.height,
10625            "focal_point_x": media.focal_point_x,
10626            "focal_point_y": media.focal_point_y,
10627            "uploaded_at": media.uploaded_at.get().copied(),
10628            // Cache-buster for the `rcms_image_url(..., v=media.content_hash)`
10629            // call in the template — without this the focal-point
10630            // preview never picks up an in-place re-crop.
10631            "content_hash": media.content_hash,
10632        }),
10633    );
10634    ctx.insert("usages", &usage_rows);
10635    ctx.insert("usage_count", &(usage_rows.len() as i64));
10636    render_with_csrf(&state, &headers, "rcms_admin/media_edit.html", &mut ctx)
10637}
10638
10639/// Form payload for the focal-point editor. All four fields
10640/// arrive as strings from the HTML form; we parse + validate
10641/// server-side. A submission with empty x/y clears the focal point.
10642#[derive(Debug, Deserialize)]
10643pub struct MediaEditForm {
10644    pub title: String,
10645    pub alt_text: String,
10646    #[serde(default)]
10647    pub description: String,
10648    #[serde(default)]
10649    pub focal_point_x: Option<String>,
10650    #[serde(default)]
10651    pub focal_point_y: Option<String>,
10652}
10653
10654/// POST /cms-admin/media/{id}/edit — save title / alt + focal point.
10655/// When the focal point changes, every cached rendition for this
10656/// media row is purged so subsequent requests regenerate around the
10657/// new center.
10658pub async fn media_edit_submit(
10659    State(_state): State<super::AdminState>,
10660    tenant: Tenant,
10661    headers: HeaderMap,
10662    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
10663    Path(id): Path<i64>,
10664    Form(form): Form<MediaEditForm>,
10665) -> Result<Response, AdminError> {
10666    let mut media = Media::objects()
10667        .where_(Media::id.eq(id))
10668        .first(tenant.pool())
10669        .await?
10670        .ok_or(AdminError::NotFound(id))?;
10671    if media.kind != "image" {
10672        return Err(AdminError::NotFound(id));
10673    }
10674    media.title = form.title.trim().to_owned();
10675    media.alt_text = form.alt_text.trim().to_owned();
10676    media.description = form.description.trim().to_owned();
10677
10678    let parse_fraction = |raw: Option<&str>| -> Option<f32> {
10679        raw.map(str::trim)
10680            .filter(|s| !s.is_empty())
10681            .and_then(|s| s.parse::<f32>().ok())
10682            .map(|f| f.clamp(0.0, 1.0))
10683    };
10684    let new_x = parse_fraction(form.focal_point_x.as_deref());
10685    let new_y = parse_fraction(form.focal_point_y.as_deref());
10686    let focal_changed = media.focal_point_x != new_x || media.focal_point_y != new_y;
10687    media.focal_point_x = new_x;
10688    media.focal_point_y = new_y;
10689    media.save(tenant.pool()).await?;
10690
10691    // Invalidate rendition cache rows + delete their on-disk bytes
10692    // so subsequent requests regenerate with the new focal point.
10693    if focal_changed {
10694        let renditions: Vec<crate::rendition::MediaRendition> =
10695            crate::rendition::MediaRendition::objects()
10696                .where_(
10697                    crate::rendition::MediaRendition::content_hash.eq(media.content_hash.clone()),
10698                )
10699                .fetch(tenant.pool())
10700                .await?;
10701        for r in renditions {
10702            // Best-effort delete of the on-disk bytes; the DB row
10703            // delete is what counts (next render miss regenerates).
10704            crate::media_storage::disk_for(&tenant.org.slug)
10705                .delete(&crate::media_storage::key(&tenant.org.slug, &r.storage_key))
10706                .await
10707                .log_warn("stored file not deleted; the blob is orphaned");
10708            r.delete(tenant.pool()).await?;
10709        }
10710    }
10711    redirect_named_with_params_and_message(
10712        "rcms-admin:media:edit",
10713        &[("id", id.to_string())],
10714        MsgLevel::Success,
10715        if focal_changed {
10716            "Saved. Renditions purged — next request regenerates with the new focal point."
10717        } else {
10718            "Saved."
10719        },
10720        &headers,
10721    )
10722}
10723
10724/// Recursively scan a JSON value for any string that contains
10725/// `needle` (already lowercased). Used by admin search to
10726/// broaden recall into page-type extension fields without listing
10727/// every key on the handler trait.
10728fn json_contains_needle(value: &serde_json::Value, needle: &str) -> bool {
10729    match value {
10730        serde_json::Value::String(s) => {
10731            if s.to_lowercase().contains(needle) {
10732                return true;
10733            }
10734            // Stream-block extension columns sometimes hold a JSON
10735            // array as a string — peek through if it looks like one.
10736            let trimmed = s.trim_start();
10737            if trimmed.starts_with('[') || trimmed.starts_with('{') {
10738                if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(s) {
10739                    return json_contains_needle(&parsed, needle);
10740                }
10741            }
10742            false
10743        }
10744        serde_json::Value::Array(arr) => arr.iter().any(|v| json_contains_needle(v, needle)),
10745        serde_json::Value::Object(map) => map.values().any(|v| json_contains_needle(v, needle)),
10746        _ => false,
10747    }
10748}
10749
10750
10751/// GET /cms-admin/media/unused — list `cms_media` rows that no page
10752/// references. Builds a reverse index by walking every page's
10753/// extension JSON for `media_id` keys, then diffs against the full
10754/// media table. Used by editors to garbage-collect stale uploads.
10755pub async fn media_unused_report(
10756    State(state): State<super::AdminState>,
10757    tenant: Tenant,
10758    headers: HeaderMap,
10759    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
10760) -> Result<Response, AdminError> {
10761    let all_media: Vec<Media> = Media::objects()
10762        .order_by(&[("uploaded_at", true)])
10763        .fetch(tenant.pool())
10764        .await?;
10765    // In use anywhere: pages (code extensions and page-builder data,
10766    // blocks included), library elements, site settings.
10767    let used = crate::media_usage::used(tenant.pool()).await?;
10768
10769    // Media rows whose id isn't in use are unused.
10770    let unused: Vec<&Media> = all_media
10771        .iter()
10772        .filter(|m| m.id.get().copied().is_some_and(|id| !used.contains(&id)))
10773        .collect();
10774
10775    let unused_view: Vec<serde_json::Value> = unused
10776        .iter()
10777        .map(|m| {
10778            serde_json::json!({
10779                "id": m.id.get().copied(),
10780                "title": m.title,
10781                "filename": m.filename,
10782                "kind": m.kind,
10783                "mime": m.mime,
10784                "size": m.size,
10785                "uploaded_at": m.uploaded_at.get().copied(),
10786                "uploaded_by": m.uploaded_by,
10787            })
10788        })
10789        .collect();
10790
10791    let mut ctx = Context::new();
10792    add_chrome(&mut ctx, &tenant, "media-unused", session_user.as_ref()).await;
10793    add_admin_theme(&mut ctx, tenant.pool()).await;
10794    ctx.insert("unused", &unused_view);
10795    ctx.insert("total_media", &all_media.len());
10796    ctx.insert("used_count", &used.len());
10797    render_with_csrf(&state, &headers, "rcms_admin/media_unused.html", &mut ctx)
10798}
10799
10800/// POST /cms-admin/media/unused/delete — bulk-delete the chosen
10801/// media rows. Receives a list of `id=N` form fields and deletes
10802/// each in sequence. The handler does NOT re-verify "unused" status
10803/// — that's the editor's job — but it stays well-behaved because
10804/// the form template only renders rows that ARE currently unused.
10805pub async fn media_unused_bulk_delete(
10806    State(_state): State<super::AdminState>,
10807    tenant: Tenant,
10808    headers: HeaderMap,
10809    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
10810    Form(form): Form<Vec<(String, String)>>,
10811) -> Result<Response, AdminError> {
10812    let ids: Vec<i64> = form
10813        .iter()
10814        .filter(|(k, _)| k == "id" || k == "ids")
10815        .filter_map(|(_, v)| v.parse::<i64>().ok())
10816        .collect();
10817    // The selected rows in one read per chunk (#631); each delete still
10818    // runs on its own, since it also removes the files and renditions.
10819    let mut deleted = 0usize;
10820    for chunk in ids.chunks(500) {
10821        let rows: Vec<Media> = Media::objects()
10822            .where_(Media::id.is_in(chunk.to_vec()))
10823            .fetch(tenant.pool())
10824            .await?;
10825        for m in rows {
10826            delete_media(tenant.pool(), &tenant.org.slug, m).await?;
10827            deleted += 1;
10828        }
10829    }
10830    redirect_named_with_message_plural(
10831        "rcms-admin:media:unused",
10832        MsgLevel::Success,
10833        "Deleted {count} unused media item(s).",
10834        deleted as i64,
10835        &[("count", &deleted.to_string())],
10836        &headers,
10837    )
10838}
10839
10840/// GET /cms-admin/media — list `cms_media` rows where `kind = 'image'`.
10841pub async fn media_list(
10842    State(state): State<super::AdminState>,
10843    tenant: Tenant,
10844    headers: HeaderMap,
10845    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
10846    Query(q): Query<MediaListQuery>,
10847    axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
10848) -> Result<Response, AdminError> {
10849    // #142 — opportunistic scratch-upload sweep. Roughly 2% of
10850    // media-list visits trigger a stale-row GC so dead scratch uploads
10851    // don't accumulate. Best-effort: file unlink errors log + continue.
10852    if rand::random::<u8>() < 5 {
10853        if let Ok(unlinked) = crate::uploaded_file::gc_stale(tenant.pool()).await {
10854            for key in unlinked {
10855                crate::media_storage::disk_for(&tenant.org.slug)
10856                    .delete(&crate::media_storage::key(&tenant.org.slug, &key))
10857                    .await
10858                    .log_warn("stored file not deleted; the blob is orphaned");
10859            }
10860        }
10861    }
10862    render_media_list(
10863        &state,
10864        &tenant,
10865        &headers,
10866        session_user.as_ref(),
10867        "image",
10868        q,
10869        raw_query,
10870    )
10871    .await
10872}
10873
10874/// GET /cms-admin/documents — same view filtered to non-image kinds.
10875pub async fn documents_list(
10876    State(state): State<super::AdminState>,
10877    tenant: Tenant,
10878    headers: HeaderMap,
10879    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
10880    Query(q): Query<MediaListQuery>,
10881    axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
10882) -> Result<Response, AdminError> {
10883    render_media_list(
10884        &state,
10885        &tenant,
10886        &headers,
10887        session_user.as_ref(),
10888        "document",
10889        q,
10890        raw_query,
10891    )
10892    .await
10893}
10894
10895/// Shared list renderer for the image / document views. `kind` is
10896/// the discriminator on `cms_media.kind` ("image" / "document").
10897async fn render_media_list(
10898    state: &super::AdminState,
10899    tenant: &Tenant,
10900    headers: &HeaderMap,
10901    session_user: Option<&rustango::tenancy::auth::User>,
10902    kind: &str,
10903    filters: MediaListQuery,
10904    raw_query: Option<String>,
10905) -> Result<Response, AdminError> {
10906    let collection_filter = filters.collection;
10907    let search = filters
10908        .q
10909        .as_deref()
10910        .map(str::trim)
10911        .filter(|s| !s.is_empty())
10912        .map(str::to_lowercase);
10913    let from_filter = parse_date_floor(filters.from.as_deref());
10914    let to_filter = parse_date_ceil(filters.to.as_deref());
10915    // Filtered, counted and paged in SQL (#632): the library used to be
10916    // loaded whole and filtered in Rust. `icontains` is case-insensitive
10917    // on every backend, which a bare LIKE is not.
10918    let pool = tenant.pool();
10919    let in_kind = || {
10920        let qs = Media::objects();
10921        if kind == "image" {
10922            qs.where_(Media::kind.eq("image".to_owned()))
10923        } else {
10924            qs.where_(Media::kind.ne("image".to_owned()))
10925        }
10926    };
10927    let listed = || {
10928        let mut qs = in_kind();
10929        if let Some(cid) = collection_filter {
10930            qs = qs.where_(Media::collection_id.eq(cid));
10931        }
10932        if let Some(needle) = &search {
10933            qs = qs.where_(
10934                Media::title
10935                    .icontains(needle)
10936                    .or(Media::filename.icontains(needle))
10937                    .or(Media::alt_text.icontains(needle)),
10938            );
10939        }
10940        if let Some(floor) = from_filter {
10941            qs = qs.where_(Media::uploaded_at.gte(floor));
10942        }
10943        if let Some(ceil) = to_filter {
10944            qs = qs.where_(Media::uploaded_at.lte(ceil));
10945        }
10946        qs
10947    };
10948    let collections: Vec<crate::media::MediaCollection> = crate::media::MediaCollection::objects()
10949        .order_by(&[("sort_order", false), ("name", false)])
10950        .fetch(pool)
10951        .await?;
10952
10953    let per_page = crate::admin::pagination::clamp_per_page(filters.per_page);
10954    let total_items = usize::try_from(listed().count(pool).await?).unwrap_or_default();
10955    let pagination = crate::admin::pagination::context(filters.page.unwrap_or(1), per_page, total_items);
10956    let current_page = pagination["page"].as_i64().unwrap_or(1);
10957    let items: Vec<Media> = listed()
10958        .order_by(&[("uploaded_at", true), ("id", true)])
10959        .limit(per_page as i64)
10960        .offset(crate::admin::pagination::offset(current_page, per_page))
10961        .fetch(pool)
10962        .await?;
10963
10964    // "(N)" beside each collection in the sidebar, for the current kind
10965    // only so the badges match the view: one grouped count.
10966    let grouped = in_kind()
10967        .values(&["collection_id"])
10968        .annotate("n", rustango::core::aggregates::count_all().into())
10969        .compile()
10970        .map_err(rustango::sql::ExecError::from)?;
10971    let counts: std::collections::HashMap<Option<i64>, i64> = rustango::sql::fetch_aggregate_dict(pool, &grouped)
10972        .await?
10973        .into_iter()
10974        .filter_map(|r| Some((sql_i64(r.get("collection_id")), sql_i64(r.get("n"))?)))
10975        .collect();
10976
10977    let collections_view: Vec<serde_json::Value> = collections
10978        .iter()
10979        .map(|c| {
10980            let id = c.id.get().copied();
10981            serde_json::json!({
10982                "id": id,
10983                "name": c.name,
10984                "parent_id": c.parent_id,
10985                "count": id.and_then(|i| counts.get(&Some(i)).copied()).unwrap_or(0),
10986            })
10987        })
10988        .collect();
10989    let uncategorized_count = counts.get(&None).copied().unwrap_or(0);
10990
10991    let mut ctx = Context::new();
10992    let active_tab = if kind == "image" {
10993        "media"
10994    } else {
10995        "documents"
10996    };
10997    add_chrome(&mut ctx, tenant, active_tab, session_user).await;
10998    add_admin_theme(&mut ctx, tenant.pool()).await;
10999    ctx.insert("items", &items);
11000    ctx.insert("collections", &collections_view);
11001    ctx.insert("collection_filter", &collection_filter);
11002    ctx.insert("uncategorized_count", &uncategorized_count);
11003    ctx.insert("search_q", &filters.q);
11004    ctx.insert("date_from", &filters.from);
11005    ctx.insert("date_to", &filters.to);
11006    ctx.insert(
11007        "is_filtered",
11008        &(collection_filter.is_some()
11009            || search.is_some()
11010            || from_filter.is_some()
11011            || to_filter.is_some()),
11012    );
11013    // The full match count, not the size of the visible page.
11014    ctx.insert("filtered_count", &total_items);
11015    ctx.insert("pagination", &pagination);
11016    ctx.insert(
11017        "kind_label",
11018        if kind == "image" {
11019            "Media (images)"
11020        } else {
11021            "Documents"
11022        },
11023    );
11024    ctx.insert(
11025        "upload_kind",
11026        if kind == "image" { "image" } else { "document" },
11027    );
11028    ctx.insert(
11029        "self_url",
11030        if kind == "image" {
11031            "/cms-admin/media"
11032        } else {
11033            "/cms-admin/documents"
11034        },
11035    );
11036    // #316 — raw query string for the `| querystring(collection=…)` rail
11037    // links: they preserve the q / from / to filters and just set or
11038    // clear `collection` (media has no page param). `qs_none` is a null
11039    // sentinel — Tera has no `null` literal, so `querystring(k=qs_none)`
11040    // is how the template drops a key.
11041    ctx.insert("query_string", &raw_query.unwrap_or_default());
11042    ctx.insert("qs_none", &serde_json::Value::Null);
11043    render_with_csrf(state, headers, "rcms_admin/media_list.html", &mut ctx)
11044}
11045
11046/// GET /cms-admin/media/upload — upload form.
11047pub async fn media_upload_form(
11048    State(state): State<super::AdminState>,
11049    tenant: Tenant,
11050    headers: HeaderMap,
11051    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
11052    Query(q): Query<UploadFormQuery>,
11053) -> Result<Response, AdminError> {
11054    let kind_label = if q.kind.as_deref() == Some("document") {
11055        "Documents"
11056    } else {
11057        "Media (images)"
11058    };
11059    let mut ctx = Context::new();
11060    add_chrome(
11061        &mut ctx,
11062        &tenant,
11063        if q.kind.as_deref() == Some("document") {
11064            "documents"
11065        } else {
11066            "media"
11067        },
11068        session_user.as_ref(),
11069    )
11070    .await;
11071    // Collections picker (#188) — pass into ctx so each queue row
11072    // can render a per-file dropdown without a follow-up fetch.
11073    let collections: Vec<crate::media::MediaCollection> = crate::media::MediaCollection::objects()
11074        .order_by(&[("sort_order", false), ("name", false)])
11075        .fetch(tenant.pool())
11076        .await?;
11077    let collections_view: Vec<serde_json::Value> = collections
11078        .iter()
11079        .map(|c| {
11080            serde_json::json!({
11081                "id": c.id.get().copied(),
11082                "name": c.name,
11083            })
11084        })
11085        .collect();
11086    ctx.insert("collections", &collections_view);
11087    ctx.insert("kind_label", kind_label);
11088    ctx.insert("upload_kind", &q.kind.as_deref().unwrap_or("image"));
11089    render_with_csrf(&state, &headers, "rcms_admin/media_upload.html", &mut ctx)
11090}
11091
11092#[derive(Debug, Deserialize)]
11093pub struct UploadFormQuery {
11094    #[serde(default)]
11095    pub kind: Option<String>,
11096}
11097
11098/// POST /cms-admin/media/upload — accept a multipart upload, hash
11099/// the bytes, drop them through the tenant `Storage` backend, and
11100/// stamp a `cms_media` row.
11101/// POST /cms-admin/media/upload-staged — write bytes to scratch
11102/// storage + return JSON `{id, filename, mime, size}`.
11103/// Returned `id` is the [`crate::uploaded_file::UploadedFile`]
11104/// row to commit / cancel later.
11105///
11106/// Coexists with the existing single-step `media_upload_submit` — that
11107/// path keeps working unchanged. Use this endpoint for future
11108/// drag-drop / multi-file UIs where bytes need to land before
11109/// metadata is collected.
11110pub async fn media_upload_staged(
11111    State(_state): State<super::AdminState>,
11112    tenant: Tenant,
11113    headers: HeaderMap,
11114    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
11115    mut multipart: axum::extract::Multipart,
11116) -> Result<Response, AdminError> {
11117    use sha2::{Digest, Sha256};
11118    let Some(viewer) = session_user.as_ref() else {
11119        // #285 — XHR/fetch clients (the multi-file upload UI) used to
11120        // get the raw HTML page injected into a toast on session
11121        // expiry. Pass the request headers so the responder returns
11122        // JSON when the client sent `Accept: application/json` or
11123        // `X-Requested-With: XMLHttpRequest`.
11124        return Ok(unauthorized_no_session_for(Some(&headers)));
11125    };
11126    let viewer_id = viewer.id.get().copied().unwrap_or_default();
11127    let mut filename = String::new();
11128    let mut bytes: Vec<u8> = Vec::new();
11129    while let Some(field) = multipart
11130        .next_field()
11131        .await
11132        .map_err(|e| AdminError::Upload(format!("multipart parse: {e}")))?
11133    {
11134        if field.name().unwrap_or("") == "file" {
11135            if let Some(fname) = field.file_name() {
11136                filename = sanitize_filename(fname);
11137            }
11138            bytes = field
11139                .bytes()
11140                .await
11141                .map_err(|e| AdminError::Upload(format!("read bytes: {e}")))?
11142                .to_vec();
11143        } else {
11144            let _ = field.bytes().await;
11145        }
11146    }
11147    if filename.is_empty() || bytes.is_empty() {
11148        return Err(AdminError::Upload("no file submitted".into()));
11149    }
11150    let mut hasher = Sha256::new();
11151    hasher.update(&bytes);
11152    let digest = hasher.finalize();
11153    let hash = digest.iter().fold(String::with_capacity(64), |mut acc, b| {
11154        use std::fmt::Write as _;
11155        let _ = write!(acc, "{b:02x}");
11156        acc
11157    });
11158    let mime = mime_guess::from_path(&filename)
11159        .first_or_octet_stream()
11160        .essence_str()
11161        .to_owned();
11162    refuse_active_upload(&mime)?;
11163    // #284 — dedup by content hash. If this tenant already has a
11164    // cms_media row whose `content_hash` matches the bytes the
11165    // editor just uploaded, skip writing to scratch + creating a
11166    // new UploadedFile row. The client treats the response as a
11167    // "skipped" outcome and surfaces it as a toast linking back to
11168    // the existing media row. Per-tenant query — the
11169    // `tenant.pool()` is the tenant-scoped pool, so a hash that
11170    // collides across tenants doesn't dedup across the boundary.
11171    {
11172        use rustango::core::Column as _;
11173        use rustango::sql::FetcherPool as _;
11174        let existing: Vec<crate::media::Media> = crate::media::Media::objects()
11175            .where_(crate::media::Media::content_hash.eq(hash.clone()))
11176            .fetch(tenant.pool())
11177            .await
11178            .unwrap_or_default();
11179        if let Some(existing_media) = existing.into_iter().next() {
11180            let existing_id = existing_media.id.get().copied().unwrap_or_default();
11181            let payload = serde_json::json!({
11182                "id": null,
11183                "duplicate_of": existing_id,
11184                "duplicate_title": existing_media.title,
11185                "duplicate_filename": existing_media.filename,
11186                "filename": filename,
11187                "mime": existing_media.mime,
11188                "size": existing_media.size,
11189            });
11190            return Ok((
11191                [(axum::http::header::CONTENT_TYPE, "application/json")],
11192                serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_owned()),
11193            )
11194                .into_response());
11195        }
11196    }
11197    let storage_key = format!("scratch/{}-{filename}", &hash[..16]);
11198    crate::media_storage::disk_for(&tenant.org.slug)
11199        .save(
11200            &crate::media_storage::key(&tenant.org.slug, &storage_key),
11201            &bytes,
11202        )
11203        .await
11204        .map_err(|e| AdminError::Upload(format!("write: {e}")))?;
11205    let size = bytes.len() as i64;
11206    let row = crate::uploaded_file::create(
11207        tenant.pool(),
11208        viewer_id,
11209        storage_key,
11210        filename,
11211        mime,
11212        size,
11213        hash,
11214    )
11215    .await?;
11216    let payload = serde_json::json!({
11217        "id": row.id.get().copied().unwrap_or_default(),
11218        "filename": row.original_filename,
11219        "mime": row.mime,
11220        "size": row.size,
11221    });
11222    Ok((
11223        [(axum::http::header::CONTENT_TYPE, "application/json")],
11224        serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_owned()),
11225    )
11226        .into_response())
11227}
11228
11229/// One entry in the [`StagedCommitPayload`] commit grid.
11230#[derive(Debug, Deserialize)]
11231pub struct StagedCommitItem {
11232    pub uploaded_file_id: i64,
11233    #[serde(default)]
11234    pub title: String,
11235    #[serde(default)]
11236    pub alt_text: String,
11237    #[serde(default)]
11238    pub collection_id: Option<i64>,
11239}
11240
11241/// Body of `POST /cms-admin/media/upload-staged/commit`. The
11242/// editor uploaded N files into scratch storage; now this payload
11243/// names each scratch row + its editorial metadata in one
11244/// transaction-equivalent call.
11245#[derive(Debug, Deserialize)]
11246pub struct StagedCommitPayload {
11247    pub items: Vec<StagedCommitItem>,
11248}
11249
11250/// POST /cms-admin/media/upload-staged/commit — promote staged rows
11251/// to `cms_media` with per-file metadata. Each item:
11252///
11253/// 1. Loads the scratch row.
11254/// 2. Re-reads bytes from the scratch path; EXIF-strips images.
11255/// 3. Moves the file out of `scratch/` to the canonical
11256///    `<hash>-<filename>` storage_key.
11257/// 4. Inserts a `cms_media` row.
11258/// 5. Deletes the scratch DB row + (best-effort) the scratch file.
11259///
11260/// On a per-item failure, that scratch row is left in place so the
11261/// editor can retry; successful items still commit. The response is
11262/// JSON `{ committed: [media_id...], failed: [{id, error}...] }`.
11263pub async fn media_upload_staged_commit(
11264    State(_state): State<super::AdminState>,
11265    tenant: Tenant,
11266    headers: HeaderMap,
11267    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
11268    Json(payload): Json<StagedCommitPayload>,
11269) -> Result<Response, AdminError> {
11270    use rustango::sql::Auto;
11271    let Some(viewer) = session_user.as_ref() else {
11272        // #285 — JSON-aware 401 for fetch clients.
11273        return Ok(unauthorized_no_session_for(Some(&headers)));
11274    };
11275    let viewer_id = viewer.id.get().copied().unwrap_or_default();
11276    let media_slug = tenant.org.slug.clone();
11277
11278    let mut committed: Vec<i64> = Vec::new();
11279    let mut failed: Vec<serde_json::Value> = Vec::new();
11280
11281    for item in payload.items {
11282        let result: Result<i64, String> = async {
11283            let row = crate::uploaded_file::get(tenant.pool(), item.uploaded_file_id)
11284                .await
11285                .map_err(|e| format!("lookup: {e}"))?
11286                .ok_or_else(|| "scratch row missing".to_owned())?;
11287            if row.user_id != viewer_id && !viewer.is_superuser {
11288                return Err("not your upload".to_owned());
11289            }
11290
11291            let scratch_key = crate::media_storage::key(&media_slug, &row.storage_key);
11292            let mut bytes = crate::media_storage::disk_for(&media_slug)
11293                .load(&scratch_key)
11294                .await
11295                .map_err(|e| format!("read scratch: {e}"))?;
11296
11297            // EXIF-strip + decode for pixel dims. Mirrors upload path.
11298            let (stored, decoded_dims) =
11299                crate::rendition::strip_exif_off_runtime(bytes, row.mime.clone()).await;
11300            bytes = stored;
11301
11302            // Canonical storage_key under the tenant's media dir —
11303            // content-addressed prefix so renditions can find bytes
11304            // by hash without hitting the DB.
11305            let final_key = format!(
11306                "{}-{}",
11307                &row.content_hash[..16.min(row.content_hash.len())],
11308                row.original_filename
11309            );
11310            crate::media_storage::disk_for(&media_slug)
11311                .save(&crate::media_storage::key(&media_slug, &final_key), &bytes)
11312                .await
11313                .map_err(|e| format!("write final: {e}"))?;
11314
11315            let kind = Media::classify_mime(&row.mime).to_owned();
11316            let (width, height): (Option<i32>, Option<i32>) = decoded_dims
11317                .map(|(w, h)| (Some(w as i32), Some(h as i32)))
11318                .unwrap_or((None, None));
11319
11320            let title = if item.title.trim().is_empty() {
11321                row.original_filename
11322                    .rsplit_once('.')
11323                    .map(|(stem, _)| stem.to_owned())
11324                    .unwrap_or_else(|| row.original_filename.clone())
11325            } else {
11326                item.title.trim().to_owned()
11327            };
11328
11329            let mut media_row = Media {
11330                id: Auto::Unset,
11331                filename: row.original_filename.clone(),
11332                content_hash: row.content_hash.clone(),
11333                mime: row.mime.clone(),
11334                size: bytes.len() as i64,
11335                kind,
11336                width,
11337                height,
11338                storage_key: final_key,
11339                title,
11340                alt_text: item.alt_text.trim().to_owned(),
11341                description: String::new(),
11342                uploaded_by: Some(viewer_id),
11343                collection_id: item.collection_id,
11344                focal_point_x: None,
11345                focal_point_y: None,
11346                uploaded_at: Auto::Unset,
11347            };
11348            media_row
11349                .insert(tenant.pool())
11350                .await
11351                .map_err(|e| format!("insert media: {e}"))?;
11352            let new_id = media_row.id.get().copied().unwrap_or_default();
11353
11354            // Best-effort scratch cleanup. Scratch file is a separate
11355            // path from the final storage_key (final lives outside
11356            // `scratch/`), so removing it is safe even when the bytes
11357            // are byte-identical.
11358            crate::media_storage::disk_for(&media_slug)
11359                .delete(&scratch_key)
11360                .await
11361                .log_warn("stored file not deleted; the blob is orphaned");
11362            crate::uploaded_file::delete(tenant.pool(), item.uploaded_file_id)
11363                .await
11364                .map_err(|e| format!("delete scratch: {e}"))?;
11365            Ok(new_id)
11366        }
11367        .await;
11368
11369        match result {
11370            Ok(id) => committed.push(id),
11371            Err(e) => {
11372                failed.push(serde_json::json!({
11373                    "uploaded_file_id": item.uploaded_file_id,
11374                    "error": e,
11375                }));
11376            }
11377        }
11378    }
11379
11380    let body = serde_json::json!({
11381        "committed": committed,
11382        "failed": failed,
11383    });
11384    Ok((
11385        [(axum::http::header::CONTENT_TYPE, "application/json")],
11386        serde_json::to_string(&body).unwrap_or_else(|_| "{}".to_owned()),
11387    )
11388        .into_response())
11389}
11390
11391/// POST /cms-admin/media/upload-staged/{id}/cancel — drop scratch row
11392/// + unlink the file. Returns 204.
11393pub async fn media_upload_staged_cancel(
11394    State(_state): State<super::AdminState>,
11395    tenant: Tenant,
11396    headers: HeaderMap,
11397    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
11398    Path(id): Path<i64>,
11399) -> Result<Response, AdminError> {
11400    let Some(viewer) = session_user.as_ref() else {
11401        // #285 — JSON-aware 401 for fetch clients.
11402        return Ok(unauthorized_no_session_for(Some(&headers)));
11403    };
11404    let viewer_id = viewer.id.get().copied().unwrap_or_default();
11405    let Some(row) = crate::uploaded_file::get(tenant.pool(), id).await? else {
11406        return Ok((axum::http::StatusCode::NOT_FOUND, "not found").into_response());
11407    };
11408    if row.user_id != viewer_id && !viewer.is_superuser {
11409        return Ok((axum::http::StatusCode::FORBIDDEN, "not your upload").into_response());
11410    }
11411    crate::media_storage::disk_for(&tenant.org.slug)
11412        .delete(&crate::media_storage::key(
11413            &tenant.org.slug,
11414            &row.storage_key,
11415        ))
11416        .await
11417        .log_warn("stored file not deleted; the blob is orphaned");
11418    crate::uploaded_file::delete(tenant.pool(), id).await?;
11419    Ok((axum::http::StatusCode::NO_CONTENT, "").into_response())
11420}
11421
11422/// Refuse a file a browser would run as a page: HTML, XHTML,
11423/// JavaScript and XML (which can carry script through XSLT or an XHTML
11424/// namespace). Serving neutralises every type already; this keeps such
11425/// files out of the library in the first place. SVG stays allowed — it is
11426/// served under a no-script CSP.
11427fn refuse_active_upload(mime: &str) -> Result<(), AdminError> {
11428    let active = matches!(
11429        mime,
11430        "text/html"
11431            | "application/xhtml+xml"
11432            | "text/javascript"
11433            | "application/javascript"
11434            | "application/ecmascript"
11435            | "text/xml"
11436            | "application/xml"
11437            | "text/xsl"
11438            | "application/xslt+xml"
11439    );
11440    if active {
11441        return Err(AdminError::Upload(format!(
11442            "files of type {mime} can't be uploaded: a browser would run them as a page"
11443        )));
11444    }
11445    Ok(())
11446}
11447
11448/// Store one media file: sanitize the name, detect + classify the mime,
11449/// strip EXIF from images, hash, write
11450/// storage key `<org_slug>/<hash16>-<name>`, and insert the `cms_media`
11451/// row. The single canonical write path — the browser upload handlers and
11452/// the MCP `upload_media` tool all funnel through here.
11453///
11454/// `dedupe = true` short-circuits on an existing row with the same
11455/// content hash (returns it instead of storing a byte-identical copy) —
11456/// the same behavior the staged-upload flow gives the browser.
11457#[allow(clippy::too_many_arguments)]
11458pub(crate) async fn store_media(
11459    pool: &rustango::sql::Pool,
11460    org_slug: &str,
11461    mut bytes: Vec<u8>,
11462    raw_filename: &str,
11463    title: Option<&str>,
11464    alt_text: &str,
11465    collection_id: Option<i64>,
11466    uploaded_by: Option<i64>,
11467    dedupe: bool,
11468) -> Result<Media, AdminError> {
11469    use rustango::sql::Auto;
11470    use sha2::{Digest, Sha256};
11471
11472    let filename = sanitize_filename(raw_filename);
11473    if filename.is_empty() || bytes.is_empty() {
11474        return Err(AdminError::Upload("no file submitted".into()));
11475    }
11476
11477    let mime = mime_guess::from_path(&filename)
11478        .first_or_octet_stream()
11479        .essence_str()
11480        .to_owned();
11481    refuse_active_upload(&mime)?;
11482    let kind = Media::classify_mime(&mime).to_owned();
11483
11484    // #184 — strip EXIF on image upload, BEFORE hashing so the hash
11485    // reflects the stored bytes. See `media_upload_submit` for the why.
11486    let (stored, decoded_dims) = crate::rendition::strip_exif_off_runtime(bytes, mime.clone()).await;
11487    bytes = stored;
11488
11489    let mut hasher = Sha256::new();
11490    hasher.update(&bytes);
11491    let digest = hasher.finalize();
11492    let hash = digest.iter().fold(String::with_capacity(64), |mut acc, b| {
11493        use std::fmt::Write as _;
11494        let _ = write!(acc, "{b:02x}");
11495        acc
11496    });
11497
11498    if dedupe {
11499        if let Some(existing) = Media::objects()
11500            .where_(Media::content_hash.eq(hash.clone()))
11501            .first(pool)
11502            .await?
11503        {
11504            return Ok(existing);
11505        }
11506    }
11507
11508    // Routed through the pluggable storage backend (Slice 8.x).
11509    let storage_key = format!("{}-{}", &hash[..16], filename);
11510    crate::media_storage::disk_for(&org_slug)
11511        .save(&crate::media_storage::key(org_slug, &storage_key), &bytes)
11512        .await
11513        .map_err(|e| AdminError::Upload(format!("write: {e}")))?;
11514
11515    let title = match title {
11516        Some(t) if !t.is_empty() => t.to_owned(),
11517        _ => filename
11518            .rsplit_once('.')
11519            .map(|(stem, _)| stem.to_owned())
11520            .unwrap_or_else(|| filename.clone()),
11521    };
11522
11523    // Pixel dimensions fall out of the EXIF-strip decode; non-images /
11524    // broken decodes get `None`.
11525    let (width, height): (Option<i32>, Option<i32>) = decoded_dims
11526        .map(|(w, h)| (Some(w as i32), Some(h as i32)))
11527        .unwrap_or((None, None));
11528
11529    let mut row = Media {
11530        id: Auto::Unset,
11531        filename,
11532        content_hash: hash,
11533        mime,
11534        size: bytes.len() as i64,
11535        kind,
11536        width,
11537        height,
11538        storage_key,
11539        title,
11540        alt_text: alt_text.to_owned(),
11541        description: String::new(),
11542        uploaded_by,
11543        collection_id,
11544        focal_point_x: None,
11545        focal_point_y: None,
11546        uploaded_at: Auto::Unset,
11547    };
11548    row.insert(pool).await?;
11549    Ok(row)
11550}
11551
11552pub async fn media_upload_submit(
11553    State(_state): State<super::AdminState>,
11554    tenant: Tenant,
11555    mut multipart: axum::extract::Multipart,
11556) -> Result<Response, AdminError> {
11557    let mut filename = String::new();
11558    let mut bytes: Vec<u8> = Vec::new();
11559    let mut title = String::new();
11560    let mut alt_text = String::new();
11561    // #24 V2 — upload-time crop. When the client submits all four
11562    // crop coords (source-image pixel space), we decode + crop the
11563    // bytes before storing so the on-disk canonical file matches the
11564    // editor's intent. Absence of any of the four = no crop.
11565    let mut crop_x: Option<u32> = None;
11566    let mut crop_y: Option<u32> = None;
11567    let mut crop_w: Option<u32> = None;
11568    let mut crop_h: Option<u32> = None;
11569
11570    while let Some(field) = multipart
11571        .next_field()
11572        .await
11573        .map_err(|e| AdminError::Upload(format!("multipart parse: {e}")))?
11574    {
11575        let name = field.name().unwrap_or("").to_owned();
11576        match name.as_str() {
11577            "file" => {
11578                if let Some(fname) = field.file_name() {
11579                    filename = sanitize_filename(fname);
11580                }
11581                bytes = field
11582                    .bytes()
11583                    .await
11584                    .map_err(|e| AdminError::Upload(format!("read bytes: {e}")))?
11585                    .to_vec();
11586            }
11587            "title" => {
11588                title = field
11589                    .text()
11590                    .await
11591                    .map_err(|e| AdminError::Upload(format!("read title: {e}")))?;
11592            }
11593            "alt_text" => {
11594                alt_text = field
11595                    .text()
11596                    .await
11597                    .map_err(|e| AdminError::Upload(format!("read alt_text: {e}")))?;
11598            }
11599            "crop_x" | "crop_y" | "crop_w" | "crop_h" => {
11600                let value = field
11601                    .text()
11602                    .await
11603                    .map_err(|e| AdminError::Upload(format!("read {name}: {e}")))?;
11604                let parsed: Option<u32> = value.trim().parse().ok();
11605                match name.as_str() {
11606                    "crop_x" => crop_x = parsed,
11607                    "crop_y" => crop_y = parsed,
11608                    "crop_w" => crop_w = parsed,
11609                    "crop_h" => crop_h = parsed,
11610                    _ => {}
11611                }
11612            }
11613            _ => {
11614                let _ = field.bytes().await;
11615            }
11616        }
11617    }
11618
11619    if filename.is_empty() || bytes.is_empty() {
11620        return Err(AdminError::Upload("no file submitted".into()));
11621    }
11622
11623    // Apply crop if all four coords arrived. Image-only — vector
11624    // sources can't be raster-cropped (mirrors the edit-time rule
11625    // in the V1 crop handler).
11626    if let (Some(x), Some(y), Some(w), Some(h)) = (crop_x, crop_y, crop_w, crop_h) {
11627        if w > 0 && h > 0 {
11628            let detected_mime = mime_guess::from_path(&filename)
11629                .first_or_octet_stream()
11630                .essence_str()
11631                .to_owned();
11632            refuse_active_upload(&detected_mime)?;
11633            if detected_mime == "image/svg+xml" {
11634                return Err(AdminError::Validation(
11635                    "Cropping SVG sources isn't supported; upload uncropped, then edit the markup."
11636                        .to_owned(),
11637                ));
11638            }
11639            if detected_mime.starts_with("image/") {
11640                let (cropped, _out_mime) = crate::rendition::crop_image_off_runtime(
11641                    bytes,
11642                    detected_mime.clone(),
11643                    (x, y, w, h),
11644                )
11645                .await
11646                .map_err(AdminError::Validation)?;
11647                bytes = cropped;
11648            }
11649        }
11650    }
11651
11652    // This legacy single-file path ignores any collection choice (the
11653    // per-file picker lives on the staged upload flow): rows land in
11654    // "uncategorized" (NULL) under the root collection.
11655    let row = store_media(
11656        tenant.pool(),
11657        &tenant.org.slug,
11658        bytes,
11659        &filename,
11660        (!title.is_empty()).then_some(title.as_str()),
11661        &alt_text,
11662        None,
11663        None,
11664        false,
11665    )
11666    .await?;
11667
11668    let redirect = if row.kind == "image" {
11669        "/cms-admin/media"
11670    } else {
11671        "/cms-admin/documents"
11672    };
11673    Ok(Redirect::to(redirect).into_response())
11674}
11675
11676/// Remove `renditions` — their stored files (best effort) and rows.
11677async fn purge_renditions(
11678    pool: &rustango::sql::Pool,
11679    org_slug: &str,
11680    renditions: Vec<crate::rendition::MediaRendition>,
11681) -> Result<(), AdminError> {
11682    for r in renditions {
11683        crate::media_storage::disk_for(org_slug)
11684            .delete(&crate::media_storage::key(org_slug, &r.storage_key))
11685            .await
11686            .log_warn("stored file not deleted; the blob is orphaned");
11687        r.delete(pool).await?;
11688    }
11689    Ok(())
11690}
11691
11692/// Delete a media item: its renditions first (they reference it, so the
11693/// row can't go while they exist), then its stored file, then the row.
11694async fn delete_media(pool: &rustango::sql::Pool, org_slug: &str, row: Media) -> Result<(), AdminError> {
11695    let renditions = crate::rendition::MediaRendition::objects()
11696        .where_(crate::rendition::MediaRendition::media_id.eq(row.id.get().copied().unwrap_or_default()))
11697        .fetch(pool)
11698        .await?;
11699    purge_renditions(pool, org_slug, renditions).await?;
11700    // Best-effort storage cleanup — a missing object is not fatal.
11701    crate::media_storage::disk_for(org_slug)
11702        .delete(&crate::media_storage::key(org_slug, &row.storage_key))
11703        .await
11704        .log_warn("stored file not deleted; the blob is orphaned");
11705    row.delete(pool).await?;
11706    Ok(())
11707}
11708
11709/// POST /cms-admin/media/{id}/delete — drop a media row.
11710pub async fn media_delete_submit(
11711    State(_state): State<super::AdminState>,
11712    tenant: Tenant,
11713    Path(id): Path<i64>,
11714) -> Result<Response, AdminError> {
11715    let row = Media::objects()
11716        .where_(Media::id.eq(id))
11717        .first(tenant.pool())
11718        .await?
11719        .ok_or(AdminError::NotFound(id))?;
11720    let redirect = if row.kind == "image" {
11721        "/cms-admin/media"
11722    } else {
11723        "/cms-admin/documents"
11724    };
11725    delete_media(tenant.pool(), &tenant.org.slug, row).await?;
11726    Ok(Redirect::to(redirect).into_response())
11727}
11728
11729fn sanitize_filename(raw: &str) -> String {
11730    raw.chars()
11731        .map(|c| {
11732            if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') {
11733                c
11734            } else {
11735                '_'
11736            }
11737        })
11738        .collect()
11739}
11740
11741// =====================================================================
11742// Locales tab
11743// =====================================================================
11744
11745/// GET /cms-admin/locales — list every locale.
11746/// GET /cms-admin/model/{slug} — generic read-only index for a
11747/// model registered via `register_model_admin!`: columns come from the
11748/// model's `admin(list_display = …)`, rows from its type-erased
11749/// list-rows thunk, all inside the CMS admin chrome. 404s an unknown
11750/// slug.
11751pub async fn model_admin_list(
11752    State(state): State<super::AdminState>,
11753    tenant: Tenant,
11754    headers: HeaderMap,
11755    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
11756    Path(slug): Path<String>,
11757    Query(paging): Query<crate::admin::pagination::PageQuery>,
11758    axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
11759) -> Result<Response, AdminError> {
11760    let Some(ma) = super::model_admin::find(&slug) else {
11761        return Ok((axum::http::StatusCode::NOT_FOUND, "unknown model admin").into_response());
11762    };
11763    // Paged (#629): a host model holds user data, not configuration. The
11764    // requested page is read first; only a `?page=` past the end (which
11765    // the window clamps to the last page) costs a second read.
11766    let per_page = crate::admin::pagination::clamp_per_page(paging.per_page);
11767    let asked = crate::admin::pagination::offset(paging.page.unwrap_or(1), per_page);
11768    let (mut rows_json, total) =
11769        (ma.list_rows)(tenant.pool().clone(), per_page as i64, asked).await;
11770    let window = paging.window(usize::try_from(total).unwrap_or_default());
11771    if window.offset != asked {
11772        rows_json = (ma.list_rows)(tenant.pool().clone(), window.limit, window.offset).await.0;
11773    }
11774    let columns = super::model_admin::list_columns(ma.schema);
11775    let header_labels: Vec<&str> = columns.iter().map(|(_, l)| l.as_str()).collect();
11776    let body_rows: Vec<Vec<String>> = rows_json
11777        .iter()
11778        .map(|r| {
11779            columns
11780                .iter()
11781                .map(|(name, _)| super::model_admin::row_cell(r, name))
11782                .collect()
11783        })
11784        .collect();
11785    let mut ctx = Context::new();
11786    add_chrome(&mut ctx, &tenant, "model-admin", session_user.as_ref()).await;
11787    add_admin_theme(&mut ctx, tenant.pool()).await;
11788    ctx.insert("model_label", ma.label);
11789    ctx.insert("model_slug", &slug);
11790    ctx.insert("columns", &header_labels);
11791    ctx.insert("rows", &body_rows);
11792    ctx.insert("total", &total);
11793    ctx.insert("pagination", &window.context);
11794    ctx.insert("query_string", &raw_query.unwrap_or_default());
11795    render_with_csrf(
11796        &state,
11797        &headers,
11798        "rcms_admin/model_admin_list.html",
11799        &mut ctx,
11800    )
11801}
11802
11803/// `?format=csv` selector for [`report_view`].
11804#[derive(serde::Deserialize, Default)]
11805pub struct ReportQuery {
11806    pub format: Option<String>,
11807}
11808
11809/// Render any registered report through the shared chrome'd
11810/// table, or export it as CSV with `?format=csv`. `active_tab` is
11811/// `report:<slug>` so `_base.html` highlights the matching sidebar link.
11812pub async fn report_view(
11813    State(state): State<super::AdminState>,
11814    tenant: Tenant,
11815    headers: HeaderMap,
11816    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
11817    Path(slug): Path<String>,
11818    Query(q): Query<ReportQuery>,
11819) -> Result<Response, AdminError> {
11820    let Some(report) = super::report::find_report(&slug) else {
11821        return Ok((axum::http::StatusCode::NOT_FOUND, "unknown report").into_response());
11822    };
11823    let user_id = session_user.as_ref().and_then(|u| u.id.get().copied());
11824    let columns = report.columns();
11825    let rows = report.rows(tenant.pool(), user_id).await;
11826
11827    // CSV export — same rows, flattened to column order.
11828    if q.format.as_deref() == Some("csv") {
11829        let mut out = String::with_capacity(128 + rows.len() * 64);
11830        let header: Vec<String> = columns.iter().map(|c| csv_escape(c.label)).collect();
11831        out.push_str(&header.join(","));
11832        out.push('\n');
11833        for row in &rows {
11834            let line: Vec<String> = columns
11835                .iter()
11836                .map(|c| csv_escape(&report_cell_string(row.get(c.key))))
11837                .collect();
11838            out.push_str(&line.join(","));
11839            out.push('\n');
11840        }
11841        return Ok(csv_response(&slug, &out));
11842    }
11843
11844    let header_labels: Vec<&str> = columns.iter().map(|c| c.label).collect();
11845    let view_rows: Vec<serde_json::Value> = rows
11846        .iter()
11847        .map(|row| {
11848            let cells: Vec<serde_json::Value> = columns
11849                .iter()
11850                .map(|c| {
11851                    serde_json::json!({
11852                        "kind": c.kind.as_str(),
11853                        "value": report_cell_string(row.get(c.key)),
11854                    })
11855                })
11856                .collect();
11857            serde_json::json!({
11858                "edit_url": row.get("edit_url").and_then(|v| v.as_str()),
11859                "cells": cells,
11860            })
11861        })
11862        .collect();
11863
11864    let mut ctx = Context::new();
11865    add_chrome(
11866        &mut ctx,
11867        &tenant,
11868        &format!("report:{slug}"),
11869        session_user.as_ref(),
11870    )
11871    .await;
11872    add_admin_theme(&mut ctx, tenant.pool()).await;
11873    ctx.insert("report_title", report.title());
11874    ctx.insert("report_slug", &slug);
11875    ctx.insert("report_description", &report.description());
11876    ctx.insert("columns", &header_labels);
11877    ctx.insert("rows", &view_rows);
11878    ctx.insert("total", &view_rows.len());
11879    render_with_csrf(&state, &headers, "rcms_admin/report.html", &mut ctx)
11880}
11881
11882// ===================================================================== Form builder (#533)
11883
11884/// GET `/cms-admin/forms` — dedicated Forms list: every form snippet with its
11885/// per-form submission count and last-submission time, linking straight into
11886/// the builder and the submission history. This exists because the generic
11887/// library table can't surface submissions (`LibraryTypeHandler::render_cell`
11888/// is sync and pool-less), which left "Forms" dead-ending on a Library view
11889/// with no way to see what a form collected.
11890pub async fn forms_list(
11891    State(state): State<super::AdminState>,
11892    tenant: Tenant,
11893    headers: HeaderMap,
11894    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
11895) -> Result<Response, AdminError> {
11896    let pool = tenant.pool();
11897    let rows = forms_list_rows(pool).await?;
11898
11899    let mut ctx = Context::new();
11900    add_chrome(&mut ctx, &tenant, "forms", session_user.as_ref()).await;
11901    add_admin_theme(&mut ctx, pool).await;
11902    ctx.insert("rows", &rows);
11903    ctx.insert("total", &rows.len());
11904    render_with_csrf(&state, &headers, "rcms_admin/forms_list.html", &mut ctx)
11905}
11906
11907/// Core of [`forms_list`] — the row model (per-form field count, submission
11908/// count, latest submission, action URLs), split out so unit tests can drive
11909/// it with an in-memory pool.
11910pub(crate) async fn forms_list_rows(
11911    pool: &rustango::sql::Pool,
11912) -> Result<Vec<serde_json::Value>, AdminError> {
11913    let mut forms: Vec<crate::snippet::Snippet> = crate::snippet::Snippet::objects()
11914        .where_(crate::snippet::Snippet::type_name.eq("form".to_owned()))
11915        .fetch(pool)
11916        .await?;
11917    // Newest-edited first.
11918    forms.sort_by(|a, b| {
11919        b.updated_at
11920            .get()
11921            .cloned()
11922            .cmp(&a.updated_at.get().cloned())
11923    });
11924
11925    // Per-form submission count + latest submission, grouped in Rust — the
11926    // tri-dialect pattern used by `counts_by_type` / the pages `child_counts`
11927    // (no SQL GROUP BY helper in the codebase).
11928    let entries: Vec<crate::forms::submit::FormEntry> = crate::forms::submit::FormEntry::objects()
11929        .fetch(pool)
11930        .await?;
11931    let mut counts: std::collections::HashMap<i64, i64> = std::collections::HashMap::new();
11932    let mut last_at: std::collections::HashMap<i64, String> = std::collections::HashMap::new();
11933    for e in &entries {
11934        *counts.entry(e.form_snippet_id).or_default() += 1;
11935        if let Some(at) = e.submitted_at.get() {
11936            let s = at.format("%Y-%m-%d %H:%M").to_string();
11937            let slot = last_at.entry(e.form_snippet_id).or_default();
11938            if s > *slot {
11939                *slot = s;
11940            }
11941        }
11942    }
11943
11944    let rows: Vec<serde_json::Value> = forms
11945        .iter()
11946        .map(|s| {
11947            let id = s.id.get().copied().unwrap_or_default();
11948            let parsed = crate::forms::schema::parse(&s.data).unwrap_or_default();
11949            serde_json::json!({
11950                "id": id,
11951                "title": s.title,
11952                "slug": s.slug,
11953                "fields": parsed.field_count(),
11954                "submissions": counts.get(&id).copied().unwrap_or(0),
11955                "last_submission": last_at.get(&id).cloned().unwrap_or_default(),
11956                "updated_at": s.updated_at.get().map(|d| d.format("%Y-%m-%d").to_string()).unwrap_or_default(),
11957                "build_url": format!("/cms-admin/forms/{id}/build"),
11958                "submissions_url": format!("/cms-admin/forms/{id}/submissions"),
11959                "delete_url": format!("/cms-admin/library/{id}/delete"),
11960            })
11961        })
11962        .collect();
11963    Ok(rows)
11964}
11965
11966/// GET `/cms-admin/forms/{id}/build` — the visual form builder editor.
11967/// Loads the form snippet's schema JSON into the page; the
11968/// `form_builder.js` engine renders the editor from it.
11969pub async fn form_build_form(
11970    State(state): State<super::AdminState>,
11971    tenant: Tenant,
11972    headers: HeaderMap,
11973    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
11974    Path(id): Path<i64>,
11975    Query(q): Query<EditQuery>,
11976) -> Result<Response, AdminError> {
11977    let snippet = crate::snippet::Snippet::objects()
11978        .where_(crate::snippet::Snippet::id.eq(id))
11979        .first(tenant.pool())
11980        .await?
11981        .ok_or(AdminError::NotFound(id))?;
11982    if snippet.type_name != "form" {
11983        return Err(AdminError::NotFound(id));
11984    }
11985    let mut ctx = Context::new();
11986    add_chrome(&mut ctx, &tenant, "forms", session_user.as_ref()).await;
11987    add_admin_theme(&mut ctx, tenant.pool()).await;
11988    ctx.insert("title", &snippet.title);
11989    ctx.insert("form_id", &id);
11990    ctx.insert("build_url", &format!("/cms-admin/forms/{id}/build"));
11991
11992    // #550 FB-17 — active non-default locales for the Translate picker.
11993    let locales: Vec<crate::locale::Locale> = crate::locale::Locale::objects()
11994        .where_(crate::locale::Locale::active.eq(true))
11995        .where_(crate::locale::Locale::is_default.eq(false))
11996        .fetch(tenant.pool())
11997        .await
11998        .unwrap_or_default();
11999    ctx.insert(
12000        "locales",
12001        &locales
12002            .iter()
12003            .map(|l| serde_json::json!({"code": l.code, "name": l.name}))
12004            .collect::<Vec<_>>(),
12005    );
12006
12007    // Translate mode: ?locale=<code> renders a focused per-leaf editor that
12008    // posts to the existing snippet-translate endpoint.
12009    if let Some(code) = q.locale.as_deref().filter(|c| !c.is_empty()) {
12010        if let Some(loc) = locales.iter().find(|l| l.code == code) {
12011            let lid = loc.id.get().copied().unwrap_or(0);
12012            let form = crate::forms::schema::parse(&snippet.data).unwrap_or_default();
12013            let leaves = crate::forms::schema::translatable_leaves(&form);
12014            let existing = crate::snippet_translation::fetch_for(tenant.pool(), id, lid)
12015                .await
12016                .unwrap_or_default();
12017            // Consecutive leaves of one field form a group, like the
12018            // block groups of the page editor.
12019            let mut groups: Vec<serde_json::Value> = Vec::new();
12020            for l in &leaves {
12021                let row = serde_json::json!({
12022                    "path": l.path,
12023                    "part": l.part,
12024                    "n": l.n.to_string(),
12025                    "canonical": l.text,
12026                    "value": existing.get(&l.path).cloned().unwrap_or_default(),
12027                });
12028                let same = groups
12029                    .last()
12030                    .is_some_and(|g| g["name"].as_str() == Some(l.group.as_str()));
12031                if same {
12032                    if let Some(arr) = groups
12033                        .last_mut()
12034                        .and_then(|g| g.get_mut("leaves"))
12035                        .and_then(|v| v.as_array_mut())
12036                    {
12037                        arr.push(row);
12038                    }
12039                } else {
12040                    groups.push(serde_json::json!({ "name": l.group, "leaves": [row] }));
12041                }
12042            }
12043            ctx.insert("editing_locale", &loc.name);
12044            ctx.insert("editing_code", &code);
12045            ctx.insert("trans_groups", &groups);
12046            ctx.insert(
12047                "translate_url",
12048                &format!("/cms-admin/library/{id}/translate"),
12049            );
12050            return render_with_csrf(&state, &headers, "rcms_admin/form_translate.html", &mut ctx);
12051        }
12052    }
12053
12054    // The builder's back button says "Forms", so it has to land on the
12055    // Forms list. Pointing it at the generic Library view dropped editors
12056    // onto a different listing of the same rows — its own search, its own
12057    // column picker, no Submissions column — which read as a second,
12058    // older Forms screen. Every other builder points at its own list.
12059    ctx.insert("list_url", "/cms-admin/forms");
12060    // FB-15 — the builder edits the DRAFT; Publish promotes it to live.
12061    ctx.insert("publish_url", &format!("/cms-admin/forms/{id}/publish"));
12062    ctx.insert(
12063        "has_unpublished",
12064        &crate::forms::schema::has_unpublished_changes(&snippet.data),
12065    );
12066    let mut draft = crate::forms::schema::parse_draft(&snippet.data);
12067    draft.sanitize_rich_text();
12068    let schema_json = serde_json::to_string(&crate::forms::schema::to_value(&draft))
12069        .unwrap_or_else(|_| "{}".to_owned());
12070    ctx.insert("schema_json", &schema_json);
12071    render_with_csrf(&state, &headers, "rcms_admin/form_builder.html", &mut ctx)
12072}
12073
12074#[derive(Debug, Deserialize)]
12075pub struct FormBuildSubmit {
12076    pub schema: String,
12077}
12078
12079/// Create-a-page-type submit. `type_name` is slugified server-side.
12080#[derive(Debug, Deserialize)]
12081pub struct FormPageTypeCreate {
12082    #[serde(default)]
12083    pub verbose_name: String,
12084    #[serde(default)]
12085    pub type_name: String,
12086    #[serde(default)]
12087    pub allowed_parents: String,
12088    #[serde(default)]
12089    pub allowed_children: String,
12090    /// `"auto" | "html" | "api"` — see [`crate::page_view::PageViewMode`].
12091    /// Offered only for UI types: a code type's mode is re-seeded from
12092    /// its handler on every boot, so an admin edit would silently revert.
12093    #[serde(default)]
12094    pub view_mode: String,
12095    /// Workflow name, or empty to publish directly.
12096    #[serde(default)]
12097    pub workflow: String,
12098}
12099
12100/// Component builder submit: builder `schema` (a `{nodes:[…]}` blob)
12101/// plus the component metadata fields.
12102#[derive(Debug, Deserialize)]
12103pub struct FormComponentSubmit {
12104    #[serde(default)]
12105    pub slug: String,
12106    #[serde(default)]
12107    pub label: String,
12108    #[serde(default)]
12109    pub icon: String,
12110    #[serde(default)]
12111    pub description: String,
12112    #[serde(default)]
12113    pub schema: String,
12114}
12115
12116/// POST `/cms-admin/forms/{id}/build` — persist the builder's schema into
12117/// GET|POST /cms-admin/forms/{id}/preview — render this form the way a
12118/// visitor sees it, for the editor's sidebar preview.
12119///
12120/// GET renders the saved draft; POST renders the schema in the request
12121/// body, which is how the builder shows unsaved edits — the same
12122/// saved-vs-unsaved split the page preview uses.
12123///
12124/// Crucially this calls [`crate::forms::render::render_form_html`] — the
12125/// one the public site calls. The builder used to draw its own preview in
12126/// JavaScript, rebuilding the layout a second time in a second language;
12127/// the two could only agree by coincidence, and every renderer change had
12128/// to be made twice or the preview quietly started lying.
12129pub async fn form_preview(
12130    tenant: Tenant,
12131    Path(id): Path<i64>,
12132    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
12133) -> Result<Response, AdminError> {
12134    let snippet = load_form_snippet(&tenant, id).await?;
12135    let form = crate::forms::schema::parse_draft(&snippet.data);
12136    Ok(render_form_preview(id, &form))
12137}
12138
12139/// POST /cms-admin/forms/{id}/preview — render the schema in the body, so
12140/// the builder previews edits that have not been saved. Mirrors
12141/// `page_preview_draft`.
12142pub async fn form_preview_draft(
12143    tenant: Tenant,
12144    Path(id): Path<i64>,
12145    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
12146    Form(body): Form<FormBuildSubmit>,
12147) -> Result<Response, AdminError> {
12148    let snippet = load_form_snippet(&tenant, id).await?;
12149    // A schema that does not parse is the normal state mid-edit, not an
12150    // error worth blanking the pane for: fall back to the saved draft and
12151    // let the editor keep typing.
12152    let form = crate::forms::schema::parse_str(&body.schema)
12153        .unwrap_or_else(|_| crate::forms::schema::parse_draft(&snippet.data));
12154    Ok(render_form_preview(id, &form))
12155}
12156
12157/// The snippet behind a form id, refusing anything that is not a form.
12158async fn load_form_snippet(
12159    tenant: &Tenant,
12160    id: i64,
12161) -> Result<crate::snippet::Snippet, AdminError> {
12162    let snippet = crate::snippet::Snippet::objects()
12163        .where_(crate::snippet::Snippet::id.eq(id))
12164        .first(tenant.pool())
12165        .await?
12166        .ok_or(AdminError::NotFound(id))?;
12167    if snippet.type_name != "form" {
12168        return Err(AdminError::NotFound(id));
12169    }
12170    Ok(snippet)
12171}
12172
12173fn render_form_preview(id: i64, form: &crate::forms::schema::Form) -> Response {
12174    // `embed_id` is empty: this is the standalone render, with no page
12175    // embedding it and so no per-embed override to resolve.
12176    let inner = crate::forms::render::render_form_html(form, id, "");
12177    let html = format!(
12178        "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
12179         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
12180         <title>Form preview</title>\
12181         <style>body{{margin:0;padding:24px;font:14px/1.5 system-ui,sans-serif;}}</style>\
12182         </head><body>{inner}</body></html>"
12183    );
12184    stamp_no_cache(
12185        (
12186            [(
12187                axum::http::header::CONTENT_TYPE,
12188                axum::http::HeaderValue::from_static("text/html; charset=utf-8"),
12189            )],
12190            html,
12191        )
12192            .into_response(),
12193    )
12194}
12195
12196/// the snippet's `data` column + capture a revision.
12197pub async fn form_build_submit(
12198    State(_state): State<super::AdminState>,
12199    tenant: Tenant,
12200    headers: HeaderMap,
12201    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
12202    Path(id): Path<i64>,
12203    Form(form): Form<FormBuildSubmit>,
12204) -> Result<Response, AdminError> {
12205    let mut snippet = crate::snippet::Snippet::objects()
12206        .where_(crate::snippet::Snippet::id.eq(id))
12207        .first(tenant.pool())
12208        .await?
12209        .ok_or(AdminError::NotFound(id))?;
12210    if snippet.type_name != "form" {
12211        return Err(AdminError::NotFound(id));
12212    }
12213    let mut parsed = crate::forms::schema::parse_str(&form.schema)
12214        .map_err(|e| AdminError::Validation(format!("invalid form schema: {e}")))?;
12215    parsed.sanitize_rich_text();
12216    let mut warnings = crate::forms::schema::validate(&parsed);
12217    // FB-15 — saving stores a DRAFT; the published (public) form is untouched
12218    // until Publish.
12219    snippet.data = crate::forms::schema::save_draft_value(&snippet.data, &parsed);
12220    snippet.save(tenant.pool()).await?;
12221    // Keep the notification target in step with the recipients typed into
12222    // form settings, so the two cannot disagree about who gets told.
12223    if let Err(e) = crate::notify::targets::sync_form_email(
12224        tenant.pool(),
12225        id,
12226        &snippet.title,
12227        &parsed.settings.notify_emails,
12228    )
12229    .await
12230    {
12231        tracing::warn!(
12232            target: "rustango_cms::notify",
12233            error = %e, form_id = id,
12234            "could not sync the form's email notification target"
12235        );
12236        warnings.push(format!("Email notifications are off: {e}."));
12237    }
12238    let (level, msg) = if warnings.is_empty() {
12239        (MsgLevel::Success, "Draft saved.".to_owned())
12240    } else {
12241        (
12242            MsgLevel::Warning,
12243            format!("Draft saved with warnings: {}", warnings.join(" ")),
12244        )
12245    };
12246    redirect_named_with_params_and_message(
12247        "rcms-admin:forms:build",
12248        &[("id", id.to_string())],
12249        level,
12250        &msg,
12251        &headers,
12252    )
12253}
12254
12255/// POST `/cms-admin/forms/{id}/publish` — publish the submitted schema: it
12256/// becomes the live (public) form + the draft, and a revision is captured.
12257pub async fn form_publish_submit(
12258    State(_state): State<super::AdminState>,
12259    tenant: Tenant,
12260    headers: HeaderMap,
12261    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
12262    Path(id): Path<i64>,
12263    Form(form): Form<FormBuildSubmit>,
12264) -> Result<Response, AdminError> {
12265    let mut snippet = crate::snippet::Snippet::objects()
12266        .where_(crate::snippet::Snippet::id.eq(id))
12267        .first(tenant.pool())
12268        .await?
12269        .ok_or(AdminError::NotFound(id))?;
12270    if snippet.type_name != "form" {
12271        return Err(AdminError::NotFound(id));
12272    }
12273    let mut parsed = crate::forms::schema::parse_str(&form.schema)
12274        .map_err(|e| AdminError::Validation(format!("invalid form schema: {e}")))?;
12275    parsed.sanitize_rich_text();
12276    snippet.data = crate::forms::schema::publish_value(&parsed);
12277    snippet.save(tenant.pool()).await?;
12278    if let Some(h) = crate::library::find_handler(&snippet.type_name) {
12279        if h.revisions_enabled() {
12280            let uid = session_user.as_ref().and_then(|u| u.id.get().copied());
12281            crate::snippet::capture_revision(tenant.pool(), &snippet, uid)
12282                .await
12283                .log_warn("revision not captured; the history has a gap");
12284        }
12285    }
12286    redirect_named_with_params_and_message(
12287        "rcms-admin:forms:build",
12288        &[("id", id.to_string())],
12289        MsgLevel::Success,
12290        "Form published — the live form is now up to date.",
12291        &headers,
12292    )
12293}
12294
12295/// Shared loader for the submissions views: the form
12296/// snippet, its parsed schema's value-columns, the entries, and a
12297/// source-page-id → url_path map for provenance links.
12298async fn load_form_submissions(
12299    pool: &rustango::sql::Pool,
12300    form_id: i64,
12301    paging: Option<&crate::admin::pagination::PageQuery>,
12302) -> Result<
12303    (
12304        crate::snippet::Snippet,
12305        Vec<(String, String)>,
12306        Vec<crate::forms::submit::FormEntry>,
12307        std::collections::HashMap<i64, String>,
12308        Option<crate::admin::pagination::Window>,
12309    ),
12310    AdminError,
12311> {
12312    use crate::forms::submit::FormEntry;
12313    let snippet = crate::snippet::Snippet::objects()
12314        .where_(crate::snippet::Snippet::id.eq(form_id))
12315        .where_(crate::snippet::Snippet::type_name.eq("form".to_owned()))
12316        .first(pool)
12317        .await?
12318        .ok_or(AdminError::NotFound(form_id))?;
12319    let form = crate::forms::schema::parse(&snippet.data).unwrap_or_default();
12320    let columns: Vec<(String, String)> = form
12321        .fields()
12322        .filter(|f| f.field_type.collects_value() && !f.key.is_empty())
12323        .map(|f| {
12324            (
12325                f.key.clone(),
12326                if f.label.is_empty() {
12327                    f.key.clone()
12328                } else {
12329                    f.label.clone()
12330                },
12331            )
12332        })
12333        .collect();
12334    // The list shows one page of submissions (#627); the CSV export
12335    // passes no paging and gets them all.
12336    let listed = || {
12337        FormEntry::objects()
12338            .where_(FormEntry::form_snippet_id.eq(form_id))
12339            // `id` breaks timestamp ties, so pages never repeat or skip rows.
12340            .order_by(&[("submitted_at", true), ("id", true)])
12341    };
12342    let (entries, window): (Vec<FormEntry>, _) = match paging {
12343        Some(q) => {
12344            let total = listed().count(pool).await?;
12345            let w = q.window(usize::try_from(total).unwrap_or_default());
12346            (listed().limit(w.limit).offset(w.offset).fetch(pool).await?, Some(w))
12347        }
12348        None => (listed().fetch(pool).await?, None),
12349    };
12350    // Resolve source pages for provenance links.
12351    let mut page_urls = std::collections::HashMap::new();
12352    let ids: std::collections::BTreeSet<i64> = entries
12353        .iter()
12354        .map(|e| e.source_page_id)
12355        .filter(|i| *i != 0)
12356        .collect();
12357    if !ids.is_empty() {
12358        // Only the pages the submissions came from, not the whole tree;
12359        // in chunks, so a CSV export over many source pages stays under
12360        // every backend's bind-parameter limit.
12361        let ids: Vec<i64> = ids.into_iter().collect();
12362        for chunk in ids.chunks(500) {
12363            match crate::page::Page::objects()
12364                .where_(crate::page::Page::id.is_in(chunk.to_vec()))
12365                .fetch(pool)
12366                .await
12367            {
12368                Ok(pages) => {
12369                    for p in pages {
12370                        if let Some(pid) = p.id.get().copied() {
12371                            page_urls.insert(pid, p.url_path.clone());
12372                        }
12373                    }
12374                }
12375                Err(e) => tracing::warn!(target: "rustango_cms::admin", error = %e, "source-page lookup failed"),
12376            }
12377        }
12378    }
12379    Ok((snippet, columns, entries, page_urls, window))
12380}
12381
12382/// Render one submission answer cell from the `data_json` value.
12383fn submission_cell(data: &serde_json::Value, key: &str) -> String {
12384    match data.get(key) {
12385        Some(serde_json::Value::Array(items)) => items
12386            .iter()
12387            .filter_map(|v| v.as_str().map(str::to_owned))
12388            .collect::<Vec<_>>()
12389            .join("; "),
12390        Some(serde_json::Value::String(s)) => s.clone(),
12391        Some(other) => other.to_string(),
12392        None => String::new(),
12393    }
12394}
12395
12396/// GET `/cms-admin/forms/{id}/submissions` — the per-form submission
12397/// history with a Source-page column.
12398pub async fn form_submissions_list(
12399    State(state): State<super::AdminState>,
12400    tenant: Tenant,
12401    headers: HeaderMap,
12402    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
12403    Path(id): Path<i64>,
12404    Query(paging): Query<crate::admin::pagination::PageQuery>,
12405    axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
12406) -> Result<Response, AdminError> {
12407    let (snippet, columns, entries, page_urls, window) =
12408        load_form_submissions(tenant.pool(), id, Some(&paging)).await?;
12409    let pagination = window.map(|w| w.context).unwrap_or_default();
12410    // Which columns are file uploads → render those cells as download links.
12411    let parsed = crate::forms::schema::parse(&snippet.data).unwrap_or_default();
12412    let file_keys: std::collections::HashSet<String> = parsed
12413        .fields()
12414        .filter(|f| matches!(f.field_type, crate::forms::schema::FieldType::File))
12415        .map(|f| f.key.clone())
12416        .collect();
12417    let rows: Vec<serde_json::Value> = entries
12418        .iter()
12419        .map(|e| {
12420            let cells: Vec<serde_json::Value> = columns
12421                .iter()
12422                .map(|(k, _)| {
12423                    let v = submission_cell(&e.data_json, k);
12424                    if file_keys.contains(k) && !v.is_empty() {
12425                        // value is the storage key; display the filename part.
12426                        let name = v.splitn(2, '-').nth(1).unwrap_or(&v).to_owned();
12427                        serde_json::json!({
12428                            "value": name,
12429                            "url": format!("/cms-admin/forms/{id}/submissions/file/{v}"),
12430                        })
12431                    } else {
12432                        serde_json::json!({ "value": v })
12433                    }
12434                })
12435                .collect();
12436            serde_json::json!({
12437                // RFC 3339, for the admin's `<time data-utc>` localizer; the
12438                // minute-precision text is what shows without JavaScript.
12439                "submitted_at": e
12440                    .submitted_at
12441                    .get()
12442                    .map(|t| t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
12443                    .unwrap_or_default(),
12444                "submitted_at_text": e
12445                    .submitted_at
12446                    .get()
12447                    .map(|t| t.format("%Y-%m-%d %H:%M UTC").to_string())
12448                    .unwrap_or_default(),
12449                "ip": e.ip,
12450                "source_page": if e.source_page_id == 0 {
12451                    serde_json::Value::Null
12452                } else {
12453                    serde_json::json!({
12454                        "id": e.source_page_id,
12455                        "url": page_urls.get(&e.source_page_id).cloned().unwrap_or_default(),
12456                    })
12457                },
12458                "cells": cells,
12459            })
12460        })
12461        .collect();
12462    let mut ctx = Context::new();
12463    add_chrome(&mut ctx, &tenant, "forms", session_user.as_ref()).await;
12464    add_admin_theme(&mut ctx, tenant.pool()).await;
12465    ctx.insert("form_title", &snippet.title);
12466    ctx.insert("form_id", &id);
12467    ctx.insert("build_url", &format!("/cms-admin/forms/{id}/build"));
12468    ctx.insert(
12469        "csv_url",
12470        &format!("/cms-admin/forms/{id}/submissions/export.csv"),
12471    );
12472    ctx.insert(
12473        "columns",
12474        &columns.iter().map(|(_, l)| l).collect::<Vec<_>>(),
12475    );
12476    ctx.insert("rows", &rows);
12477    ctx.insert("total", &pagination["total"]);
12478    ctx.insert("pagination", &pagination);
12479    ctx.insert("query_string", &raw_query.unwrap_or_default());
12480    render_with_csrf(
12481        &state,
12482        &headers,
12483        "rcms_admin/form_submissions.html",
12484        &mut ctx,
12485    )
12486}
12487
12488/// GET `/cms-admin/forms/{id}/submissions/export.csv`.
12489pub async fn form_submissions_csv(
12490    State(_state): State<super::AdminState>,
12491    tenant: Tenant,
12492    Path(id): Path<i64>,
12493) -> Result<Response, AdminError> {
12494    let (snippet, columns, entries, page_urls, _) = load_form_submissions(tenant.pool(), id, None).await?;
12495    let mut out = String::new();
12496    out.push_str("submitted_at,source_page,ip");
12497    for (_, label) in &columns {
12498        out.push(',');
12499        out.push_str(&csv_escape(label));
12500    }
12501    out.push('\n');
12502    for e in &entries {
12503        let when = e
12504            .submitted_at
12505            .get()
12506            .map(ToString::to_string)
12507            .unwrap_or_default();
12508        let src = if e.source_page_id == 0 {
12509            String::new()
12510        } else {
12511            page_urls
12512                .get(&e.source_page_id)
12513                .cloned()
12514                .unwrap_or_default()
12515        };
12516        out.push_str(&csv_escape(&when));
12517        out.push(',');
12518        out.push_str(&csv_escape(&src));
12519        out.push(',');
12520        out.push_str(&csv_escape(&e.ip));
12521        for (k, _) in &columns {
12522            out.push(',');
12523            out.push_str(&csv_escape(&submission_cell(&e.data_json, k)));
12524        }
12525        out.push('\n');
12526    }
12527    let filename = format!("submissions-{}.csv", snippet.slug);
12528    Ok(csv_response(&filename, &out))
12529}
12530
12531/// GET `/cms-admin/forms/{id}/submissions/file/{key}` — download a file
12532/// uploaded through a form submission (admin-gated). Streams from
12533/// `./var/form-uploads/<tenant>/<key>`; rejects path traversal.
12534pub async fn form_submission_file(
12535    State(_state): State<super::AdminState>,
12536    tenant: Tenant,
12537    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
12538    Path((_id, key)): Path<(i64, String)>,
12539) -> Result<Response, AdminError> {
12540    if key.contains('/') || key.contains('\\') || key.contains("..") || key.is_empty() {
12541        return Err(AdminError::NotFound(0));
12542    }
12543    let path = std::path::PathBuf::from("./var/form-uploads")
12544        .join(&tenant.org.slug)
12545        .join(&key);
12546    let bytes = std::fs::read(&path).map_err(|_| AdminError::NotFound(0))?;
12547    let mime = mime_guess::from_path(&key)
12548        .first_or_octet_stream()
12549        .essence_str()
12550        .to_owned();
12551    let download = key.splitn(2, '-').nth(1).unwrap_or(&key).to_owned();
12552    Ok((
12553        [
12554            (header::CONTENT_TYPE, mime),
12555            (
12556                header::CONTENT_DISPOSITION,
12557                format!("attachment; filename=\"{download}\""),
12558            ),
12559        ],
12560        bytes,
12561    )
12562        .into_response())
12563}
12564
12565#[derive(Debug, Deserialize)]
12566pub struct SetLangQuery {
12567    pub lang: String,
12568}
12569
12570/// POST `/cms-admin/set-language` (`lang=<code>`) — persist the sticky
12571/// admin-UI language cookie and the user's durable preference, then
12572/// redirect back to the Referer. POST so a cross-site link can't
12573/// rewrite a signed-in user's preference: it goes through the CSRF check
12574/// like every other admin write.
12575pub async fn admin_set_language(
12576    tenant: Tenant,
12577    headers: HeaderMap,
12578    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
12579    Form(q): Form<SetLangQuery>,
12580) -> Response {
12581    let lang = if super::i18n::is_ui_locale(&q.lang) {
12582        q.lang
12583    } else {
12584        "en".to_owned()
12585    };
12586    // #526 — persist to the user's durable pref too, so the switcher choice
12587    // follows them across devices (not just this browser's cookie). Best-effort:
12588    // a save failure still sets the cookie below.
12589    if let Some(uid) = session_user.as_ref().and_then(|u| u.id.get().copied()) {
12590        persist_user_admin_lang(tenant.pool(), uid, &lang)
12591            .await
12592            .log_warn("admin language preference not saved");
12593    }
12594    // The Referer's path, if it is a local one, else the admin root. The
12595    // path of `https://evil.test//evil.test/x` is `//evil.test/x`, so it
12596    // goes through safe_next like any other redirect target (#728).
12597    let back = headers
12598        .get(header::REFERER)
12599        .and_then(|v| v.to_str().ok())
12600        .and_then(|r| match r.split_once("://") {
12601            Some((_, rest)) => rest.find('/').map(|i| &rest[i..]),
12602            None => Some(r),
12603        })
12604        .and_then(rustango::auth_decorators::safe_next)
12605        .unwrap_or_else(|| "/cms-admin/".to_owned());
12606    let cookie = format!(
12607        "{}={lang}; Path=/; SameSite=Lax; Max-Age=31536000",
12608        super::i18n::ADMIN_LANG_COOKIE
12609    );
12610    let mut resp = axum::response::Redirect::to(&back).into_response();
12611    if let Ok(v) = HeaderValue::from_str(&cookie) {
12612        resp.headers_mut().append(header::SET_COOKIE, v);
12613    }
12614    resp
12615}
12616
12617/// RFC-4180 CSV field escaping: quote when the value contains a comma,
12618/// quote, or newline, doubling any embedded quotes. Shared by every
12619/// admin CSV export (reports, audit log, pages, redirects, …).
12620fn csv_escape(s: &str) -> String {
12621    if s.contains(',') || s.contains('"') || s.contains('\n') || s.contains('\r') {
12622        let mut out = String::with_capacity(s.len() + 2);
12623        out.push('"');
12624        for c in s.chars() {
12625            if c == '"' {
12626                out.push('"');
12627            }
12628            out.push(c);
12629        }
12630        out.push('"');
12631        out
12632    } else {
12633        s.to_owned()
12634    }
12635}
12636
12637/// Stringify a report cell value for display / CSV: strings pass
12638/// through; null / missing → empty; numbers + bools → their literal.
12639fn report_cell_string(v: Option<&serde_json::Value>) -> String {
12640    match v {
12641        Some(serde_json::Value::String(s)) => s.clone(),
12642        None | Some(serde_json::Value::Null) => String::new(),
12643        Some(other) => other.to_string(),
12644    }
12645}
12646
12647pub async fn locale_list(
12648    State(state): State<super::AdminState>,
12649    tenant: Tenant,
12650    headers: HeaderMap,
12651    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
12652) -> Result<Response, AdminError> {
12653    // Not paged: one row per language the site is published in.
12654    let items: Vec<Locale> = Locale::objects()
12655        .order_by(&[("sort_order", false), ("code", false)])
12656        .fetch(tenant.pool())
12657        .await?;
12658    // Enrich each row with core's static support level so the list can warn
12659    // where a content locale outruns the framework (no admin-UI catalog, no
12660    // language-specific plural rule, unknown to core). Serialize the row then
12661    // attach `support` — keeps every existing template field working.
12662    let rows: Vec<serde_json::Value> = items
12663        .iter()
12664        .map(|l| {
12665            let info = rustango::i18n::locale_info(&l.code);
12666            let ui = super::i18n::is_ui_locale(&l.code);
12667            let mut v = serde_json::to_value(l).unwrap_or_default();
12668            v["support"] = serde_json::json!({
12669                "ui_translated": ui,
12670                "known": info.known,
12671                "display_name": info.display_name,
12672                "has_plural_rules": info.has_plural_rules,
12673                "is_rtl": info.is_rtl,
12674                "content_only": !ui,
12675            });
12676            v
12677        })
12678        .collect();
12679    let mut ctx = Context::new();
12680    add_chrome(&mut ctx, &tenant, "locales", session_user.as_ref()).await;
12681    add_admin_theme(&mut ctx, tenant.pool()).await;
12682    ctx.insert("items", &rows);
12683    render_with_csrf(&state, &headers, "rcms_admin/locale_list.html", &mut ctx)
12684}
12685
12686/// Inject core's known-locale roster into a locale-form context: a
12687/// `known_locales` list (`code`, `name`) for the code datalist, and a
12688/// `known_locales_meta` map (`code → {ui, is_rtl, has_plural_rules}`) the
12689/// form JS reads to show a live support hint. Free-text codes stay valid;
12690/// this is guidance, not a whitelist.
12691fn insert_known_locales(ctx: &mut Context) {
12692    let known: Vec<serde_json::Value> = rustango::i18n::known_locales()
12693        .map(|(code, name)| serde_json::json!({ "code": code, "name": name }))
12694        .collect();
12695    let meta: serde_json::Map<String, serde_json::Value> = rustango::i18n::known_locales()
12696        .map(|(code, _)| {
12697            let info = rustango::i18n::locale_info(code);
12698            (
12699                code.to_owned(),
12700                serde_json::json!({
12701                    "ui": super::i18n::is_ui_locale(code),
12702                    "is_rtl": info.is_rtl,
12703                    "has_plural_rules": info.has_plural_rules,
12704                }),
12705            )
12706        })
12707        .collect();
12708    ctx.insert("known_locales", &known);
12709    ctx.insert("known_locales_meta", &serde_json::Value::Object(meta));
12710}
12711
12712pub async fn locale_new_form(
12713    State(state): State<super::AdminState>,
12714    tenant: Tenant,
12715    headers: HeaderMap,
12716    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
12717) -> Result<Response, AdminError> {
12718    let mut ctx = Context::new();
12719    add_chrome(&mut ctx, &tenant, "locales", session_user.as_ref()).await;
12720    add_admin_theme(&mut ctx, tenant.pool()).await;
12721    insert_known_locales(&mut ctx);
12722    ctx.insert("mode", "new");
12723    ctx.insert(
12724        "locale",
12725        &serde_json::json!({
12726            "code": "",
12727            "name": "",
12728            "is_default": false,
12729            "active": true,
12730            "sort_order": 100,
12731        }),
12732    );
12733    render_with_csrf(&state, &headers, "rcms_admin/locale_form.html", &mut ctx)
12734}
12735
12736#[derive(Debug, Deserialize)]
12737pub struct LocaleForm {
12738    pub code: String,
12739    pub name: String,
12740    #[serde(default)]
12741    pub is_default: Option<String>,
12742    #[serde(default)]
12743    pub active: Option<String>,
12744    #[serde(default)]
12745    pub sort_order: Option<i32>,
12746}
12747
12748impl LocaleForm {
12749    fn parsed_default(&self) -> bool {
12750        self.is_default.is_some()
12751    }
12752    fn parsed_active(&self) -> bool {
12753        self.active.is_some()
12754    }
12755    fn parsed_sort_order(&self) -> i32 {
12756        self.sort_order.unwrap_or(100)
12757    }
12758}
12759
12760pub async fn locale_new_submit(
12761    State(_state): State<super::AdminState>,
12762    tenant: Tenant,
12763    headers: HeaderMap,
12764    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
12765    Form(form): Form<LocaleForm>,
12766) -> Result<Response, AdminError> {
12767    use rustango::sql::Auto;
12768    let name = form.name.trim().to_owned();
12769    if name.is_empty() {
12770        return Err(AdminError::Validation(
12771            "Display name is required.".to_owned(),
12772        ));
12773    }
12774    let mut row = Locale {
12775        id: Auto::Unset,
12776        code: crate::locale::validate_code(&form.code).map_err(AdminError::Validation)?,
12777        name,
12778        is_default: form.parsed_default(),
12779        active: form.parsed_active(),
12780        sort_order: form.parsed_sort_order(),
12781        created_at: Auto::Unset,
12782    };
12783    if row.is_default {
12784        clear_default_flag(&tenant, None).await?;
12785    }
12786    row.insert(tenant.pool()).await?;
12787    redirect_named_with_message_args(
12788        "rcms-admin:locales:list",
12789        MsgLevel::Success,
12790        "Added locale {name} ({code}).",
12791        &[("name", row.name.as_str()), ("code", row.code.as_str())],
12792        &headers,
12793    )
12794}
12795
12796pub async fn locale_edit_form(
12797    State(state): State<super::AdminState>,
12798    tenant: Tenant,
12799    headers: HeaderMap,
12800    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
12801    Path(id): Path<i64>,
12802) -> Result<Response, AdminError> {
12803    let row = Locale::objects()
12804        .where_(Locale::id.eq(id))
12805        .first(tenant.pool())
12806        .await?
12807        .ok_or(AdminError::NotFound(id))?;
12808    let mut ctx = Context::new();
12809    add_chrome(&mut ctx, &tenant, "locales", session_user.as_ref()).await;
12810    add_admin_theme(&mut ctx, tenant.pool()).await;
12811    insert_known_locales(&mut ctx);
12812    ctx.insert("mode", "edit");
12813    ctx.insert("locale", &row);
12814    render_with_csrf(&state, &headers, "rcms_admin/locale_form.html", &mut ctx)
12815}
12816
12817pub async fn locale_edit_submit(
12818    State(_state): State<super::AdminState>,
12819    tenant: Tenant,
12820    headers: HeaderMap,
12821    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
12822    Path(id): Path<i64>,
12823    Form(form): Form<LocaleForm>,
12824) -> Result<Response, AdminError> {
12825    let mut row = Locale::objects()
12826        .where_(Locale::id.eq(id))
12827        .first(tenant.pool())
12828        .await?
12829        .ok_or(AdminError::NotFound(id))?;
12830    let name = form.name.trim().to_owned();
12831    if name.is_empty() {
12832        return Err(AdminError::Validation(
12833            "Display name is required.".to_owned(),
12834        ));
12835    }
12836    row.code = crate::locale::validate_code(&form.code).map_err(AdminError::Validation)?;
12837    row.name = name;
12838    row.is_default = form.parsed_default();
12839    row.active = form.parsed_active();
12840    row.sort_order = form.parsed_sort_order();
12841    if row.is_default {
12842        clear_default_flag(&tenant, Some(id)).await?;
12843    }
12844    row.save(tenant.pool()).await?;
12845    redirect_named_with_message_args(
12846        "rcms-admin:locales:list",
12847        MsgLevel::Success,
12848        "Saved locale {name} ({code}).",
12849        &[("name", row.name.as_str()), ("code", row.code.as_str())],
12850        &headers,
12851    )
12852}
12853
12854pub async fn locale_delete_submit(
12855    State(_state): State<super::AdminState>,
12856    tenant: Tenant,
12857    headers: HeaderMap,
12858    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
12859    Path(id): Path<i64>,
12860) -> Result<Response, AdminError> {
12861    let row = Locale::objects()
12862        .where_(Locale::id.eq(id))
12863        .first(tenant.pool())
12864        .await?
12865        .ok_or(AdminError::NotFound(id))?;
12866    if row.is_default {
12867        return redirect_named_with_message(
12868            "rcms-admin:locales:list",
12869            MsgLevel::Error,
12870            "Cannot delete the default locale — promote another locale to default first.",
12871            &headers,
12872        );
12873    }
12874    let label = format!("{} ({})", row.name, row.code);
12875    // Translations reference the locale; they go with it, in one step,
12876    // or the foreign keys refuse the delete.
12877    let pages = crate::translation::Translation::objects()
12878        .where_(crate::translation::Translation::locale_id.eq(id))
12879        .compile_delete()
12880        .map_err(rustango::sql::ExecError::from)?;
12881    let snippets = crate::snippet_translation::SnippetTranslation::objects()
12882        .where_(crate::snippet_translation::SnippetTranslation::locale_id.eq(id))
12883        .compile_delete()
12884        .map_err(rustango::sql::ExecError::from)?;
12885    let menus = crate::menu_item_translation::MenuItemTranslation::objects()
12886        .where_(crate::menu_item_translation::MenuItemTranslation::locale_id.eq(id))
12887        .compile_delete()
12888        .map_err(rustango::sql::ExecError::from)?;
12889    let categories = crate::category_translation::CategoryTranslation::objects()
12890        .where_(crate::category_translation::CategoryTranslation::locale_id.eq(id))
12891        .compile_delete()
12892        .map_err(rustango::sql::ExecError::from)?;
12893    rustango::atomic!(tenant.pool(), |tx| {
12894        let mut guard = tx.lock().await?;
12895        let tx = &mut *guard;
12896        for q in [&pages, &snippets, &menus, &categories] {
12897            rustango::sql::delete_tx(tx, q).await?;
12898        }
12899        row.delete_tx(tx).await?;
12900        Ok::<_, rustango::sql::ExecError>(())
12901    })
12902    .await?;
12903    redirect_named_with_message_args(
12904        "rcms-admin:locales:list",
12905        MsgLevel::Success,
12906        "Deleted locale {label}.",
12907        &[("label", label.as_str())],
12908        &headers,
12909    )
12910}
12911
12912// ============================================================ SSO Providers
12913//
12914// Admin-managed, DB-backed multi-provider SSO (the framework's
12915// `rustango::admin::SsoProvider`, one row per configurable OIDC/social
12916// provider). Each enabled row becomes a "Sign in with …" button on the
12917// login page (`/login/sso/{slug}`). This is the UI that replaces hand-
12918// editing `rustango_sso_providers` — mirrors the Locales CRUD.
12919
12920/// Built-in provider presets offered in the `kind` dropdown, plus generic
12921/// `oidc` (needs an issuer URL). Free-text isn't allowed — the framework
12922/// only knows these preset keys + `oidc`.
12923const SSO_KINDS: &[(&str, &str)] = &[
12924    ("google", "Google"),
12925    ("microsoft", "Microsoft"),
12926    ("github", "GitHub"),
12927    ("gitlab", "GitLab"),
12928    ("discord", "Discord"),
12929    ("oidc", "Generic OpenID Connect"),
12930];
12931
12932/// Serialize a `SsoProvider` row to JSON for the templates. The framework
12933/// model isn't `Serialize`, so map the fields by hand.
12934fn sso_provider_json(p: &rustango::admin::SsoProvider) -> serde_json::Value {
12935    serde_json::json!({
12936        "id": p.id.get().copied().unwrap_or_default(),
12937        "slug": p.slug,
12938        "label": p.label,
12939        "kind": p.kind,
12940        "issuer_url": p.issuer_url,
12941        "client_id": p.client_id,
12942        // Never surface the secret itself — just whether one is set (for the
12943        // edit form's "leave blank to keep" hint).
12944        "has_secret": !p.client_secret.is_empty(),
12945        "enabled": p.enabled,
12946        "sort_order": p.sort_order,
12947        "scopes": p.scopes,
12948    })
12949}
12950
12951pub async fn sso_provider_list(
12952    State(state): State<super::AdminState>,
12953    tenant: Tenant,
12954    headers: HeaderMap,
12955    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
12956) -> Result<Response, AdminError> {
12957    // Identity administration is superuser-only (#672).
12958    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
12959        return Ok(redirect);
12960    }
12961    use rustango::sql::FetcherPool as _;
12962    // Not paged: one row per identity provider configured for sign-in.
12963    let mut items: Vec<rustango::admin::SsoProvider> = rustango::admin::SsoProvider::objects()
12964        .fetch(tenant.pool())
12965        .await
12966        .unwrap_or_default();
12967    items.sort_by(|a, b| a.sort_order.cmp(&b.sort_order).then(a.slug.cmp(&b.slug)));
12968    let rows: Vec<serde_json::Value> = items.iter().map(sso_provider_json).collect();
12969    let mut ctx = Context::new();
12970    add_chrome(&mut ctx, &tenant, "sso-providers", session_user.as_ref()).await;
12971    add_admin_theme(&mut ctx, tenant.pool()).await;
12972    ctx.insert("items", &rows);
12973    render_with_csrf(
12974        &state,
12975        &headers,
12976        "rcms_admin/sso_provider_list.html",
12977        &mut ctx,
12978    )
12979}
12980
12981#[derive(Deserialize)]
12982pub struct SsoProviderForm {
12983    pub slug: String,
12984    pub label: String,
12985    pub kind: String,
12986    #[serde(default)]
12987    pub issuer_url: String,
12988    pub client_id: String,
12989    /// The raw OAuth client secret. On edit, blank means "keep the current one"
12990    /// (the field is never pre-filled — it's write-only).
12991    #[serde(default)]
12992    pub client_secret: String,
12993    #[serde(default)]
12994    pub scopes: String,
12995    #[serde(default)]
12996    pub enabled: Option<String>,
12997    #[serde(default)]
12998    pub sort_order: Option<i32>,
12999}
13000
13001impl SsoProviderForm {
13002    /// Validate + normalize the form into field values, or an error message.
13003    fn validated(&self) -> Result<ValidatedProvider, String> {
13004        let slug = self.slug.trim().to_lowercase();
13005        if slug.is_empty()
13006            || !slug
13007                .chars()
13008                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
13009        {
13010            return Err(
13011                "Slug is required and may only contain letters, numbers, - and _.".to_owned(),
13012            );
13013        }
13014        let label = self.label.trim().to_owned();
13015        if label.is_empty() {
13016            return Err("Button label is required.".to_owned());
13017        }
13018        let kind = self.kind.trim().to_lowercase();
13019        if !SSO_KINDS.iter().any(|(k, _)| *k == kind) {
13020            return Err("Pick a provider type.".to_owned());
13021        }
13022        let client_id = self.client_id.trim().to_owned();
13023        if client_id.is_empty() {
13024            return Err("Client ID is required.".to_owned());
13025        }
13026        let issuer = self.issuer_url.trim().to_owned();
13027        if kind == "oidc" && issuer.is_empty() {
13028            return Err("A generic OpenID Connect provider needs an issuer URL.".to_owned());
13029        }
13030        let scopes = self.scopes.trim().to_owned();
13031        Ok(ValidatedProvider {
13032            slug,
13033            label,
13034            kind,
13035            issuer_url: (!issuer.is_empty()).then_some(issuer),
13036            client_id,
13037            scopes: (!scopes.is_empty()).then_some(scopes),
13038            enabled: self.enabled.is_some(),
13039            sort_order: self.sort_order.unwrap_or(0),
13040        })
13041    }
13042}
13043
13044struct ValidatedProvider {
13045    slug: String,
13046    label: String,
13047    kind: String,
13048    issuer_url: Option<String>,
13049    client_id: String,
13050    scopes: Option<String>,
13051    enabled: bool,
13052    sort_order: i32,
13053}
13054
13055fn render_sso_provider_form(ctx: &mut Context, mode: &str, provider: serde_json::Value) {
13056    let kinds: Vec<serde_json::Value> = SSO_KINDS
13057        .iter()
13058        .map(|(k, name)| serde_json::json!({ "key": k, "name": name }))
13059        .collect();
13060    ctx.insert("mode", mode);
13061    ctx.insert("kinds", &kinds);
13062    ctx.insert("provider", &provider);
13063}
13064
13065pub async fn sso_provider_new_form(
13066    State(state): State<super::AdminState>,
13067    tenant: Tenant,
13068    headers: HeaderMap,
13069    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
13070) -> Result<Response, AdminError> {
13071    // Identity administration is superuser-only (#672).
13072    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
13073        return Ok(redirect);
13074    }
13075    let mut ctx = Context::new();
13076    add_chrome(&mut ctx, &tenant, "sso-providers", session_user.as_ref()).await;
13077    add_admin_theme(&mut ctx, tenant.pool()).await;
13078    render_sso_provider_form(
13079        &mut ctx,
13080        "new",
13081        serde_json::json!({
13082            "slug": "", "label": "", "kind": "google", "issuer_url": null,
13083            "client_id": "", "has_secret": false, "scopes": null,
13084            "enabled": true, "sort_order": 0,
13085        }),
13086    );
13087    render_with_csrf(
13088        &state,
13089        &headers,
13090        "rcms_admin/sso_provider_form.html",
13091        &mut ctx,
13092    )
13093}
13094
13095async fn find_sso_provider(
13096    tenant: &Tenant,
13097    id: i64,
13098) -> Result<rustango::admin::SsoProvider, AdminError> {
13099    use rustango::sql::FetcherPool as _;
13100    rustango::admin::SsoProvider::objects()
13101        .filter("id", id)
13102        .fetch(tenant.pool())
13103        .await
13104        .map_err(|e| AdminError::Validation(format!("db: {e}")))?
13105        .into_iter()
13106        .next()
13107        .ok_or(AdminError::NotFound(id))
13108}
13109
13110pub async fn sso_provider_edit_form(
13111    State(state): State<super::AdminState>,
13112    tenant: Tenant,
13113    headers: HeaderMap,
13114    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
13115    Path(id): Path<i64>,
13116) -> Result<Response, AdminError> {
13117    // Identity administration is superuser-only (#672).
13118    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
13119        return Ok(redirect);
13120    }
13121    let row = find_sso_provider(&tenant, id).await?;
13122    let mut ctx = Context::new();
13123    add_chrome(&mut ctx, &tenant, "sso-providers", session_user.as_ref()).await;
13124    add_admin_theme(&mut ctx, tenant.pool()).await;
13125    render_sso_provider_form(&mut ctx, "edit", sso_provider_json(&row));
13126    render_with_csrf(
13127        &state,
13128        &headers,
13129        "rcms_admin/sso_provider_form.html",
13130        &mut ctx,
13131    )
13132}
13133
13134pub async fn sso_provider_new_submit(
13135    State(_state): State<super::AdminState>,
13136    tenant: Tenant,
13137    headers: HeaderMap,
13138    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
13139    Form(form): Form<SsoProviderForm>,
13140) -> Result<Response, AdminError> {
13141    // Identity administration is superuser-only (#672).
13142    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
13143        return Ok(redirect);
13144    }
13145    let v = form.validated().map_err(AdminError::Validation)?;
13146    let secret = form.client_secret.trim().to_owned();
13147    if secret.is_empty() {
13148        return Err(AdminError::Validation(
13149            "Client secret is required.".to_owned(),
13150        ));
13151    }
13152    let mut row = rustango::admin::SsoProvider {
13153        id: rustango::sql::Auto::Unset,
13154        slug: v.slug,
13155        label: v.label,
13156        kind: v.kind,
13157        issuer_url: v.issuer_url,
13158        client_id: v.client_id,
13159        client_secret: rustango::casts::Cast::new(secret),
13160        enabled: v.enabled,
13161        sort_order: v.sort_order,
13162        scopes: v.scopes,
13163        allow_email_link: false,
13164        // 0.62 policy columns, at their column defaults.
13165        allowed_email_domains: None,
13166        blocked_email_domains: None,
13167        allowed_idp_tenants: None,
13168        allowed_hosted_domains: None,
13169        required_claims: serde_json::json!({}),
13170        signup_mode: None,
13171        default_roles: None,
13172        role_map: serde_json::json!({}),
13173        role_claims: None,
13174        sync_roles_on_login: false,
13175        username_from: "email_local".to_owned(),
13176        username_clash: "suffix".to_owned(),
13177        sync_profile: false,
13178        allow_email_link_staff: false,
13179        sso_only: false,
13180        auto_deactivate_after_days: None,
13181        session_ttl_secs: None,
13182        superuser_session_ttl_secs: None,
13183        created_at: rustango::sql::Auto::Unset,
13184        updated_at: rustango::sql::Auto::Unset,
13185    };
13186    row.insert(tenant.pool()).await?;
13187    redirect_named_with_message_args(
13188        "rcms-admin:sso-providers:list",
13189        MsgLevel::Success,
13190        "Added SSO provider {label}.",
13191        &[("label", row.label.as_str())],
13192        &headers,
13193    )
13194}
13195
13196pub async fn sso_provider_edit_submit(
13197    State(_state): State<super::AdminState>,
13198    tenant: Tenant,
13199    headers: HeaderMap,
13200    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
13201    Path(id): Path<i64>,
13202    Form(form): Form<SsoProviderForm>,
13203) -> Result<Response, AdminError> {
13204    // Identity administration is superuser-only (#672).
13205    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
13206        return Ok(redirect);
13207    }
13208    let mut row = find_sso_provider(&tenant, id).await?;
13209    let v = form.validated().map_err(AdminError::Validation)?;
13210    row.slug = v.slug;
13211    row.label = v.label;
13212    row.kind = v.kind;
13213    row.issuer_url = v.issuer_url;
13214    row.client_id = v.client_id;
13215    // Write-only secret: only replace it when a new one was typed; a blank
13216    // field keeps the stored (encrypted) value.
13217    let new_secret = form.client_secret.trim();
13218    if !new_secret.is_empty() {
13219        row.client_secret = rustango::casts::Cast::new(new_secret.to_owned());
13220    }
13221    row.enabled = v.enabled;
13222    row.sort_order = v.sort_order;
13223    row.scopes = v.scopes;
13224    row.save(tenant.pool()).await?;
13225    redirect_named_with_message_args(
13226        "rcms-admin:sso-providers:list",
13227        MsgLevel::Success,
13228        "Saved SSO provider {label}.",
13229        &[("label", row.label.as_str())],
13230        &headers,
13231    )
13232}
13233
13234pub async fn sso_provider_delete_submit(
13235    State(_state): State<super::AdminState>,
13236    tenant: Tenant,
13237    headers: HeaderMap,
13238    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
13239    Path(id): Path<i64>,
13240) -> Result<Response, AdminError> {
13241    // Identity administration is superuser-only (#672).
13242    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
13243        return Ok(redirect);
13244    }
13245    let row = find_sso_provider(&tenant, id).await?;
13246    let label = row.label.clone();
13247    row.delete(tenant.pool()).await?;
13248    redirect_named_with_message_args(
13249        "rcms-admin:sso-providers:list",
13250        MsgLevel::Success,
13251        "Deleted SSO provider {label}.",
13252        &[("label", label.as_str())],
13253        &headers,
13254    )
13255}
13256
13257/// Clear `is_default = true` on every other row so the new default
13258/// row owns the flag uniquely. Optionally exclude an id when
13259/// editing the same row.
13260async fn clear_default_flag(tenant: &Tenant, except: Option<i64>) -> Result<(), AdminError> {
13261    let rows: Vec<Locale> = Locale::objects()
13262        .where_(Locale::is_default.eq(true))
13263        .fetch(tenant.pool())
13264        .await?;
13265    for mut r in rows {
13266        if let (Some(skip), Some(id)) = (except, r.id.get().copied()) {
13267            if skip == id {
13268                continue;
13269            }
13270        }
13271        r.is_default = false;
13272        r.save(tenant.pool()).await?;
13273    }
13274    Ok(())
13275}
13276
13277// =====================================================================
13278// Workflows — multi-step approval CRUD (#73 PR 1)
13279// =====================================================================
13280
13281pub async fn workflows_list(
13282    State(state): State<super::AdminState>,
13283    tenant: Tenant,
13284    headers: HeaderMap,
13285    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
13286) -> Result<Response, AdminError> {
13287    let items: Vec<crate::workflow::Workflow> = crate::workflow::Workflow::objects()
13288        .order_by(&[("name", false)])
13289        .fetch(tenant.pool())
13290        .await?;
13291    // Task counts per workflow — surfaced in the list as a quick
13292    // indicator. One query for all tasks; bucket client-side.
13293    let all_tasks: Vec<crate::workflow::WorkflowTask> = crate::workflow::WorkflowTask::objects()
13294        .fetch(tenant.pool())
13295        .await?;
13296    let mut task_counts: std::collections::HashMap<i64, usize> = std::collections::HashMap::new();
13297    for t in &all_tasks {
13298        *task_counts.entry(t.workflow_id).or_insert(0) += 1;
13299    }
13300    let rows: Vec<serde_json::Value> = items
13301        .iter()
13302        .map(|w| {
13303            let id = w.id.get().copied().unwrap_or_default();
13304            serde_json::json!({
13305                "id": id,
13306                "name": w.name,
13307                "description": w.description,
13308                "active": w.active,
13309                "require_reapproval_on_edit": w.require_reapproval_on_edit,
13310                "task_count": task_counts.get(&id).copied().unwrap_or(0),
13311                "created_at": w.created_at.get().copied(),
13312            })
13313        })
13314        .collect();
13315    let mut ctx = Context::new();
13316    add_chrome(&mut ctx, &tenant, "workflows", session_user.as_ref()).await;
13317    add_admin_theme(&mut ctx, tenant.pool()).await;
13318    ctx.insert("items", &rows);
13319    render_with_csrf(&state, &headers, "rcms_admin/workflow_list.html", &mut ctx)
13320}
13321
13322pub async fn workflow_new_form(
13323    State(state): State<super::AdminState>,
13324    tenant: Tenant,
13325    headers: HeaderMap,
13326    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
13327) -> Result<Response, AdminError> {
13328    let mut ctx = Context::new();
13329    add_chrome(&mut ctx, &tenant, "workflows", session_user.as_ref()).await;
13330    add_admin_theme(&mut ctx, tenant.pool()).await;
13331    ctx.insert("mode", "new");
13332    ctx.insert(
13333        "workflow",
13334        &serde_json::json!({
13335            "name": "",
13336            "description": "",
13337            "active": true,
13338            "require_reapproval_on_edit": false,
13339        }),
13340    );
13341    ctx.insert("tasks", &Vec::<serde_json::Value>::new());
13342    ctx.insert("roles", &Vec::<serde_json::Value>::new());
13343    render_with_csrf(&state, &headers, "rcms_admin/workflow_form.html", &mut ctx)
13344}
13345
13346#[derive(Debug, Deserialize)]
13347pub struct WorkflowForm {
13348    pub name: String,
13349    #[serde(default)]
13350    pub description: String,
13351    #[serde(default)]
13352    pub active: Option<String>,
13353    #[serde(default)]
13354    pub require_reapproval_on_edit: Option<String>,
13355}
13356
13357impl WorkflowForm {
13358    fn parsed_active(&self) -> bool {
13359        self.active.is_some()
13360    }
13361    fn parsed_reapproval(&self) -> bool {
13362        self.require_reapproval_on_edit.is_some()
13363    }
13364}
13365
13366pub async fn workflow_new_submit(
13367    State(_state): State<super::AdminState>,
13368    tenant: Tenant,
13369    headers: HeaderMap,
13370    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
13371    Form(form): Form<WorkflowForm>,
13372) -> Result<Response, AdminError> {
13373    use rustango::sql::Auto;
13374    let name = form.name.trim().to_owned();
13375    if name.is_empty() {
13376        return redirect_named_with_message(
13377            "rcms-admin:workflows:list",
13378            MsgLevel::Error,
13379            "Workflow name is required.",
13380            &headers,
13381        );
13382    }
13383    let mut row = crate::workflow::Workflow {
13384        id: Auto::Unset,
13385        name: name.clone(),
13386        description: form.description.trim().to_owned(),
13387        active: form.parsed_active(),
13388        require_reapproval_on_edit: form.parsed_reapproval(),
13389        created_at: Auto::Unset,
13390        updated_at: Auto::Unset,
13391    };
13392    row.insert(tenant.pool()).await?;
13393    let id = row.id.get().copied().unwrap_or_default();
13394    redirect_named_with_params_and_message_args(
13395        "rcms-admin:workflows:edit",
13396        &[("id", id.to_string())],
13397        MsgLevel::Success,
13398        "Created workflow “{name}”. Add review steps below.",
13399        &[("name", name.as_str())],
13400        &headers,
13401    )
13402}
13403
13404pub async fn workflow_edit_form(
13405    State(state): State<super::AdminState>,
13406    tenant: Tenant,
13407    headers: HeaderMap,
13408    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
13409    Path(id): Path<i64>,
13410) -> Result<Response, AdminError> {
13411    let row = crate::workflow::Workflow::objects()
13412        .where_(crate::workflow::Workflow::id.eq(id))
13413        .first(tenant.pool())
13414        .await?
13415        .ok_or(AdminError::NotFound(id))?;
13416    let tasks: Vec<crate::workflow::WorkflowTask> = crate::workflow::WorkflowTask::objects()
13417        .where_(crate::workflow::WorkflowTask::workflow_id.eq(id))
13418        .order_by(&[("sort_order", false), ("id", false)])
13419        .fetch(tenant.pool())
13420        .await?;
13421    // Role picker — every tenant role is a valid assignee for a
13422    // task. Sort alphabetically for predictable ordering.
13423    let roles: Vec<rustango::tenancy::permissions::Role> =
13424        rustango::tenancy::permissions::Role::objects()
13425            .order_by(&[("name", false)])
13426            .fetch(tenant.pool())
13427            .await?;
13428    let role_rows: Vec<serde_json::Value> = roles
13429        .iter()
13430        .map(|r| {
13431            serde_json::json!({
13432                "id": r.id.get().copied(),
13433                "name": r.name,
13434            })
13435        })
13436        .collect();
13437    let role_by_id: std::collections::HashMap<i64, String> = roles
13438        .iter()
13439        .filter_map(|r| r.id.get().copied().map(|id| (id, r.name.clone())))
13440        .collect();
13441    let task_rows: Vec<serde_json::Value> = tasks
13442        .iter()
13443        .map(|t| {
13444            serde_json::json!({
13445                "id": t.id.get().copied(),
13446                "name": t.name,
13447                "role_id": t.role_id,
13448                "role_name": role_by_id.get(&t.role_id).cloned().unwrap_or_default(),
13449                "sort_order": t.sort_order,
13450                "kind": t.kind,
13451                "webhook_url": t.webhook_url,
13452            })
13453        })
13454        .collect();
13455    // #191 — every registered task kind, surfaced to the template
13456    // so the Add-step form can offer the kind picker.
13457    // A person's approval first: it's what a review step normally is,
13458    // and the pre-selected kind.
13459    let mut task_kinds: Vec<serde_json::Value> = crate::task_kind::registered_kinds()
13460        .iter()
13461        .map(|k| {
13462            serde_json::json!({
13463                "name": k.kind_name(),
13464                "verbose_name": k.verbose_name(),
13465            })
13466        })
13467        .collect();
13468    task_kinds.sort_by_key(|k| k["name"] != "group_approval");
13469    let kind_label = |name: &str| {
13470        crate::task_kind::registered_kinds()
13471            .iter()
13472            .find(|k| k.kind_name() == name)
13473            .map_or_else(|| name.to_owned(), |k| k.verbose_name().to_owned())
13474    };
13475    let task_rows: Vec<serde_json::Value> = task_rows
13476        .into_iter()
13477        .map(|mut t| {
13478            let label = kind_label(t["kind"].as_str().unwrap_or_default());
13479            t["kind_label"] = serde_json::Value::String(label);
13480            t
13481        })
13482        .collect();
13483    let mut ctx = Context::new();
13484    add_chrome(&mut ctx, &tenant, "workflows", session_user.as_ref()).await;
13485    add_admin_theme(&mut ctx, tenant.pool()).await;
13486    ctx.insert("mode", "edit");
13487    ctx.insert("workflow", &row);
13488    ctx.insert("tasks", &task_rows);
13489    ctx.insert("roles", &role_rows);
13490    ctx.insert("task_kinds", &task_kinds);
13491    render_with_csrf(&state, &headers, "rcms_admin/workflow_form.html", &mut ctx)
13492}
13493
13494pub async fn workflow_edit_submit(
13495    State(_state): State<super::AdminState>,
13496    tenant: Tenant,
13497    headers: HeaderMap,
13498    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
13499    Path(id): Path<i64>,
13500    Form(form): Form<WorkflowForm>,
13501) -> Result<Response, AdminError> {
13502    let mut row = crate::workflow::Workflow::objects()
13503        .where_(crate::workflow::Workflow::id.eq(id))
13504        .first(tenant.pool())
13505        .await?
13506        .ok_or(AdminError::NotFound(id))?;
13507    let old_name = row.name.clone();
13508    row.name = form.name.trim().to_owned();
13509    row.description = form.description.trim().to_owned();
13510    row.active = form.parsed_active();
13511    row.require_reapproval_on_edit = form.parsed_reapproval();
13512    row.save(tenant.pool()).await?;
13513    // Page types name their workflow; a rename must move them along, or
13514    // their pages would silently publish without review.
13515    if old_name != row.name {
13516        crate::workflow::rebind_page_types(tenant.pool(), &old_name, &row.name).await?;
13517    }
13518    redirect_named_with_params_and_message_args(
13519        "rcms-admin:workflows:edit",
13520        &[("id", id.to_string())],
13521        MsgLevel::Success,
13522        "Saved workflow “{name}”.",
13523        &[("name", row.name.as_str())],
13524        &headers,
13525    )
13526}
13527
13528pub async fn workflow_delete_submit(
13529    State(_state): State<super::AdminState>,
13530    tenant: Tenant,
13531    headers: HeaderMap,
13532    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
13533    Path(id): Path<i64>,
13534) -> Result<Response, AdminError> {
13535    let row = crate::workflow::Workflow::objects()
13536        .where_(crate::workflow::Workflow::id.eq(id))
13537        .first(tenant.pool())
13538        .await?
13539        .ok_or(AdminError::NotFound(id))?;
13540    // Page types that use it would quietly stop requiring review.
13541    let users: Vec<String> = crate::workflow::page_types_using(tenant.pool(), &row.name)
13542        .await?
13543        .into_iter()
13544        .map(|pt| pt.verbose_name)
13545        .collect();
13546    if !users.is_empty() {
13547        let types = users.join(", ");
13548        return redirect_named_with_message_args(
13549            "rcms-admin:workflows:list",
13550            MsgLevel::Error,
13551            "Can't delete “{title}” — the page types {types} use it. Choose another workflow for them first.",
13552            &[("title", row.name.as_str()), ("types", types.as_str())],
13553            &headers,
13554        );
13555    }
13556    // Reject when any WorkflowState references this workflow — the
13557    // audit trail would otherwise lose its parent FK. Editors should
13558    // toggle `active = false` instead.
13559    let in_use: Vec<crate::workflow::WorkflowState> = crate::workflow::WorkflowState::objects()
13560        .where_(crate::workflow::WorkflowState::workflow_id.eq(id))
13561        .fetch(tenant.pool())
13562        .await?;
13563    if !in_use.is_empty() {
13564        let count = in_use.len().to_string();
13565        return redirect_named_with_message_plural(
13566            "rcms-admin:workflows:list",
13567            MsgLevel::Error,
13568            "Can't delete “{title}” — {count} page(s) have history under it. Toggle Active off instead.",
13569            in_use.len() as i64,
13570            &[("title", row.name.as_str()), ("count", count.as_str())],
13571            &headers,
13572        );
13573    }
13574    // Cascade the task rows by hand (FK isn't ON DELETE CASCADE).
13575    let tasks: Vec<crate::workflow::WorkflowTask> = crate::workflow::WorkflowTask::objects()
13576        .where_(crate::workflow::WorkflowTask::workflow_id.eq(id))
13577        .fetch(tenant.pool())
13578        .await?;
13579    for t in tasks {
13580        t.delete(tenant.pool()).await?;
13581    }
13582    let name = row.name.clone();
13583    row.delete(tenant.pool()).await?;
13584    redirect_named_with_message_args(
13585        "rcms-admin:workflows:list",
13586        MsgLevel::Success,
13587        "Deleted workflow “{name}”.",
13588        &[("name", name.as_str())],
13589        &headers,
13590    )
13591}
13592
13593#[derive(Debug, Deserialize)]
13594pub struct WorkflowTaskForm {
13595    pub name: String,
13596    pub role_id: i64,
13597    /// Task kind discriminator. Defaults to `group_approval`
13598    /// when the form input is missing or empty so the existing
13599    /// human-approval flow stays the default behavior.
13600    #[serde(default)]
13601    pub kind: Option<String>,
13602    #[serde(default)]
13603    pub webhook_url: Option<String>,
13604}
13605
13606pub async fn workflow_task_add(
13607    State(_state): State<super::AdminState>,
13608    tenant: Tenant,
13609    headers: HeaderMap,
13610    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
13611    Path(workflow_id): Path<i64>,
13612    Form(form): Form<WorkflowTaskForm>,
13613) -> Result<Response, AdminError> {
13614    use rustango::sql::Auto;
13615    let name = form.name.trim().to_owned();
13616    if name.is_empty() {
13617        return redirect_named_with_params_and_message(
13618            "rcms-admin:workflows:edit",
13619            &[("id", workflow_id.to_string())],
13620            MsgLevel::Error,
13621            "Step name is required.",
13622            &headers,
13623        );
13624    }
13625    let existing: Vec<crate::workflow::WorkflowTask> = crate::workflow::WorkflowTask::objects()
13626        .where_(crate::workflow::WorkflowTask::workflow_id.eq(workflow_id))
13627        .order_by(&[("sort_order", true)]) // desc
13628        .fetch(tenant.pool())
13629        .await?;
13630    let next_order = existing.first().map_or(10, |t| t.sort_order + 10);
13631    let kind = form
13632        .kind
13633        .as_deref()
13634        .map(str::trim)
13635        .filter(|s| !s.is_empty())
13636        .filter(|s| crate::task_kind::find(s).is_some())
13637        .unwrap_or("group_approval")
13638        .to_owned();
13639    let webhook_url = form
13640        .webhook_url
13641        .as_deref()
13642        .map(str::trim)
13643        .unwrap_or("")
13644        .to_owned();
13645    let mut row = crate::workflow::WorkflowTask {
13646        id: Auto::Unset,
13647        workflow_id,
13648        name: name.clone(),
13649        role_id: form.role_id,
13650        sort_order: next_order,
13651        kind,
13652        webhook_url,
13653    };
13654    row.insert(tenant.pool()).await?;
13655    redirect_named_with_params_and_message_args(
13656        "rcms-admin:workflows:edit",
13657        &[("id", workflow_id.to_string())],
13658        MsgLevel::Success,
13659        "Added step “{name}”.",
13660        &[("name", name.as_str())],
13661        &headers,
13662    )
13663}
13664
13665pub async fn workflow_task_delete(
13666    State(_state): State<super::AdminState>,
13667    tenant: Tenant,
13668    headers: HeaderMap,
13669    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
13670    Path((workflow_id, task_id)): Path<(i64, i64)>,
13671) -> Result<Response, AdminError> {
13672    let row = crate::workflow::WorkflowTask::objects()
13673        .where_(crate::workflow::WorkflowTask::id.eq(task_id))
13674        .where_(crate::workflow::WorkflowTask::workflow_id.eq(workflow_id))
13675        .first(tenant.pool())
13676        .await?
13677        .ok_or(AdminError::NotFound(task_id))?;
13678    let name = row.name.clone();
13679    row.delete(tenant.pool()).await?;
13680    redirect_named_with_params_and_message_args(
13681        "rcms-admin:workflows:edit",
13682        &[("id", workflow_id.to_string())],
13683        MsgLevel::Success,
13684        "Removed step “{name}”.",
13685        &[("name", name.as_str())],
13686        &headers,
13687    )
13688}
13689
13690// ---------------------------------------------------------------
13691// Per-page workflow actions (#73 PR 2): submit / approve / reject /
13692// cancel. Permission rules:
13693//   - submit: any logged-in user (page-Edit perm already gated the
13694//     editor URL).
13695//   - approve / reject: viewer must be a member of the role bound
13696//     to the current task. Tenant superusers bypass.
13697//   - cancel: any logged-in user (audit captures who).
13698// ---------------------------------------------------------------
13699
13700#[derive(Debug, Deserialize)]
13701pub struct WorkflowDecisionForm {
13702    #[serde(default)]
13703    pub comment: String,
13704    /// The step the reviewer was looking at. A decision posted
13705    /// for a step that is no longer current is refused, not applied to
13706    /// whichever step is current now.
13707    #[serde(default)]
13708    pub task_id: Option<i64>,
13709}
13710
13711/// The decision the reviewer posted is for a step that is no
13712/// longer the current one, or another request decided it first.
13713fn step_already_decided(page_id: i64, headers: &HeaderMap) -> Result<Response, AdminError> {
13714    redirect_named_with_params_and_message(
13715        "rcms-admin:pages:edit",
13716        &[("id", page_id.to_string())],
13717        MsgLevel::Error,
13718        "That review step was already decided — check the page's current step before deciding again.",
13719        headers,
13720    )
13721}
13722
13723async fn user_is_in_role(
13724    pool: &rustango::sql::Pool,
13725    user_id: i64,
13726    role_id: i64,
13727) -> Result<bool, rustango::sql::ExecError> {
13728    use rustango::core::Column as _;
13729    use rustango::sql::FetcherPool as _;
13730    let rows: Vec<rustango::tenancy::permissions::UserRole> =
13731        rustango::tenancy::permissions::UserRole::objects()
13732            .where_(rustango::tenancy::permissions::UserRole::user_id.eq(user_id))
13733            .where_(rustango::tenancy::permissions::UserRole::role_id.eq(role_id))
13734            .fetch(pool)
13735            .await?;
13736    Ok(!rows.is_empty())
13737}
13738
13739pub async fn page_workflow_submit(
13740    State(_state): State<super::AdminState>,
13741    tenant: Tenant,
13742    headers: HeaderMap,
13743    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
13744    Path(id): Path<i64>,
13745) -> Result<Response, AdminError> {
13746    let Some(viewer_id) = session_user.as_ref().and_then(|u| u.id.get().copied()) else {
13747        return Ok(unauthorized_no_session());
13748    };
13749    let page = Page::objects()
13750        .where_(Page::id.eq(id))
13751        .first(tenant.pool())
13752        .await?
13753        .ok_or(AdminError::NotFound(id))?;
13754    // Resolve the page-type → workflow slug.
13755    let pts: Vec<PageType> = PageType::objects()
13756        .where_(PageType::id.eq(page.page_type_id))
13757        .fetch(tenant.pool())
13758        .await?;
13759    let Some(pt) = pts.into_iter().next() else {
13760        return redirect_named_with_params_and_message(
13761            "rcms-admin:pages:edit",
13762            &[("id", id.to_string())],
13763            MsgLevel::Error,
13764            "Page type row not found.",
13765            &headers,
13766        );
13767    };
13768    let Some(slug) = pt.workflow_name() else {
13769        return redirect_named_with_params_and_message(
13770            "rcms-admin:pages:edit",
13771            &[("id", id.to_string())],
13772            MsgLevel::Error,
13773            "This page type isn't bound to a workflow — nothing to submit.",
13774            &headers,
13775        );
13776    };
13777    let Some(workflow) = crate::workflow::find_by_name(tenant.pool(), &slug).await? else {
13778        return redirect_named_with_params_and_message_args(
13779            "rcms-admin:pages:edit",
13780            &[("id", id.to_string())],
13781            MsgLevel::Error,
13782            "Workflow `{slug}` not found or inactive — ask an admin to enable it.",
13783            &[("slug", slug.as_str())],
13784            &headers,
13785        );
13786    };
13787    let tasks = crate::workflow::tasks_for(
13788        tenant.pool(),
13789        workflow.id.get().copied().unwrap_or_default(),
13790    )
13791    .await?;
13792    if tasks.is_empty() {
13793        return redirect_named_with_params_and_message(
13794            "rcms-admin:pages:edit",
13795            &[("id", id.to_string())],
13796            MsgLevel::Error,
13797            "Workflow has no review steps yet — ask an admin to add at least one step.",
13798            &headers,
13799        );
13800    }
13801    // Only block when an in-progress review already exists. A
13802    // `needs_changes` row means the prior cycle was rejected; the
13803    // author is allowed to resubmit, which leaves the rejected row
13804    // as audit history and starts a fresh cycle.
13805    if let Some(active) = crate::workflow::active_state_for_page(tenant.pool(), id).await? {
13806        if active.status == crate::workflow::WorkflowStatus::InProgress.as_str() {
13807            return redirect_named_with_params_and_message(
13808                "rcms-admin:pages:edit",
13809                &[("id", id.to_string())],
13810                MsgLevel::Warning,
13811                "This page is already under review.",
13812                &headers,
13813            );
13814        }
13815    }
13816    crate::workflow::submit_for_review(tenant.pool(), id, &workflow, &tasks, viewer_id).await?;
13817    // The submitter waits for the verdict now; their edit lock would
13818    // only stop the reviewer from editing.
13819    crate::lock::release(tenant.pool(), id, viewer_id)
13820        .await
13821        .log_warn("editor lock not released on submit");
13822
13823    // #192 — audit log the workflow submission.
13824    crate::page_log::record_or_warn(
13825        tenant.pool(),
13826        id,
13827        crate::page_log::ACTION_WORKFLOW_SUBMIT,
13828        Some(viewer_id),
13829        format!(
13830            "Submitted for review — workflow “{}”, first step “{}”.",
13831            workflow.name, tasks[0].name
13832        ),
13833        Some(serde_json::json!({
13834            "workflow_id": workflow.id.get().copied(),
13835            "workflow_name": workflow.name,
13836            "first_task": tasks[0].name,
13837        })),
13838    )
13839    .await;
13840
13841    // #85 — notify the first task's reviewers that a review is
13842    // waiting. No-op when no mailer is wired into AdminState.
13843    notify_workflow(
13844        _state.mailer.as_deref(),
13845        &_state.mailer_from,
13846        tenant.pool(),
13847        &tenant.org.slug,
13848        "submit",
13849        &workflow.name,
13850        &page.title,
13851        id,
13852        Some(&tasks[0].name),
13853        session_user.as_ref().map(|u| u.username.as_str()),
13854        None,
13855        WorkflowRecipients::Role(tasks[0].role_id),
13856    )
13857    .await;
13858
13859    redirect_named_with_params_and_message_args(
13860        "rcms-admin:pages:edit",
13861        &[("id", id.to_string())],
13862        MsgLevel::Success,
13863        "Submitted for review — first step: “{name}”.",
13864        &[("name", tasks[0].name.as_str())],
13865        &headers,
13866    )
13867}
13868
13869/// Recipient selector for [`notify_workflow`].
13870enum WorkflowRecipients {
13871    /// Members of a single role (reviewers on the active task).
13872    Role(i64),
13873    /// A single user — used to notify the original submitter on
13874    /// approve-finish / reject / cancel.
13875    User(i64),
13876}
13877
13878/// Helper invoked by the workflow handlers to dispatch the right
13879/// notification per event. Resolves recipients, composes subject +
13880/// body, and hands off to the framework's `Mailer`. No-op if the
13881/// AdminState has no mailer attached.
13882#[allow(clippy::too_many_arguments)]
13883async fn notify_workflow(
13884    mailer: Option<&dyn rustango::email::Mailer>,
13885    from: &str,
13886    pool: &rustango::sql::Pool,
13887    tenant_slug: &str,
13888    event: &str,
13889    workflow_name: &str,
13890    page_title: &str,
13891    page_id: i64,
13892    task_name: Option<&str>,
13893    actor_username: Option<&str>,
13894    comment: Option<&str>,
13895    recipients: WorkflowRecipients,
13896) {
13897    let Some(mailer) = mailer else {
13898        return;
13899    };
13900    // #197 — resolve recipients to user_ids first so we can filter
13901    // out users who have muted this event class before composing
13902    // email bodies.
13903    let kind = crate::notification_pref::pref_kind_for_workflow_event(event);
13904    let candidate_user_ids: Vec<i64> = match recipients {
13905        WorkflowRecipients::Role(role_id) => {
13906            crate::workflow_mail::role_member_user_ids(pool, role_id)
13907                .await
13908                .unwrap_or_default()
13909        }
13910        WorkflowRecipients::User(user_id) => vec![user_id],
13911    };
13912    let allowed_ids = crate::notification_pref::filter_enabled(pool, &candidate_user_ids, kind)
13913        .await
13914        .unwrap_or(candidate_user_ids);
13915    let mut pairs: Vec<(String, String)> = Vec::with_capacity(allowed_ids.len());
13916    for uid in allowed_ids {
13917        if let Ok(Some(pair)) = crate::workflow_mail::user_email(pool, uid, tenant_slug).await {
13918            pairs.push(pair);
13919        }
13920    }
13921    if pairs.is_empty() {
13922        return;
13923    }
13924    let (subject, body) = crate::workflow_mail::render_notification(
13925        event,
13926        workflow_name,
13927        page_title,
13928        page_id,
13929        task_name,
13930        actor_username,
13931        comment,
13932    );
13933    crate::workflow_mail::notify_many(mailer, from, &pairs, &subject, &body).await;
13934}
13935
13936pub async fn page_workflow_approve(
13937    State(_state): State<super::AdminState>,
13938    tenant: Tenant,
13939    headers: HeaderMap,
13940    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
13941    Path(id): Path<i64>,
13942    Form(form): Form<WorkflowDecisionForm>,
13943) -> Result<Response, AdminError> {
13944    let Some(viewer) = session_user.as_ref() else {
13945        return Ok(unauthorized_no_session());
13946    };
13947    let viewer_id = viewer.id.get().copied().unwrap_or_default();
13948    let Some(mut state) = crate::workflow::active_state_for_page(tenant.pool(), id).await? else {
13949        return redirect_named_with_params_and_message(
13950            "rcms-admin:pages:edit",
13951            &[("id", id.to_string())],
13952            MsgLevel::Error,
13953            "No active workflow on this page.",
13954            &headers,
13955        );
13956    };
13957    let tasks = crate::workflow::tasks_for(tenant.pool(), state.workflow_id).await?;
13958    let Some(current_task) = state
13959        .current_task_id
13960        .and_then(|tid| tasks.iter().find(|t| t.id.get().copied() == Some(tid)))
13961    else {
13962        return redirect_named_with_params_and_message(
13963            "rcms-admin:pages:edit",
13964            &[("id", id.to_string())],
13965            MsgLevel::Error,
13966            "Workflow has no current task — refresh the page.",
13967            &headers,
13968        );
13969    };
13970    if !viewer.is_superuser
13971        && !user_is_in_role(tenant.pool(), viewer_id, current_task.role_id).await?
13972    {
13973        return redirect_named_with_params_and_message_args(
13974            "rcms-admin:pages:edit",
13975            &[("id", id.to_string())],
13976            MsgLevel::Error,
13977            "Only members of the task's role can approve “{name}”.",
13978            &[("name", current_task.name.as_str())],
13979            &headers,
13980        );
13981    }
13982    if form.task_id.is_some_and(|t| current_task.id.get().copied() != Some(t)) {
13983        return step_already_decided(id, &headers);
13984    }
13985    // Capture submitter_id + page title BEFORE the transition so we
13986    // can route the notification on Finished.
13987    let submitter_id = state.requested_by;
13988    let page_title: String = Page::objects()
13989        .where_(Page::id.eq(id))
13990        .fetch(tenant.pool())
13991        .await
13992        .ok()
13993        .and_then(|v| v.into_iter().next())
13994        .map(|p| p.title)
13995        .unwrap_or_else(|| format!("page #{id}"));
13996    let workflow_name: String = crate::workflow::Workflow::objects()
13997        .where_(crate::workflow::Workflow::id.eq(state.workflow_id))
13998        .fetch(tenant.pool())
13999        .await
14000        .ok()
14001        .and_then(|v| v.into_iter().next())
14002        .map(|w| w.name)
14003        .unwrap_or_else(|| "Workflow".to_owned());
14004    let outcome = crate::workflow::approve_current(
14005        tenant.pool(),
14006        &mut state,
14007        &tasks,
14008        viewer_id,
14009        &form.comment,
14010    )
14011    .await?;
14012    let msg = match outcome {
14013        crate::workflow::ApproveOutcome::AlreadyDecided => {
14014            return step_already_decided(id, &headers);
14015        }
14016        crate::workflow::ApproveOutcome::Advanced { next_task_id } => {
14017            let next = tasks
14018                .iter()
14019                .find(|t| t.id.get().copied() == Some(next_task_id));
14020            let next_name = next.map(|t| t.name.as_str()).unwrap_or("next step");
14021            // #85 — notify reviewers of the new current step.
14022            if let Some(nt) = next {
14023                notify_workflow(
14024                    _state.mailer.as_deref(),
14025                    &_state.mailer_from,
14026                    tenant.pool(),
14027                    &tenant.org.slug,
14028                    "approve_advance",
14029                    &workflow_name,
14030                    &page_title,
14031                    id,
14032                    Some(&nt.name),
14033                    Some(&viewer.username),
14034                    Some(&form.comment),
14035                    WorkflowRecipients::Role(nt.role_id),
14036                )
14037                .await;
14038            }
14039            // #192 — audit log the approve-advance.
14040            crate::page_log::record_or_warn(
14041                tenant.pool(),
14042                id,
14043                crate::page_log::ACTION_WORKFLOW_APPROVE,
14044                Some(viewer_id),
14045                format!(
14046                    "Approved “{}” — advanced to “{next_name}”.",
14047                    current_task.name
14048                ),
14049                Some(serde_json::json!({
14050                    "outcome": "advanced",
14051                    "task_name": current_task.name,
14052                    "next_task_name": next_name,
14053                    "comment": form.comment,
14054                })),
14055            )
14056            .await;
14057            format!("Approved “{}” — moved to “{next_name}”.", current_task.name)
14058        }
14059        crate::workflow::ApproveOutcome::Finished => {
14060            // Changes to the live page held for this review go live now,
14061            // through the normal save path.
14062            if let Some(pending) = crate::pending_change::for_page(tenant.pool(), id).await? {
14063                match apply_page_edit(
14064                    tenant.pool(),
14065                    &tenant_key(&tenant.org)?,
14066                    &_state.cache_invalidator,
14067                    _state.mailer.as_deref(),
14068                    &_state.mailer_from,
14069                    false,
14070                    id,
14071                    &pending.form_map(),
14072                    None,
14073                )
14074                .await
14075                {
14076                    Ok(Ok(_)) => crate::pending_change::discard(tenant.pool(), id).await?,
14077                    Ok(Err(_)) | Err(_) => {
14078                        tracing::warn!(page_id = id, "held change could not be applied on approval");
14079                    }
14080                }
14081            }
14082            // Auto-publish on workflow completion.
14083            if let Some(mut page) = Page::objects()
14084                .where_(Page::id.eq(id))
14085                .first(tenant.pool())
14086                .await?
14087            {
14088                page.status = crate::page::PageStatus::Published.as_str().to_owned();
14089                let now = chrono::Utc::now();
14090                if page.published_at.is_none() {
14091                    page.published_at = Some(now);
14092                }
14093                // #251 — workflow-finish publish bumps last-publish.
14094                page.last_published_at = Some(now);
14095                page.save(tenant.pool()).await?;
14096                // #692 — the same go-live effects as any other publish
14097                // (search index + after_publish_page hooks), and the page's
14098                // cached URL goes too: it used to keep serving the old copy.
14099                crate::page::went_live_effects(tenant.pool(), &tenant.org.slug, &page, Some(viewer_id)).await;
14100                crate::task_queue::purge_urls(
14101                    _state.cache_invalidator.clone(),
14102                    tenant_key(&tenant.org)?,
14103                    vec![page.url_path.clone()],
14104                )
14105                .await;
14106                // #115 — notify-on-publish subscribers.
14107                crate::page_subscription::notify_publish(
14108                    _state.mailer.as_deref(),
14109                    &_state.mailer_from,
14110                    tenant.pool(),
14111                    &tenant.org.slug,
14112                    id,
14113                    &page.title,
14114                    &page.url_path,
14115                    Some(&viewer.username),
14116                )
14117                .await;
14118            }
14119            // #85 — notify the submitter that their submission shipped.
14120            notify_workflow(
14121                _state.mailer.as_deref(),
14122                &_state.mailer_from,
14123                tenant.pool(),
14124                &tenant.org.slug,
14125                "approve_finish",
14126                &workflow_name,
14127                &page_title,
14128                id,
14129                Some(&current_task.name),
14130                Some(&viewer.username),
14131                Some(&form.comment),
14132                WorkflowRecipients::User(submitter_id),
14133            )
14134            .await;
14135            // #192 — audit log the workflow-finish approval + the
14136            // auto-publish it triggered.
14137            crate::page_log::record_or_warn(
14138                tenant.pool(),
14139                id,
14140                crate::page_log::ACTION_WORKFLOW_APPROVE,
14141                Some(viewer_id),
14142                format!(
14143                    "Approved “{}” — workflow complete; page auto-published.",
14144                    current_task.name
14145                ),
14146                Some(serde_json::json!({
14147                    "outcome": "finished",
14148                    "task_name": current_task.name,
14149                    "comment": form.comment,
14150                })),
14151            )
14152            .await;
14153            crate::page_log::record_or_warn(
14154                tenant.pool(),
14155                id,
14156                crate::page_log::ACTION_PUBLISH,
14157                Some(viewer_id),
14158                "Published via workflow approval.",
14159                Some(serde_json::json!({ "via": "workflow" })),
14160            )
14161            .await;
14162            format!(
14163                "Approved “{}” — workflow complete, page published.",
14164                current_task.name
14165            )
14166        }
14167    };
14168    redirect_named_with_params_and_message(
14169        "rcms-admin:pages:edit",
14170        &[("id", id.to_string())],
14171        MsgLevel::Success,
14172        &msg,
14173        &headers,
14174    )
14175}
14176
14177pub async fn page_workflow_reject(
14178    State(_state): State<super::AdminState>,
14179    tenant: Tenant,
14180    headers: HeaderMap,
14181    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
14182    Path(id): Path<i64>,
14183    Form(form): Form<WorkflowDecisionForm>,
14184) -> Result<Response, AdminError> {
14185    let Some(viewer) = session_user.as_ref() else {
14186        return Ok(unauthorized_no_session());
14187    };
14188    let viewer_id = viewer.id.get().copied().unwrap_or_default();
14189    let Some(mut state) = crate::workflow::active_state_for_page(tenant.pool(), id).await? else {
14190        return redirect_named_with_params_and_message(
14191            "rcms-admin:pages:edit",
14192            &[("id", id.to_string())],
14193            MsgLevel::Error,
14194            "No active workflow on this page.",
14195            &headers,
14196        );
14197    };
14198    let tasks = crate::workflow::tasks_for(tenant.pool(), state.workflow_id).await?;
14199    let Some(current_task) = state
14200        .current_task_id
14201        .and_then(|tid| tasks.iter().find(|t| t.id.get().copied() == Some(tid)))
14202    else {
14203        return redirect_named_with_params_and_message(
14204            "rcms-admin:pages:edit",
14205            &[("id", id.to_string())],
14206            MsgLevel::Error,
14207            "Workflow has no current task — refresh the page.",
14208            &headers,
14209        );
14210    };
14211    if !viewer.is_superuser
14212        && !user_is_in_role(tenant.pool(), viewer_id, current_task.role_id).await?
14213    {
14214        return redirect_named_with_params_and_message_args(
14215            "rcms-admin:pages:edit",
14216            &[("id", id.to_string())],
14217            MsgLevel::Error,
14218            "Only members of the task's role can reject “{name}”.",
14219            &[("name", current_task.name.as_str())],
14220            &headers,
14221        );
14222    }
14223    if form.task_id.is_some_and(|t| current_task.id.get().copied() != Some(t)) {
14224        return step_already_decided(id, &headers);
14225    }
14226    if form.comment.trim().is_empty() {
14227        return redirect_named_with_params_and_message(
14228            "rcms-admin:pages:edit",
14229            &[("id", id.to_string())],
14230            MsgLevel::Error,
14231            "Say what should change — the author sees it in the review history.",
14232            &headers,
14233        );
14234    }
14235    let submitter_id = state.requested_by;
14236    let workflow_id = state.workflow_id;
14237    if !crate::workflow::reject_current(tenant.pool(), &mut state, viewer_id, &form.comment).await? {
14238        return step_already_decided(id, &headers);
14239    }
14240    // #192 — audit log the rejection.
14241    crate::page_log::record_or_warn(
14242        tenant.pool(),
14243        id,
14244        crate::page_log::ACTION_WORKFLOW_REJECT,
14245        Some(viewer_id),
14246        format!("Rejected “{}” — changes requested.", current_task.name),
14247        Some(serde_json::json!({
14248            "task_name": current_task.name,
14249            "comment": form.comment,
14250        })),
14251    )
14252    .await;
14253    // #85 — notify the submitter that changes are requested.
14254    let workflow_name: String = crate::workflow::Workflow::objects()
14255        .where_(crate::workflow::Workflow::id.eq(workflow_id))
14256        .fetch(tenant.pool())
14257        .await
14258        .ok()
14259        .and_then(|v| v.into_iter().next())
14260        .map(|w| w.name)
14261        .unwrap_or_else(|| "Workflow".to_owned());
14262    let page_title: String = Page::objects()
14263        .where_(Page::id.eq(id))
14264        .fetch(tenant.pool())
14265        .await
14266        .ok()
14267        .and_then(|v| v.into_iter().next())
14268        .map(|p| p.title)
14269        .unwrap_or_else(|| format!("page #{id}"));
14270    notify_workflow(
14271        _state.mailer.as_deref(),
14272        &_state.mailer_from,
14273        tenant.pool(),
14274        &tenant.org.slug,
14275        "reject",
14276        &workflow_name,
14277        &page_title,
14278        id,
14279        Some(&current_task.name),
14280        Some(&viewer.username),
14281        Some(&form.comment),
14282        WorkflowRecipients::User(submitter_id),
14283    )
14284    .await;
14285    redirect_named_with_params_and_message_args(
14286        "rcms-admin:pages:edit",
14287        &[("id", id.to_string())],
14288        MsgLevel::Success,
14289        "Rejected “{name}” — page returned to author for changes.",
14290        &[("name", current_task.name.as_str())],
14291        &headers,
14292    )
14293}
14294
14295pub async fn page_workflow_cancel(
14296    State(_state): State<super::AdminState>,
14297    tenant: Tenant,
14298    headers: HeaderMap,
14299    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
14300    Path(id): Path<i64>,
14301) -> Result<Response, AdminError> {
14302    let Some(viewer_id) = session_user.as_ref().and_then(|u| u.id.get().copied()) else {
14303        return Ok(unauthorized_no_session());
14304    };
14305    let Some(mut state) = crate::workflow::active_state_for_page(tenant.pool(), id).await? else {
14306        return redirect_named_with_params_and_message(
14307            "rcms-admin:pages:edit",
14308            &[("id", id.to_string())],
14309            MsgLevel::Warning,
14310            "This page isn't currently under review.",
14311            &headers,
14312        );
14313    };
14314    let submitter_id = state.requested_by;
14315    let workflow_id = state.workflow_id;
14316    crate::workflow::cancel(tenant.pool(), &mut state, viewer_id).await?;
14317    // #192 — audit log the cancellation.
14318    crate::page_log::record_or_warn(
14319        tenant.pool(),
14320        id,
14321        crate::page_log::ACTION_WORKFLOW_CANCEL,
14322        Some(viewer_id),
14323        "Workflow cancelled.",
14324        Some(serde_json::json!({ "workflow_id": workflow_id })),
14325    )
14326    .await;
14327    // #85 — notify the submitter the review was cancelled. No-op
14328    // when the submitter is the canceller themselves (the mailer
14329    // still sends but the user's inbox is the audit trail).
14330    let workflow_name: String = crate::workflow::Workflow::objects()
14331        .where_(crate::workflow::Workflow::id.eq(workflow_id))
14332        .fetch(tenant.pool())
14333        .await
14334        .ok()
14335        .and_then(|v| v.into_iter().next())
14336        .map(|w| w.name)
14337        .unwrap_or_else(|| "Workflow".to_owned());
14338    let page_title: String = Page::objects()
14339        .where_(Page::id.eq(id))
14340        .fetch(tenant.pool())
14341        .await
14342        .ok()
14343        .and_then(|v| v.into_iter().next())
14344        .map(|p| p.title)
14345        .unwrap_or_else(|| format!("page #{id}"));
14346    let actor_username = session_user.as_ref().map(|u| u.username.as_str());
14347    notify_workflow(
14348        _state.mailer.as_deref(),
14349        &_state.mailer_from,
14350        tenant.pool(),
14351        &tenant.org.slug,
14352        "cancel",
14353        &workflow_name,
14354        &page_title,
14355        id,
14356        None,
14357        actor_username,
14358        None,
14359        WorkflowRecipients::User(submitter_id),
14360    )
14361    .await;
14362    redirect_named_with_params_and_message(
14363        "rcms-admin:pages:edit",
14364        &[("id", id.to_string())],
14365        MsgLevel::Success,
14366        "Workflow cancelled.",
14367        &headers,
14368    )
14369}
14370
14371// =====================================================================
14372// Per-page audit log CSV export (#192)
14373// =====================================================================
14374
14375/// GET /cms-admin/pages/{id}/log.csv — every audit-log entry for the
14376/// page, newest first, as CSV. Columns: timestamp, action, actor_id,
14377/// actor_username, message, data_json. The full log (no row cap)
14378/// emits — the editor explicitly clicked Download.
14379pub async fn page_log_csv(
14380    State(_state): State<super::AdminState>,
14381    tenant: Tenant,
14382    Path(id): Path<i64>,
14383) -> Result<Response, AdminError> {
14384    let entries = crate::page_log::for_page(tenant.pool(), id, None).await?;
14385    let user_ids: std::collections::BTreeSet<i64> =
14386        entries.iter().filter_map(|e| e.actor_id).collect();
14387    let users: std::collections::HashMap<i64, String> = if user_ids.is_empty() {
14388        std::collections::HashMap::new()
14389    } else {
14390        rustango::tenancy::auth::User::objects()
14391            .where_(
14392                rustango::tenancy::auth::User::id.is_in(user_ids.into_iter().collect::<Vec<_>>()),
14393            )
14394            .fetch(tenant.pool())
14395            .await?
14396            .into_iter()
14397            .filter_map(|u| u.id.get().copied().map(|id| (id, u.username)))
14398            .collect()
14399    };
14400
14401    let mut out = String::with_capacity(4096);
14402    out.push_str("timestamp,action,actor_id,actor_username,message,data_json\n");
14403    for e in entries {
14404        let ts = e
14405            .created_at
14406            .get()
14407            .map(|t| t.to_rfc3339())
14408            .unwrap_or_default();
14409        let actor_id = e.actor_id.map(|i| i.to_string()).unwrap_or_default();
14410        let actor_username = e
14411            .actor_id
14412            .and_then(|uid| users.get(&uid).cloned())
14413            .unwrap_or_default();
14414        out.push_str(&csv_escape(&ts));
14415        out.push(',');
14416        out.push_str(&csv_escape(&e.action));
14417        out.push(',');
14418        out.push_str(&csv_escape(&actor_id));
14419        out.push(',');
14420        out.push_str(&csv_escape(&actor_username));
14421        out.push(',');
14422        out.push_str(&csv_escape(&e.message));
14423        out.push(',');
14424        out.push_str(&csv_escape(&e.data_json));
14425        out.push('\n');
14426    }
14427
14428    let filename = format!("page-{id}-audit-log.csv");
14429    Ok((
14430        [
14431            (
14432                axum::http::header::CONTENT_TYPE,
14433                "text/csv; charset=utf-8".to_owned(),
14434            ),
14435            (
14436                axum::http::header::CONTENT_DISPOSITION,
14437                format!("attachment; filename=\"{filename}\""),
14438            ),
14439        ],
14440        out,
14441    )
14442        .into_response())
14443}
14444
14445// =====================================================================
14446// History — tenant-wide revision audit log (#17)
14447// =====================================================================
14448
14449/// Query string for the history view. All filters optional; pagination
14450/// via `page` (1-indexed, defaults to 1 — `limit` is fixed at 50 to
14451/// keep the URL state simple).
14452#[derive(Debug, Deserialize)]
14453pub struct HistoryQuery {
14454    #[serde(default)]
14455    pub page_id: Option<i64>,
14456    #[serde(default)]
14457    pub user_id: Option<i64>,
14458    #[serde(default)]
14459    pub page: Option<u32>,
14460    /// Rows per page.
14461    #[serde(default)]
14462    pub per_page: Option<usize>,
14463}
14464
14465/// GET /cms-admin/history — tenant-wide cross-page audit log built
14466/// from `cms_revision`. Each row joins to the page (for title +
14467/// current URL) and the editor (for username). One Rust-side stitch
14468/// pass instead of a SQL JOIN since the ORM doesn't expose joins
14469/// fluently yet.
14470pub async fn history_page(
14471    State(state): State<super::AdminState>,
14472    tenant: Tenant,
14473    headers: HeaderMap,
14474    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
14475    Query(q): Query<HistoryQuery>,
14476    axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
14477) -> Result<Response, AdminError> {
14478    let page_size = crate::admin::pagination::clamp_per_page(q.per_page);
14479
14480    // Build the base query with optional filters. The ORM's
14481    // `.where_()` is additive (AND); we apply each filter only when
14482    // present so the SQL stays minimal.
14483    let mut revisions_query =
14484        // Newest first; `id` breaks timestamp ties so pages are stable.
14485        crate::revision::Revision::objects().order_by(&[("created_at", true), ("id", true)]);
14486    if let Some(pid) = q.page_id {
14487        revisions_query = revisions_query.where_(crate::revision::Revision::page_id.eq(pid));
14488    }
14489    if let Some(uid) = q.user_id {
14490        revisions_query =
14491            revisions_query.where_(crate::revision::Revision::created_by.eq(Some(uid)));
14492    }
14493
14494    // Counted and paged in SQL (#627): each revision carries a full page
14495    // snapshot, so loading every match to show 50 was the expensive part.
14496    let total = usize::try_from(revisions_query.clone().count(tenant.pool()).await?).unwrap_or_default();
14497    let pagination = crate::admin::pagination::context(q.page.unwrap_or(1).max(1) as i64, page_size, total);
14498    let current_page = pagination["page"].as_i64().unwrap_or(1) as u32;
14499    let has_next = pagination["has_next"].as_bool().unwrap_or(false);
14500    let has_prev = pagination["has_prev"].as_bool().unwrap_or(false);
14501    let revisions: Vec<crate::revision::Revision> = revisions_query
14502        .limit(page_size as i64)
14503        .offset(crate::admin::pagination::offset(i64::from(current_page), page_size))
14504        .fetch(tenant.pool())
14505        .await?;
14506
14507    // Batch-fetch every distinct page + user referenced by this slice.
14508    let page_ids: std::collections::BTreeSet<i64> = revisions.iter().map(|r| r.page_id).collect();
14509    let user_ids: std::collections::BTreeSet<i64> =
14510        revisions.iter().filter_map(|r| r.created_by).collect();
14511
14512    let pages: Vec<Page> = if page_ids.is_empty() {
14513        Vec::new()
14514    } else {
14515        Page::objects()
14516            .where_(Page::id.is_in(page_ids.iter().copied()))
14517            .fetch(tenant.pool())
14518            .await?
14519    };
14520    let users: Vec<rustango::tenancy::auth::User> = if user_ids.is_empty() {
14521        Vec::new()
14522    } else {
14523        rustango::tenancy::auth::User::objects()
14524            .where_(rustango::tenancy::auth::User::id.is_in(user_ids.iter().copied()))
14525            .fetch(tenant.pool())
14526            .await?
14527    };
14528
14529    let pages_by_id: std::collections::HashMap<i64, &Page> = pages
14530        .iter()
14531        .filter_map(|p| p.id.get().copied().map(|id| (id, p)))
14532        .collect();
14533    let users_by_id: std::collections::HashMap<i64, &rustango::tenancy::auth::User> = users
14534        .iter()
14535        .filter_map(|u| u.id.get().copied().map(|id| (id, u)))
14536        .collect();
14537
14538    // Build a list of view-model dicts for the template — each row
14539    // carries everything Tera needs (no further lookups inside the
14540    // template loop). `is_latest` flags the most-recent revision for
14541    // each page so the UI can disable revert on the current state.
14542    // Every revision's (id, page_id, sequence) for the pages on this
14543    // screen — light columns only, never the snapshots — so the latest
14544    // flag and the Compare link are right at the edge of a page too.
14545    let page_id_list: Vec<i64> = page_ids.iter().copied().collect();
14546    let seqs: Vec<(i64, i64, i32)> = crate::revision::page_sequences(tenant.pool(), &page_id_list).await?;
14547    let mut latest_seq_by_page: std::collections::HashMap<i64, i32> =
14548        std::collections::HashMap::new();
14549    for &(_, pid, seq) in &seqs {
14550        let cur = latest_seq_by_page.entry(pid).or_insert(seq);
14551        if seq > *cur {
14552            *cur = seq;
14553        }
14554    }
14555    // #74 — the prior revision (next-lower sequence on the same page) of
14556    // each row, for the Compare button's deep link to the diff view.
14557    let mut by_page: std::collections::HashMap<i64, Vec<(i64, i32)>> =
14558        std::collections::HashMap::new();
14559    for &(id, pid, seq) in &seqs {
14560        by_page.entry(pid).or_default().push((id, seq));
14561    }
14562    let mut prev_by_id: std::collections::HashMap<i64, (i64, i32)> =
14563        std::collections::HashMap::new();
14564    for (_pid, mut list) in by_page {
14565        list.sort_by_key(|&(_, seq)| seq);
14566        for pair in list.windows(2) {
14567            let (earlier_id, earlier_seq) = pair[0];
14568            let (later_id, _) = pair[1];
14569            prev_by_id.insert(later_id, (earlier_id, earlier_seq));
14570        }
14571    }
14572
14573    let rows: Vec<serde_json::Value> = revisions
14574        .iter()
14575        .map(|r| {
14576            let page = pages_by_id.get(&r.page_id);
14577            let user = r.created_by.and_then(|uid| users_by_id.get(&uid));
14578            let created_at = r.created_at.get().copied();
14579            let (prev_id, prev_sequence) =
14580                r.id.get()
14581                    .copied()
14582                    .and_then(|id| prev_by_id.get(&id).copied())
14583                    .map(|(a, b)| (Some(a), Some(b)))
14584                    .unwrap_or((None, None));
14585            let is_latest = latest_seq_by_page
14586                .get(&r.page_id)
14587                .is_some_and(|s| *s == r.sequence);
14588            serde_json::json!({
14589                "id": r.id.get().copied(),
14590                "page_id": r.page_id,
14591                "sequence": r.sequence,
14592                "created_at": created_at,
14593                "page_title": page.map(|p| p.title.clone()),
14594                "page_url_path": page.map(|p| p.url_path.clone()),
14595                "page_status": page.map(|p| p.status.as_str()),
14596                "username": user.map(|u| u.username.clone()),
14597                "system_user": r.created_by.is_none(),
14598                "is_latest": is_latest,
14599                "prev_id": prev_id,
14600                "prev_sequence": prev_sequence,
14601            })
14602        })
14603        .collect();
14604
14605    let mut ctx = Context::new();
14606    add_chrome(&mut ctx, &tenant, "history", session_user.as_ref()).await;
14607    add_admin_theme(&mut ctx, tenant.pool()).await;
14608    ctx.insert("rows", &rows);
14609    ctx.insert("filter_page_id", &q.page_id);
14610    ctx.insert("filter_user_id", &q.user_id);
14611    // #316 — raw query string for the `| querystring(page=…)` pagination
14612    // links (preserves the page_id / user_id filters + sets page).
14613    ctx.insert("query_string", &raw_query.unwrap_or_default());
14614    ctx.insert("current_page", &current_page);
14615    ctx.insert("has_next", &has_next);
14616    ctx.insert("has_prev", &has_prev);
14617    ctx.insert("total", &total);
14618    ctx.insert("page_size", &page_size);
14619    ctx.insert(
14620        "pagination",
14621        &crate::admin::pagination::context(current_page as i64, page_size, total),
14622    );
14623    render_with_csrf(&state, &headers, "rcms_admin/history.html", &mut ctx)
14624}
14625
14626/// Query string for the diff view: required `a` + `b` revision ids.
14627/// `only_changes` (default true) hides unchanged fields when the
14628/// template renders.
14629#[derive(Debug, Deserialize)]
14630pub struct HistoryDiffQuery {
14631    pub a: i64,
14632    pub b: i64,
14633    #[serde(default)]
14634    pub all: Option<String>,
14635}
14636
14637/// GET /cms-admin/pages/{id}/history/diff?a=<rev_id>&b=<rev_id>.
14638/// Side-by-side comparison of two revisions on the same
14639/// page. v1 surfaces a flat field-level diff; rich-text +
14640/// StreamField-aware diff is a follow-up.
14641pub async fn history_diff(
14642    State(state): State<super::AdminState>,
14643    tenant: Tenant,
14644    headers: HeaderMap,
14645    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
14646    Path(page_id): Path<i64>,
14647    Query(q): Query<HistoryDiffQuery>,
14648) -> Result<Response, AdminError> {
14649    let revisions: Vec<crate::revision::Revision> = crate::revision::Revision::objects()
14650        .where_(crate::revision::Revision::page_id.eq(page_id))
14651        .where_(crate::revision::Revision::id.is_in([q.a, q.b]))
14652        .fetch(tenant.pool())
14653        .await?;
14654    let a_row = revisions
14655        .iter()
14656        .find(|r| r.id.get().copied() == Some(q.a))
14657        .cloned()
14658        .ok_or(AdminError::NotFound(q.a))?;
14659    let b_row = revisions
14660        .iter()
14661        .find(|r| r.id.get().copied() == Some(q.b))
14662        .cloned()
14663        .ok_or(AdminError::NotFound(q.b))?;
14664
14665    let page = Page::objects()
14666        .where_(Page::id.eq(page_id))
14667        .first(tenant.pool())
14668        .await?
14669        .ok_or(AdminError::NotFound(page_id))?;
14670
14671    // Reviewer name lookup for the header.
14672    let user_ids: Vec<i64> = [a_row.created_by, b_row.created_by]
14673        .into_iter()
14674        .flatten()
14675        .collect();
14676    let users: Vec<rustango::tenancy::auth::User> = if user_ids.is_empty() {
14677        Vec::new()
14678    } else {
14679        rustango::tenancy::auth::User::objects()
14680            .where_(rustango::tenancy::auth::User::id.is_in(user_ids))
14681            .fetch(tenant.pool())
14682            .await?
14683    };
14684    let username_for = |uid: Option<i64>| -> Option<String> {
14685        uid.and_then(|id| {
14686            users
14687                .iter()
14688                .find(|u| u.id.get().copied() == Some(id))
14689                .map(|u| u.username.clone())
14690        })
14691    };
14692
14693    let diffs = crate::revision::diff_snapshots(&a_row.snapshot, &b_row.snapshot);
14694    let changed_count = diffs.iter().filter(|d| d.is_change()).count();
14695    let only_changes = q.all.is_none();
14696
14697    let mut ctx = Context::new();
14698    add_chrome(&mut ctx, &tenant, "history", session_user.as_ref()).await;
14699    add_admin_theme(&mut ctx, tenant.pool()).await;
14700    ctx.insert("page", &page);
14701    ctx.insert(
14702        "rev_a",
14703        &serde_json::json!({
14704            "id": a_row.id.get().copied(),
14705            "sequence": a_row.sequence,
14706            "created_at": a_row.created_at.get().copied(),
14707            "username": username_for(a_row.created_by),
14708        }),
14709    );
14710    ctx.insert(
14711        "rev_b",
14712        &serde_json::json!({
14713            "id": b_row.id.get().copied(),
14714            "sequence": b_row.sequence,
14715            "created_at": b_row.created_at.get().copied(),
14716            "username": username_for(b_row.created_by),
14717        }),
14718    );
14719    ctx.insert("diffs", &diffs);
14720    ctx.insert("changed_count", &changed_count);
14721    ctx.insert("only_changes", &only_changes);
14722    render_with_csrf(&state, &headers, "rcms_admin/history_diff.html", &mut ctx)
14723}
14724
14725// =====================================================================
14726// Aging-pages report (#101)
14727// =====================================================================
14728
14729#[derive(Debug, Deserialize)]
14730pub struct AnalyticsQuery {
14731    /// Window in days back from now — defaults to 30, clamped 1..=365.
14732    #[serde(default)]
14733    pub days: Option<i64>,
14734}
14735
14736/// GET /cms-admin/analytics — the default first-party analytics
14737/// dashboard: unique visitors, pageviews, bounce, avg time, top pages /
14738/// referrers / countries / devices, a per-day series, and "active now".
14739pub async fn analytics_dashboard(
14740    State(state): State<super::AdminState>,
14741    tenant: Tenant,
14742    headers: HeaderMap,
14743    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
14744    Query(q): Query<AnalyticsQuery>,
14745) -> Result<Response, AdminError> {
14746    let days = q.days.unwrap_or(30).clamp(1, 365);
14747    let to = chrono::Utc::now();
14748    let from = to - chrono::Duration::days(days);
14749    let metrics = crate::analytics::query::compute(tenant.pool(), from, to).await?;
14750    let host = headers
14751        .get(header::HOST)
14752        .and_then(|v| v.to_str().ok())
14753        .unwrap_or("");
14754    let active_now = crate::analytics::presence_count(host);
14755    // Max pageviews across the series → the 100%-height reference for the
14756    // bar chart (min 1 to avoid divide-by-zero).
14757    let series_max = metrics
14758        .series
14759        .iter()
14760        .map(|p| p.pageviews)
14761        .max()
14762        .unwrap_or(0)
14763        .max(1);
14764
14765    let mut ctx = Context::new();
14766    add_chrome(&mut ctx, &tenant, "analytics", session_user.as_ref()).await;
14767    add_admin_theme(&mut ctx, tenant.pool()).await;
14768    ctx.insert("metrics", &metrics);
14769    ctx.insert("active_now", &active_now);
14770    ctx.insert("series_max", &series_max);
14771    ctx.insert("days", &days);
14772    render_with_csrf(&state, &headers, "rcms_admin/analytics.html", &mut ctx)
14773}
14774
14775#[derive(Debug, Deserialize)]
14776pub struct AgingQuery {
14777    /// Minimum days stale — defaults to 90.
14778    #[serde(default)]
14779    pub min_days: Option<i64>,
14780    /// Status filter — defaults to "published". Pass `all` to skip.
14781    #[serde(default)]
14782    pub status: Option<String>,
14783    /// 1-indexed page number.
14784    #[serde(default)]
14785    pub page: Option<u32>,
14786    /// Rows per page.
14787    #[serde(default)]
14788    pub per_page: Option<usize>,
14789}
14790
14791/// GET /cms-admin/reports/aging — table of pages sorted by
14792/// `updated_at` ascending (oldest first). Editors use this to spot
14793/// pages that have gone stale.
14794pub async fn aging_pages_report(
14795    State(state): State<super::AdminState>,
14796    tenant: Tenant,
14797    headers: HeaderMap,
14798    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
14799    Query(q): Query<AgingQuery>,
14800    axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
14801) -> Result<Response, AdminError> {
14802    let page_size = crate::admin::pagination::clamp_per_page(q.per_page);
14803    let min_days = q.min_days.unwrap_or(90).max(0);
14804    let status_filter = q
14805        .status
14806        .as_deref()
14807        .map(str::trim)
14808        .filter(|s| !s.is_empty() && *s != "all")
14809        .map(str::to_owned)
14810        .unwrap_or_else(|| "published".to_owned());
14811
14812    let now = chrono::Utc::now();
14813    let mut q_pages = Page::objects().order_by(&[("updated_at", false)]); // asc
14814    if status_filter != "all" {
14815        q_pages = q_pages.where_(Page::status.eq(status_filter.clone()));
14816    }
14817    let all: Vec<Page> = q_pages.fetch(tenant.pool()).await?;
14818
14819    // Filter by min-days-stale.
14820    let stale: Vec<&Page> = all
14821        .iter()
14822        .filter(|p| match p.updated_at.get().copied() {
14823            Some(ts) => {
14824                let delta = now.signed_duration_since(ts).num_days();
14825                delta >= min_days
14826            }
14827            None => false,
14828        })
14829        .collect();
14830    let total = stale.len();
14831    // Page in memory via `rustango::pagination::Paginator` (matches the
14832    // snippet list); `get_page()` clamps out-of-range numbers to the
14833    // last page so prev/next links never dangle.
14834    let paginator = rustango::pagination::Paginator::new(total, page_size);
14835    let page_obj = paginator.get_page(q.page.unwrap_or(1).max(1) as i64);
14836    let current_page = page_obj.number as u32;
14837    let has_next = page_obj.has_next();
14838    let has_prev = page_obj.has_previous();
14839    let slice: Vec<&&Page> = if total == 0 {
14840        Vec::new()
14841    } else {
14842        stale[page_obj.start_index().saturating_sub(1)..page_obj.end_index()]
14843            .iter()
14844            .collect()
14845    };
14846
14847    // Per-row last editor — pulled from the latest revision per
14848    // page in one batched query.
14849    let page_ids: Vec<i64> = slice.iter().filter_map(|p| p.id.get().copied()).collect();
14850    let revisions: Vec<crate::revision::Revision> = if page_ids.is_empty() {
14851        Vec::new()
14852    } else {
14853        crate::revision::Revision::objects()
14854            .where_(crate::revision::Revision::page_id.is_in(page_ids.iter().copied()))
14855            .order_by(&[("sequence", true)]) // desc, so newest sequence per page first
14856            .fetch(tenant.pool())
14857            .await
14858            .unwrap_or_default()
14859    };
14860    let mut last_editor_by_page: std::collections::HashMap<i64, Option<i64>> =
14861        std::collections::HashMap::new();
14862    for r in &revisions {
14863        // First insertion wins for each page_id since we ordered
14864        // desc by sequence — that's the most-recent revision.
14865        last_editor_by_page.entry(r.page_id).or_insert(r.created_by);
14866    }
14867    let user_ids: Vec<i64> = last_editor_by_page
14868        .values()
14869        .filter_map(|opt| *opt)
14870        .collect();
14871    let users: Vec<rustango::tenancy::auth::User> = if user_ids.is_empty() {
14872        Vec::new()
14873    } else {
14874        rustango::tenancy::auth::User::objects()
14875            .where_(rustango::tenancy::auth::User::id.is_in(user_ids))
14876            .fetch(tenant.pool())
14877            .await
14878            .unwrap_or_default()
14879    };
14880    let username_by_id: std::collections::HashMap<i64, String> = users
14881        .into_iter()
14882        .filter_map(|u| u.id.get().copied().map(|id| (id, u.username)))
14883        .collect();
14884
14885    let rows: Vec<serde_json::Value> = slice
14886        .iter()
14887        .map(|p| {
14888            let pid = p.id.get().copied().unwrap_or_default();
14889            let updated = p.updated_at.get().copied();
14890            let days_stale = updated.map(|ts| now.signed_duration_since(ts).num_days());
14891            let editor = last_editor_by_page
14892                .get(&pid)
14893                .and_then(|v| *v)
14894                .and_then(|uid| username_by_id.get(&uid).cloned());
14895            serde_json::json!({
14896                "id": pid,
14897                "title": p.title,
14898                "url_path": p.url_path,
14899                "status": p.status,
14900                "updated_at": updated,
14901                "days_stale": days_stale,
14902                "last_editor": editor,
14903            })
14904        })
14905        .collect();
14906
14907    let mut ctx = Context::new();
14908    add_chrome(&mut ctx, &tenant, "reports", session_user.as_ref()).await;
14909    add_admin_theme(&mut ctx, tenant.pool()).await;
14910    ctx.insert("rows", &rows);
14911    ctx.insert("min_days", &min_days);
14912    ctx.insert("status_filter", &status_filter);
14913    // #316 — raw query string for the `| querystring(page=…)` pagination
14914    // links (preserves min_days / status + sets page).
14915    ctx.insert("query_string", &raw_query.unwrap_or_default());
14916    ctx.insert("current_page", &current_page);
14917    ctx.insert("has_next", &has_next);
14918    ctx.insert("has_prev", &has_prev);
14919    ctx.insert("total", &total);
14920    ctx.insert("page_size", &page_size);
14921    ctx.insert(
14922        "pagination",
14923        &crate::admin::pagination::context(current_page as i64, page_size, total),
14924    );
14925    render_with_csrf(&state, &headers, "rcms_admin/aging_pages.html", &mut ctx)
14926}
14927
14928/// GET /cms-admin/reports/aging.csv — same data as the HTML view
14929/// but streamed as RFC 4180 CSV. Honors the same `min_days` +
14930/// `status` filters.
14931pub async fn aging_pages_csv(
14932    State(_state): State<super::AdminState>,
14933    tenant: Tenant,
14934    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
14935    Query(q): Query<AgingQuery>,
14936) -> Result<Response, AdminError> {
14937    let min_days = q.min_days.unwrap_or(90).max(0);
14938    let status_filter = q
14939        .status
14940        .as_deref()
14941        .map(str::trim)
14942        .filter(|s| !s.is_empty() && *s != "all")
14943        .map(str::to_owned)
14944        .unwrap_or_else(|| "published".to_owned());
14945    let now = chrono::Utc::now();
14946    let mut q_pages = Page::objects().order_by(&[("updated_at", false)]);
14947    if status_filter != "all" {
14948        q_pages = q_pages.where_(Page::status.eq(status_filter.clone()));
14949    }
14950    let all: Vec<Page> = q_pages.fetch(tenant.pool()).await?;
14951    let stale: Vec<&Page> = all
14952        .iter()
14953        .filter(|p| match p.updated_at.get().copied() {
14954            Some(ts) => now.signed_duration_since(ts).num_days() >= min_days,
14955            None => false,
14956        })
14957        .collect();
14958
14959    let mut out = String::with_capacity(256 + stale.len() * 96);
14960    out.push_str("page_id,title,url_path,status,updated_at,days_stale\n");
14961    for p in stale {
14962        let pid = p.id.get().copied().unwrap_or_default();
14963        let updated = p.updated_at.get().copied();
14964        let days = updated
14965            .map(|ts| now.signed_duration_since(ts).num_days())
14966            .unwrap_or_default();
14967        let when = updated.map(|t| t.to_rfc3339()).unwrap_or_default();
14968        out.push_str(&format!(
14969            "{},{},{},{},{},{}\n",
14970            pid,
14971            csv_escape(&p.title),
14972            csv_escape(&p.url_path),
14973            csv_escape(&p.status),
14974            csv_escape(&when),
14975            days
14976        ));
14977    }
14978    Ok(csv_response("aging-pages", &out))
14979}
14980
14981/// Helper — attach CSV content-type + a date-stamped Content-Disposition.
14982fn csv_response(name: &str, body: &str) -> Response {
14983    let filename = format!("{name}-{}.csv", chrono::Utc::now().format("%Y%m%d"));
14984    let mut response = (
14985        [(header::CONTENT_TYPE, "text/csv; charset=utf-8")],
14986        body.to_owned(),
14987    )
14988        .into_response();
14989    if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{filename}\"")) {
14990        response
14991            .headers_mut()
14992            .insert(header::CONTENT_DISPOSITION, v);
14993    }
14994    response
14995}
14996
14997// =====================================================================
14998// Site settings (#108)
14999// =====================================================================
15000
15001pub async fn site_settings_list(
15002    State(state): State<super::AdminState>,
15003    tenant: Tenant,
15004    headers: HeaderMap,
15005    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
15006) -> Result<Response, AdminError> {
15007    // Not paged: one row per registered settings schema plus any ad-hoc
15008    // scope a developer wrote; settings are not user content.
15009    let rows = crate::site_setting::list_all(tenant.pool())
15010        .await
15011        .unwrap_or_default();
15012    let by_scope: std::collections::HashMap<&str, &crate::site_setting::SiteSetting> =
15013        rows.iter().map(|r| (r.scope.as_str(), r)).collect();
15014    // #406 — registered typed schemas come first and are always listed
15015    // (configured or not); then any
15016    // ad-hoc free-form JSON scopes that aren't backed by a schema.
15017    let mut view: Vec<serde_json::Value> = Vec::new();
15018    for schema in crate::site_setting::registered_schemas() {
15019        let row = by_scope.get(schema.scope).copied();
15020        view.push(serde_json::json!({
15021            "scope": schema.scope,
15022            "label": schema.label,
15023            "typed": true,
15024            "configured": row.is_some(),
15025            "preview": row
15026                .map(|r| serde_json::to_string(&r.value_json).unwrap_or_default())
15027                .unwrap_or_default(),
15028            "updated_at": row.and_then(|r| r.updated_at.get().copied()),
15029        }));
15030    }
15031    for s in &rows {
15032        // A schema's row is listed above; the starter theme's own record
15033        // of which theme it applied is not a setting to edit.
15034        if crate::site_setting::schema_for(&s.scope).is_some() || s.scope == crate::starter::MARKER_SCOPE {
15035            continue;
15036        }
15037        view.push(serde_json::json!({
15038            "scope": s.scope,
15039            "label": s.scope,
15040            "typed": false,
15041            "configured": true,
15042            "preview": serde_json::to_string(&s.value_json).unwrap_or_default(),
15043            "updated_at": s.updated_at.get().copied(),
15044        }));
15045    }
15046    let mut ctx = Context::new();
15047    add_chrome(&mut ctx, &tenant, "site-settings", session_user.as_ref()).await;
15048    add_admin_theme(&mut ctx, tenant.pool()).await;
15049    ctx.insert("rows", &view);
15050    render_with_csrf(
15051        &state,
15052        &headers,
15053        "rcms_admin/site_settings_list.html",
15054        &mut ctx,
15055    )
15056}
15057
15058pub async fn site_setting_edit_form(
15059    State(state): State<super::AdminState>,
15060    tenant: Tenant,
15061    headers: HeaderMap,
15062    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
15063    Path(scope): Path<String>,
15064    Query(q): Query<EditQuery>,
15065) -> Result<Response, AdminError> {
15066    let row = crate::site_setting::get(tenant.pool(), &scope)
15067        .await
15068        .unwrap_or(None);
15069    let stored = row
15070        .as_ref()
15071        .map(|s| s.value_json.clone())
15072        .unwrap_or_else(|| serde_json::json!({}));
15073    let mut ctx = Context::new();
15074    add_chrome(&mut ctx, &tenant, "site-settings", session_user.as_ref()).await;
15075    add_admin_theme(&mut ctx, tenant.pool()).await;
15076    ctx.insert("scope", &scope);
15077    ctx.insert("is_new", &row.is_none());
15078    // #406 — a registered schema renders a typed form; otherwise the
15079    // free-form JSON textarea covers ad-hoc scopes.
15080    if let Some(schema) = crate::site_setting::schema_for(&scope) {
15081        let widgets = crate::site_setting::prefill_widgets((schema.fields)(), &stored);
15082        ctx.insert("typed", &true);
15083        ctx.insert("schema_label", schema.label);
15084        // Other languages: the text fields, translated side by side.
15085        let locales: Vec<crate::locale::Locale> = crate::locale::Locale::objects()
15086            .where_(crate::locale::Locale::active.eq(true))
15087            .order_by(&[("sort_order", false), ("code", false)])
15088            .fetch(tenant.pool())
15089            .await?;
15090        let editing = q
15091            .locale
15092            .as_deref()
15093            .and_then(|c| locales.iter().find(|l| l.code == c && !l.is_default).cloned());
15094        if let (Some(loc), false) = (&editing, row.is_none()) {
15095            let tr = crate::site_setting::translations(&stored, &loc.code);
15096            let rows: Vec<serde_json::Value> = widgets
15097                .iter()
15098                .filter(|w| site_setting_translatable(w))
15099                .map(|w| {
15100                    serde_json::json!({
15101                        "name": w.name,
15102                        "label": w.label,
15103                        "canonical": w.value,
15104                        "multiline": !matches!(w.kind, crate::widget::WidgetKind::Text),
15105                        "value": tr.get(&w.name).and_then(|v| v.as_str()).unwrap_or(""),
15106                    })
15107                })
15108                .collect();
15109            ctx.insert("translation_mode", &true);
15110            ctx.insert("editing_locale", loc);
15111            ctx.insert("tr_rows", &rows);
15112        }
15113        ctx.insert("locales", &locales);
15114        ctx.insert("widgets", &widgets);
15115    } else {
15116        ctx.insert("typed", &false);
15117        let body = serde_json::to_string_pretty(&stored).unwrap_or_else(|_| "{}".to_owned());
15118        ctx.insert("value_pretty", &body);
15119    }
15120    render_with_csrf(
15121        &state,
15122        &headers,
15123        "rcms_admin/site_setting_form.html",
15124        &mut ctx,
15125    )
15126}
15127
15128pub async fn site_setting_edit_submit(
15129    State(_state): State<super::AdminState>,
15130    tenant: Tenant,
15131    headers: HeaderMap,
15132    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
15133    Path(scope): Path<String>,
15134    Form(form): Form<std::collections::HashMap<String, String>>,
15135) -> Result<Response, AdminError> {
15136    // #406 — typed scopes coerce each declared field by widget kind;
15137    // unregistered scopes keep the raw-JSON textarea contract.
15138    let parsed: serde_json::Value = if let Some(schema) = crate::site_setting::schema_for(&scope) {
15139        let fields = (schema.fields)();
15140        let missing = crate::site_setting::missing_required(&fields, &form);
15141        if !missing.is_empty() {
15142            return Err(AdminError::Validation(format!(
15143                "These required fields are empty: {}.",
15144                missing.join(", ")
15145            )));
15146        }
15147        let mut value = crate::site_setting::value_json_from_form(&fields, &form);
15148        if let Ok(Some(old)) = crate::site_setting::get(tenant.pool(), &scope).await {
15149            crate::site_setting::keep_translations(&old.value_json, &mut value);
15150        }
15151        value
15152    } else {
15153        let raw = form.get("value_json").map_or("", |s| s.trim());
15154        if raw.is_empty() {
15155            serde_json::json!({})
15156        } else {
15157            serde_json::from_str(raw)
15158                .map_err(|e| AdminError::Validation(format!("value_json isn't valid JSON: {e}")))?
15159        }
15160    };
15161    crate::site_setting::upsert(tenant.pool(), &scope, parsed).await?;
15162    redirect_named_with_message_args(
15163        "rcms-admin:site-settings:list",
15164        MsgLevel::Success,
15165        "Saved site setting “{scope}”.",
15166        &[("scope", scope.as_str())],
15167        &headers,
15168    )
15169}
15170
15171/// A typed setting field worth translating: free text.
15172fn site_setting_translatable(w: &crate::widget::Widget) -> bool {
15173    use crate::widget::WidgetKind as K;
15174    matches!(w.kind, K::Text | K::Textarea | K::Markdown | K::RichText)
15175}
15176
15177/// POST /cms-admin/site-settings/{scope}/translate?locale=<code> — store
15178/// the text fields' translations in the setting's `_i18n` bag.
15179pub async fn site_setting_translate_submit(
15180    State(_state): State<super::AdminState>,
15181    tenant: Tenant,
15182    headers: HeaderMap,
15183    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
15184    Path(scope): Path<String>,
15185    Query(q): Query<EditQuery>,
15186    Form(form): Form<std::collections::HashMap<String, String>>,
15187) -> Result<Response, AdminError> {
15188    let locale = translate_locale(&tenant, q.locale.as_deref()).await?;
15189    let schema = crate::site_setting::schema_for(&scope)
15190        .ok_or_else(|| AdminError::Validation(format!("`{scope}` has no typed fields to translate")))?;
15191    let row = crate::site_setting::get(tenant.pool(), &scope)
15192        .await?
15193        .ok_or_else(|| AdminError::Validation(format!("save `{scope}` before translating it")))?;
15194    let fields: serde_json::Map<String, serde_json::Value> = (schema.fields)()
15195        .iter()
15196        .filter(|w| site_setting_translatable(w))
15197        .filter_map(|w| {
15198            form.get(&format!("tr__{}", w.name))
15199                .map(|v| (w.name.clone(), serde_json::Value::String(v.trim().to_owned())))
15200        })
15201        .collect();
15202    let mut value = row.value_json;
15203    crate::site_setting::set_translations(&mut value, &locale.code, fields);
15204    crate::site_setting::upsert(tenant.pool(), &scope, value).await?;
15205    Ok(rustango::messages::redirect_with_message(
15206        messages_secret(),
15207        &headers,
15208        MsgLevel::Success,
15209        &super::i18n::tr(&headers, "Translations saved.", &[]),
15210        &format!("/cms-admin/site-settings/{scope}/edit?locale={}", locale.code),
15211    ))
15212}
15213
15214pub async fn site_setting_delete_submit(
15215    State(_state): State<super::AdminState>,
15216    tenant: Tenant,
15217    headers: HeaderMap,
15218    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
15219    Path(scope): Path<String>,
15220) -> Result<Response, AdminError> {
15221    if let Some(row) = crate::site_setting::get(tenant.pool(), &scope)
15222        .await
15223        .unwrap_or(None)
15224    {
15225        row.delete(tenant.pool()).await?;
15226    }
15227    redirect_named_with_message_args(
15228        "rcms-admin:site-settings:list",
15229        MsgLevel::Success,
15230        "Deleted site setting “{scope}”.",
15231        &[("scope", scope.as_str())],
15232        &headers,
15233    )
15234}
15235
15236// =====================================================================
15237// Locked-pages report (#109)
15238// =====================================================================
15239
15240// ----- #143 — search promotions report ---------
15241
15242/// GET /cms-admin/reports/search — top queries by hit count with
15243/// counts of pinned promotions per query.
15244pub async fn search_promotions_report(
15245    State(state): State<super::AdminState>,
15246    tenant: Tenant,
15247    headers: HeaderMap,
15248    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
15249) -> Result<Response, AdminError> {
15250    let top = crate::search_promotion::top_queries(tenant.pool(), 100)
15251        .await
15252        .unwrap_or_default();
15253    // Each query's promotion count, from one grouped query (#628) rather
15254    // than one lookup per row.
15255    let ids: Vec<i64> = top.iter().filter_map(|q| q.id.get().copied()).collect();
15256    let mut promo_counts: std::collections::HashMap<i64, i64> = std::collections::HashMap::new();
15257    if !ids.is_empty() {
15258        use crate::search_promotion::SearchPromotion;
15259        let grouped = SearchPromotion::objects()
15260            .where_(SearchPromotion::query_id.is_in(ids))
15261            .values(&["query_id"])
15262            .annotate("n", rustango::core::aggregates::count_all().into())
15263            .compile()
15264            .map_err(rustango::sql::ExecError::from)?;
15265        let found = rustango::sql::fetch_aggregate_dict(tenant.pool(), &grouped)
15266            .await
15267            .unwrap_or_else(|e| {
15268                tracing::warn!(target: "rustango_cms::admin", error = %e, "promotion counts failed");
15269                Vec::new()
15270            });
15271        for r in found {
15272            if let (Some(qid), Some(n)) = (sql_i64(r.get("query_id")), sql_i64(r.get("n"))) {
15273                promo_counts.insert(qid, n);
15274            }
15275        }
15276    }
15277    let mut rows: Vec<serde_json::Value> = Vec::with_capacity(top.len());
15278    for q in top {
15279        let qid = q.id.get().copied().unwrap_or_default();
15280        rows.push(serde_json::json!({
15281            "id": qid,
15282            "raw": q.raw,
15283            "normalized": q.normalized,
15284            "hits": q.hits,
15285            "last_seen_at": q.last_seen_at.get().copied(),
15286            "promotion_count": promo_counts.get(&qid).copied().unwrap_or(0),
15287        }));
15288    }
15289    let mut ctx = Context::new();
15290    add_chrome(&mut ctx, &tenant, "reports-search", session_user.as_ref()).await;
15291    add_admin_theme(&mut ctx, tenant.pool()).await;
15292    ctx.insert("rows", &rows);
15293    render_with_csrf(
15294        &state,
15295        &headers,
15296        "rcms_admin/search_promotions_report.html",
15297        &mut ctx,
15298    )
15299}
15300
15301/// GET /cms-admin/reports/search/{id}/edit — edit pinned pages for
15302/// one query.
15303pub async fn search_promotion_edit_form(
15304    State(state): State<super::AdminState>,
15305    tenant: Tenant,
15306    headers: HeaderMap,
15307    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
15308    Path(query_id): Path<i64>,
15309) -> Result<Response, AdminError> {
15310    use rustango::core::Column as _;
15311    use rustango::sql::FetcherPool as _;
15312    let queries: Vec<crate::search_promotion::SearchQuery> =
15313        crate::search_promotion::SearchQuery::objects()
15314            .where_(crate::search_promotion::SearchQuery::id.eq(query_id))
15315            .fetch(tenant.pool())
15316            .await?;
15317    let Some(query) = queries.into_iter().next() else {
15318        return Err(AdminError::NotFound(query_id));
15319    };
15320    let promotions = crate::search_promotion::promotions_for_query(tenant.pool(), query_id)
15321        .await
15322        .unwrap_or_default();
15323    let pages: Vec<Page> = Page::objects()
15324        .where_(Page::status.eq("published".to_owned()))
15325        .order_by(&[("title", false)])
15326        .fetch(tenant.pool())
15327        .await
15328        .unwrap_or_default();
15329    let mut ctx = Context::new();
15330    add_chrome(&mut ctx, &tenant, "reports-search", session_user.as_ref()).await;
15331    add_admin_theme(&mut ctx, tenant.pool()).await;
15332    ctx.insert("query", &query);
15333    ctx.insert("promotions", &promotions);
15334    ctx.insert("pages", &pages);
15335    render_with_csrf(
15336        &state,
15337        &headers,
15338        "rcms_admin/search_promotion_edit.html",
15339        &mut ctx,
15340    )
15341}
15342
15343#[derive(Debug, Deserialize)]
15344pub struct SearchPromotionForm {
15345    /// Comma-separated page ids in pin order.
15346    #[serde(default)]
15347    pub page_ids: String,
15348    #[serde(default)]
15349    pub descriptions: String,
15350}
15351
15352/// POST /cms-admin/reports/search/{id}/edit — replace the pinned
15353/// list with the posted ordered page ids.
15354pub async fn search_promotion_edit_submit(
15355    State(_state): State<super::AdminState>,
15356    tenant: Tenant,
15357    headers: HeaderMap,
15358    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
15359    Path(query_id): Path<i64>,
15360    Form(form): Form<SearchPromotionForm>,
15361) -> Result<Response, AdminError> {
15362    use rustango::core::Column as _;
15363    use rustango::sql::Auto;
15364    use rustango::sql::FetcherPool as _;
15365    // Drop existing promotions then re-insert fresh — simpler than
15366    // diffing.
15367    let existing: Vec<crate::search_promotion::SearchPromotion> =
15368        crate::search_promotion::SearchPromotion::objects()
15369            .where_(crate::search_promotion::SearchPromotion::query_id.eq(query_id))
15370            .fetch(tenant.pool())
15371            .await?;
15372    for row in existing {
15373        row.delete(tenant.pool()).await.log_warn("old search promotion not deleted");
15374    }
15375    let ids: Vec<i64> = form
15376        .page_ids
15377        .split(',')
15378        .map(str::trim)
15379        .filter(|s| !s.is_empty())
15380        .filter_map(|s| s.parse::<i64>().ok())
15381        .collect();
15382    let descriptions: Vec<String> = form
15383        .descriptions
15384        .split('\n')
15385        .map(|s| s.trim().to_owned())
15386        .collect();
15387    for (idx, page_id) in ids.iter().enumerate() {
15388        let mut row = crate::search_promotion::SearchPromotion {
15389            id: Auto::Unset,
15390            query_id,
15391            page_id: *page_id,
15392            sort_order: idx as i32,
15393            description: descriptions.get(idx).cloned().unwrap_or_default(),
15394            created_at: Auto::Unset,
15395        };
15396        row.insert(tenant.pool()).await.log_warn("search promotion not saved");
15397    }
15398    redirect_named_with_message_plural(
15399        "rcms-admin:reports:search",
15400        MsgLevel::Success,
15401        "Saved {count} pinned result(s).",
15402        ids.len() as i64,
15403        &[("count", &ids.len().to_string())],
15404        &headers,
15405    )
15406}
15407
15408// ----- #141 — scheduled-publish report ---------
15409
15410/// Derive the effective lifecycle state from `go_live_at`.
15411/// Any row carrying a future
15412/// `go_live_at` is treated as `scheduled` regardless of the editor's
15413/// literal status pick (draft / published) so the sweep job +
15414/// scheduled-report query pick it up. Clearing `go_live_at` on a
15415/// previously-scheduled row falls back to `draft` so the row stops
15416/// claiming a schedule it no longer has.
15417///
15418/// `archived` is preserved either way — archive is an explicit
15419/// lifecycle terminus and an editor un-archives via a different
15420/// path. A scheduled row whose `go_live_at` has already passed is
15421/// left alone too; the sweep is the one that flips it to `published`,
15422/// and stepping in here would steal that transition.
15423pub(crate) fn derive_scheduled_status(
15424    current: &str,
15425    go_live_at: Option<chrono::DateTime<chrono::Utc>>,
15426) -> String {
15427    let archived = crate::page::PageStatus::Archived.as_str();
15428    if current == archived {
15429        return current.to_owned();
15430    }
15431    let now = chrono::Utc::now();
15432    let future = go_live_at.is_some_and(|t| t > now);
15433    let scheduled = crate::page::PageStatus::Scheduled.as_str();
15434    let draft = crate::page::PageStatus::Draft.as_str();
15435    match (current, future, go_live_at) {
15436        (_, true, _) => scheduled.to_owned(),
15437        (s, false, None) if s == scheduled => draft.to_owned(),
15438        _ => current.to_owned(),
15439    }
15440}
15441
15442#[cfg(test)]
15443mod scheduled_status_tests {
15444    use super::derive_scheduled_status;
15445    use chrono::{Duration, Utc};
15446
15447    #[test]
15448    fn future_go_live_promotes_draft_to_scheduled() {
15449        let go = Utc::now() + Duration::hours(1);
15450        assert_eq!(derive_scheduled_status("draft", Some(go)), "scheduled");
15451    }
15452
15453    #[test]
15454    fn future_go_live_also_promotes_published() {
15455        // Editor picked "published" + a future go-live. The row
15456        // defers to the sweep — surface as scheduled.
15457        let go = Utc::now() + Duration::hours(2);
15458        assert_eq!(derive_scheduled_status("published", Some(go)), "scheduled");
15459    }
15460
15461    #[test]
15462    fn cleared_go_live_demotes_scheduled_to_draft() {
15463        assert_eq!(derive_scheduled_status("scheduled", None), "draft");
15464    }
15465
15466    #[test]
15467    fn past_go_live_on_scheduled_left_alone_for_sweep() {
15468        let past = Utc::now() - Duration::hours(1);
15469        assert_eq!(
15470            derive_scheduled_status("scheduled", Some(past)),
15471            "scheduled",
15472        );
15473    }
15474
15475    #[test]
15476    fn archived_preserved_regardless_of_go_live() {
15477        let go = Utc::now() + Duration::hours(1);
15478        assert_eq!(derive_scheduled_status("archived", Some(go)), "archived");
15479        assert_eq!(derive_scheduled_status("archived", None), "archived");
15480    }
15481
15482    #[test]
15483    fn draft_with_no_go_live_unchanged() {
15484        assert_eq!(derive_scheduled_status("draft", None), "draft");
15485    }
15486
15487    #[test]
15488    fn published_with_no_go_live_unchanged() {
15489        assert_eq!(derive_scheduled_status("published", None), "published");
15490    }
15491}
15492
15493/// Build the dataset for the scheduled-publish report: every page
15494/// with a future `go_live_at` plus every published page with a
15495/// future `expire_at`. Rows sorted by go_live_at ascending (soonest
15496/// first), with expirations interleaved by their expire_at.
15497async fn scheduled_pages_rows(
15498    pool: &rustango::sql::Pool,
15499) -> Result<Vec<serde_json::Value>, rustango::sql::ExecError> {
15500    use rustango::sql::FetcherPool as _;
15501    let pages: Vec<Page> = Page::objects().fetch(pool).await?;
15502    let now = chrono::Utc::now();
15503    let mut rows: Vec<serde_json::Value> = Vec::new();
15504    for p in &pages {
15505        let pid = p.id.get().copied().unwrap_or_default();
15506        if let Some(go) = p.go_live_at {
15507            // #264 — surface any page with a future `go_live_at`,
15508            // even if its status hasn't been coerced to "scheduled"
15509            // yet (the save handler now does the coercion, but legacy
15510            // rows or out-of-band edits may have `go_live_at` set on
15511            // a draft/published row — the editor still wants to see
15512            // the upcoming flip). Archived / expired rows are excluded
15513            // because both are explicit lifecycle termini.
15514            if go > now
15515                && p.status != crate::page::PageStatus::Archived.as_str()
15516                && p.status != crate::page::PageStatus::Expired.as_str()
15517            {
15518                let countdown = (go - now).num_seconds();
15519                rows.push(serde_json::json!({
15520                    "kind": "publish",
15521                    "when": go,
15522                    "countdown_secs": countdown,
15523                    "page_id": pid,
15524                    "title": p.title,
15525                    "url_path": p.url_path,
15526                    "status": p.status,
15527                }));
15528            }
15529        }
15530        if let Some(exp) = p.expire_at {
15531            // A scheduled page with both dates comes down too: list it.
15532            if exp > now
15533                && (p.status == crate::page::PageStatus::Published.as_str()
15534                    || p.status == crate::page::PageStatus::Scheduled.as_str())
15535            {
15536                let countdown = (exp - now).num_seconds();
15537                rows.push(serde_json::json!({
15538                    "kind": "expire",
15539                    "when": exp,
15540                    "countdown_secs": countdown,
15541                    "page_id": pid,
15542                    "title": p.title,
15543                    "url_path": p.url_path,
15544                    "status": p.status,
15545                }));
15546            }
15547        }
15548    }
15549    rows.sort_by_key(|r| {
15550        r.get("countdown_secs")
15551            .and_then(|v| v.as_i64())
15552            .unwrap_or(i64::MAX)
15553    });
15554    Ok(rows)
15555}
15556
15557pub async fn scheduled_report(
15558    State(state): State<super::AdminState>,
15559    tenant: Tenant,
15560    headers: HeaderMap,
15561    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
15562) -> Result<Response, AdminError> {
15563    let rows = scheduled_pages_rows(tenant.pool())
15564        .await
15565        .unwrap_or_default();
15566    let mut ctx = Context::new();
15567    add_chrome(
15568        &mut ctx,
15569        &tenant,
15570        "reports-scheduled",
15571        session_user.as_ref(),
15572    )
15573    .await;
15574    add_admin_theme(&mut ctx, tenant.pool()).await;
15575    ctx.insert("rows", &rows);
15576    render_with_csrf(
15577        &state,
15578        &headers,
15579        "rcms_admin/scheduled_report.html",
15580        &mut ctx,
15581    )
15582}
15583
15584pub async fn scheduled_report_csv(
15585    State(_state): State<super::AdminState>,
15586    tenant: Tenant,
15587    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
15588) -> Result<Response, AdminError> {
15589    let rows = scheduled_pages_rows(tenant.pool())
15590        .await
15591        .unwrap_or_default();
15592    let mut out = String::with_capacity(256 + rows.len() * 160);
15593    out.push_str("kind,page_id,title,url_path,status,when,countdown_secs\n");
15594    for r in &rows {
15595        out.push_str(&format!(
15596            "{},{},{},{},{},{},{}\n",
15597            csv_escape(r.get("kind").and_then(|v| v.as_str()).unwrap_or_default()),
15598            r.get("page_id")
15599                .and_then(|v| v.as_i64())
15600                .unwrap_or_default(),
15601            csv_escape(r.get("title").and_then(|v| v.as_str()).unwrap_or_default()),
15602            csv_escape(
15603                r.get("url_path")
15604                    .and_then(|v| v.as_str())
15605                    .unwrap_or_default()
15606            ),
15607            csv_escape(r.get("status").and_then(|v| v.as_str()).unwrap_or_default()),
15608            csv_escape(&r.get("when").map(ToString::to_string).unwrap_or_default()),
15609            r.get("countdown_secs")
15610                .and_then(|v| v.as_i64())
15611                .unwrap_or_default(),
15612        ));
15613    }
15614    Ok(csv_response("scheduled-pages", &out))
15615}
15616
15617/// Build the locked-pages dataset: every live PageLock joined with
15618/// its page + holder username. Returns rows sorted by acquired_at
15619/// desc (newest holds first). Excludes stale locks past their TTL.
15620async fn locked_pages_rows(
15621    pool: &rustango::sql::Pool,
15622) -> Result<Vec<serde_json::Value>, rustango::sql::ExecError> {
15623    use rustango::sql::FetcherPool as _;
15624    let locks: Vec<crate::lock::PageLock> = crate::lock::PageLock::objects()
15625        .order_by(&[("acquired_at", true)]) // desc
15626        .fetch(pool)
15627        .await?;
15628    let now = chrono::Utc::now();
15629    let live: Vec<&crate::lock::PageLock> = locks.iter().filter(|l| !l.is_stale(now)).collect();
15630    if live.is_empty() {
15631        return Ok(Vec::new());
15632    }
15633    let page_ids: Vec<i64> = live.iter().map(|l| l.page_id).collect();
15634    let user_ids: Vec<i64> = live.iter().map(|l| l.user_id).collect();
15635    let pages: Vec<Page> = Page::objects()
15636        .where_(Page::id.is_in(page_ids))
15637        .fetch(pool)
15638        .await
15639        .unwrap_or_default();
15640    let users: Vec<rustango::tenancy::auth::User> = rustango::tenancy::auth::User::objects()
15641        .where_(rustango::tenancy::auth::User::id.is_in(user_ids))
15642        .fetch(pool)
15643        .await
15644        .unwrap_or_default();
15645    let page_by_id: std::collections::HashMap<i64, &Page> = pages
15646        .iter()
15647        .filter_map(|p| p.id.get().copied().map(|id| (id, p)))
15648        .collect();
15649    let user_by_id: std::collections::HashMap<i64, String> = users
15650        .into_iter()
15651        .filter_map(|u| u.id.get().copied().map(|id| (id, u.username)))
15652        .collect();
15653    Ok(live
15654        .into_iter()
15655        .map(|l| {
15656            let title = page_by_id
15657                .get(&l.page_id)
15658                .map(|p| p.title.clone())
15659                .unwrap_or_else(|| format!("page #{}", l.page_id));
15660            let url_path = page_by_id
15661                .get(&l.page_id)
15662                .map(|p| p.url_path.clone())
15663                .unwrap_or_default();
15664            let username = user_by_id
15665                .get(&l.user_id)
15666                .cloned()
15667                .unwrap_or_else(|| format!("user#{}", l.user_id));
15668            let ttl_remaining = (l.expires_at - now).num_seconds();
15669            serde_json::json!({
15670                "page_id": l.page_id,
15671                "title": title,
15672                "url_path": url_path,
15673                "user_id": l.user_id,
15674                "username": username,
15675                "acquired_at": l.acquired_at.get().copied(),
15676                "expires_at": l.expires_at,
15677                "ttl_remaining_secs": ttl_remaining,
15678            })
15679        })
15680        .collect())
15681}
15682
15683pub async fn locked_pages_report(
15684    State(state): State<super::AdminState>,
15685    tenant: Tenant,
15686    headers: HeaderMap,
15687    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
15688) -> Result<Response, AdminError> {
15689    let rows = locked_pages_rows(tenant.pool()).await.unwrap_or_default();
15690    let mut ctx = Context::new();
15691    add_chrome(&mut ctx, &tenant, "reports-locked", session_user.as_ref()).await;
15692    add_admin_theme(&mut ctx, tenant.pool()).await;
15693    ctx.insert("rows", &rows);
15694    render_with_csrf(&state, &headers, "rcms_admin/locked_pages.html", &mut ctx)
15695}
15696
15697pub async fn locked_pages_csv(
15698    State(_state): State<super::AdminState>,
15699    tenant: Tenant,
15700    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
15701) -> Result<Response, AdminError> {
15702    let rows = locked_pages_rows(tenant.pool()).await.unwrap_or_default();
15703    let mut out = String::with_capacity(256 + rows.len() * 128);
15704    out.push_str("page_id,title,url_path,username,acquired_at,expires_at\n");
15705    for r in &rows {
15706        out.push_str(&format!(
15707            "{},{},{},{},{},{}\n",
15708            r.get("page_id")
15709                .and_then(|v| v.as_i64())
15710                .unwrap_or_default(),
15711            csv_escape(r.get("title").and_then(|v| v.as_str()).unwrap_or_default()),
15712            csv_escape(
15713                r.get("url_path")
15714                    .and_then(|v| v.as_str())
15715                    .unwrap_or_default()
15716            ),
15717            csv_escape(
15718                r.get("username")
15719                    .and_then(|v| v.as_str())
15720                    .unwrap_or_default()
15721            ),
15722            csv_escape(
15723                r.get("acquired_at")
15724                    .and_then(|v| v.as_str())
15725                    .unwrap_or_default()
15726            ),
15727            csv_escape(
15728                r.get("expires_at")
15729                    .and_then(|v| v.as_str())
15730                    .unwrap_or_default()
15731            ),
15732        ));
15733    }
15734    Ok(csv_response("locked-pages", &out))
15735}
15736
15737// =====================================================================
15738// Workflows report (#109)
15739// =====================================================================
15740
15741/// The report rows, newest first: one page of them for the screen
15742/// (`window` = limit, offset; #628), every row for the CSV.
15743async fn workflows_report_rows(
15744    pool: &rustango::sql::Pool,
15745    window: Option<(i64, i64)>,
15746) -> Result<Vec<serde_json::Value>, rustango::sql::ExecError> {
15747    use rustango::sql::FetcherPool as _;
15748    let mut qs = crate::workflow::WorkflowState::objects().order_by(&[("requested_at", true), ("id", true)]);
15749    if let Some((limit, offset)) = window {
15750        qs = qs.limit(limit).offset(offset);
15751    }
15752    let states: Vec<crate::workflow::WorkflowState> = qs.fetch(pool).await?;
15753    if states.is_empty() {
15754        return Ok(Vec::new());
15755    }
15756    let workflow_ids: Vec<i64> = states.iter().map(|s| s.workflow_id).collect();
15757    let page_ids: Vec<i64> = states.iter().map(|s| s.page_id).collect();
15758    let user_ids: Vec<i64> = states.iter().map(|s| s.requested_by).collect();
15759    let workflows: Vec<crate::workflow::Workflow> = crate::workflow::Workflow::objects()
15760        .where_(crate::workflow::Workflow::id.is_in(workflow_ids))
15761        .fetch(pool)
15762        .await
15763        .unwrap_or_default();
15764    let pages: Vec<Page> = Page::objects()
15765        .where_(Page::id.is_in(page_ids))
15766        .fetch(pool)
15767        .await
15768        .unwrap_or_default();
15769    let users: Vec<rustango::tenancy::auth::User> = rustango::tenancy::auth::User::objects()
15770        .where_(rustango::tenancy::auth::User::id.is_in(user_ids))
15771        .fetch(pool)
15772        .await
15773        .unwrap_or_default();
15774    let task_ids: Vec<i64> = states.iter().filter_map(|s| s.current_task_id).collect();
15775    let tasks: Vec<crate::workflow::WorkflowTask> = if task_ids.is_empty() {
15776        Vec::new()
15777    } else {
15778        crate::workflow::WorkflowTask::objects()
15779            .where_(crate::workflow::WorkflowTask::id.is_in(task_ids))
15780            .fetch(pool)
15781            .await
15782            .unwrap_or_default()
15783    };
15784    let workflow_by_id: std::collections::HashMap<i64, String> = workflows
15785        .into_iter()
15786        .filter_map(|w| w.id.get().copied().map(|id| (id, w.name)))
15787        .collect();
15788    let page_by_id: std::collections::HashMap<i64, &Page> = pages
15789        .iter()
15790        .filter_map(|p| p.id.get().copied().map(|id| (id, p)))
15791        .collect();
15792    let user_by_id: std::collections::HashMap<i64, String> = users
15793        .into_iter()
15794        .filter_map(|u| u.id.get().copied().map(|id| (id, u.username)))
15795        .collect();
15796    let task_by_id: std::collections::HashMap<i64, String> = tasks
15797        .into_iter()
15798        .filter_map(|t| t.id.get().copied().map(|id| (id, t.name)))
15799        .collect();
15800    Ok(states
15801        .iter()
15802        .map(|s| {
15803            serde_json::json!({
15804                "id": s.id.get().copied(),
15805                "workflow_name": workflow_by_id.get(&s.workflow_id).cloned().unwrap_or_else(|| format!("workflow #{}", s.workflow_id)),
15806                "page_id": s.page_id,
15807                "page_title": page_by_id.get(&s.page_id).map(|p| p.title.clone()).unwrap_or_else(|| format!("page #{}", s.page_id)),
15808                "page_url_path": page_by_id.get(&s.page_id).map(|p| p.url_path.clone()).unwrap_or_default(),
15809                "status": s.status,
15810                "current_task_name": s.current_task_id.and_then(|tid| task_by_id.get(&tid).cloned()),
15811                "requested_by_username": user_by_id.get(&s.requested_by).cloned(),
15812                "requested_at": s.requested_at.get().copied(),
15813                "finished_at": s.finished_at,
15814            })
15815        })
15816        .collect())
15817}
15818
15819pub async fn workflows_report(
15820    State(state): State<super::AdminState>,
15821    tenant: Tenant,
15822    headers: HeaderMap,
15823    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
15824    Query(paging): Query<crate::admin::pagination::PageQuery>,
15825    axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
15826) -> Result<Response, AdminError> {
15827    let total = crate::workflow::WorkflowState::objects().count(tenant.pool()).await?;
15828    let window = paging.window(usize::try_from(total).unwrap_or_default());
15829    let rows = workflows_report_rows(tenant.pool(), Some((window.limit, window.offset))).await?;
15830    let mut ctx = Context::new();
15831    ctx.insert("pagination", &window.context);
15832    ctx.insert("query_string", &raw_query.unwrap_or_default());
15833    add_chrome(
15834        &mut ctx,
15835        &tenant,
15836        "reports-workflows",
15837        session_user.as_ref(),
15838    )
15839    .await;
15840    add_admin_theme(&mut ctx, tenant.pool()).await;
15841    ctx.insert("rows", &rows);
15842    render_with_csrf(
15843        &state,
15844        &headers,
15845        "rcms_admin/workflow_report.html",
15846        &mut ctx,
15847    )
15848}
15849
15850// =====================================================================
15851// #122 — revision storage report + manual prune.
15852// =====================================================================
15853
15854/// GET /cms-admin/reports/revisions — list pages ordered by revision
15855/// count so editors can see which ones accumulate history fastest.
15856/// Surface a "Prune now" form scoped to the whole tenant.
15857pub async fn revisions_report(
15858    State(state): State<super::AdminState>,
15859    tenant: Tenant,
15860    headers: HeaderMap,
15861    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
15862    Query(paging): Query<crate::admin::pagination::PageQuery>,
15863    axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
15864) -> Result<Response, AdminError> {
15865    use crate::revision::Revision;
15866    use rustango::core::aggregates::count_all;
15867    use rustango::sql::FetcherPool as _;
15868    let pool = tenant.pool();
15869    // Counted in SQL (#627): this used to load every revision — each a
15870    // full page snapshot — to count them per page.
15871    let grouped = Revision::objects()
15872        .values(&["page_id"])
15873        .annotate("n", count_all().into())
15874        .order_by(&[("n", true), ("page_id", false)])
15875        .compile()
15876        .map_err(rustango::sql::ExecError::from)?;
15877    let counts: Vec<(i64, i64)> = rustango::sql::fetch_aggregate_dict(pool, &grouped)
15878        .await?
15879        .into_iter()
15880        .filter_map(|r| Some((sql_i64(r.get("page_id"))?, sql_i64(r.get("n"))?)))
15881        .collect();
15882    let total_revisions: i64 = counts.iter().map(|(_, n)| n).sum();
15883    let window = paging.window(counts.len());
15884    let slice: Vec<(i64, i64)> = counts
15885        .into_iter()
15886        .skip(usize::try_from(window.offset).unwrap_or_default())
15887        .take(usize::try_from(window.limit).unwrap_or_default())
15888        .collect();
15889    let pages: std::collections::HashMap<i64, Page> = if slice.is_empty() {
15890        std::collections::HashMap::new()
15891    } else {
15892        Page::objects()
15893            .where_(Page::id.is_in(slice.iter().map(|(id, _)| *id).collect::<Vec<_>>()))
15894            .fetch(pool)
15895            .await?
15896            .into_iter()
15897            .filter_map(|p| p.id.get().copied().map(|id| (id, p)))
15898            .collect()
15899    };
15900    let rows: Vec<serde_json::Value> = slice
15901        .iter()
15902        .filter_map(|(pid, n)| {
15903            let p = pages.get(pid)?;
15904            Some(serde_json::json!({
15905                "page_id": pid,
15906                "title": p.title,
15907                "url_path": p.url_path,
15908                "status": p.status,
15909                "revision_count": n,
15910            }))
15911        })
15912        .collect();
15913    let mut ctx = Context::new();
15914    add_chrome(
15915        &mut ctx,
15916        &tenant,
15917        "reports-revisions",
15918        session_user.as_ref(),
15919    )
15920    .await;
15921    add_admin_theme(&mut ctx, tenant.pool()).await;
15922    ctx.insert("rows", &rows);
15923    ctx.insert("total_revisions", &total_revisions);
15924    ctx.insert("pagination", &window.context);
15925    ctx.insert("query_string", &raw_query.unwrap_or_default());
15926    ctx.insert("default_keep_latest", &crate::revision::DEFAULT_KEEP_LATEST);
15927    render_with_csrf(
15928        &state,
15929        &headers,
15930        "rcms_admin/revisions_report.html",
15931        &mut ctx,
15932    )
15933}
15934
15935/// An integer from an aggregate row (dynamically typed per backend).
15936/// `group_col → row count` over `qs`, from one grouped query instead of
15937/// loading every row to count it. Rows whose group is NULL are left out.
15938async fn counts_by<T: rustango::core::Model>(
15939    pool: &rustango::sql::Pool,
15940    qs: rustango::query::QuerySet<T>,
15941    group_col: &'static str,
15942) -> Result<std::collections::HashMap<i64, i64>, rustango::sql::ExecError> {
15943    let grouped = qs
15944        .values(&[group_col])
15945        .annotate("n", rustango::core::aggregates::count_all().into())
15946        .compile()
15947        .map_err(rustango::sql::ExecError::from)?;
15948    Ok(rustango::sql::fetch_aggregate_dict(pool, &grouped)
15949        .await?
15950        .into_iter()
15951        .filter_map(|r| Some((sql_i64(r.get(group_col))?, sql_i64(r.get("n"))?)))
15952        .collect())
15953}
15954
15955fn sql_i64(v: Option<&rustango::core::SqlValue>) -> Option<i64> {
15956    use rustango::core::SqlValue;
15957    match v? {
15958        SqlValue::I64(n) => Some(*n),
15959        SqlValue::I32(n) => Some(i64::from(*n)),
15960        SqlValue::I16(n) => Some(i64::from(*n)),
15961        SqlValue::F64(n) => Some(*n as i64),
15962        _ => None,
15963    }
15964}
15965
15966/// Form posted from the revisions report's "Prune now" button.
15967#[derive(Debug, Deserialize)]
15968pub struct RevisionsPruneForm {
15969    #[serde(default)]
15970    pub keep_latest: Option<usize>,
15971    #[serde(default)]
15972    pub include_published: Option<String>,
15973}
15974
15975/// POST /cms-admin/reports/revisions/prune — manual prune. Honours
15976/// the same `(keep_latest, keep_published)` knobs as the library
15977/// helper. Redirects back to the report with a count flash.
15978pub async fn revisions_report_prune(
15979    State(_state): State<super::AdminState>,
15980    tenant: Tenant,
15981    headers: HeaderMap,
15982    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
15983    Form(form): Form<RevisionsPruneForm>,
15984) -> Result<Response, AdminError> {
15985    let keep_latest = form
15986        .keep_latest
15987        .unwrap_or(crate::revision::DEFAULT_KEEP_LATEST)
15988        .max(1);
15989    // The form check sends "1" when the box is ticked → keep
15990    // published-status revisions. Unchecked = include them in the
15991    // sweep (more aggressive).
15992    let keep_published = form.include_published.as_deref() != Some("1");
15993    let (pages_scanned, rows_deleted) =
15994        crate::revision::prune_all_pages(tenant.pool(), keep_latest, keep_published)
15995            .await
15996            .unwrap_or((0, 0));
15997    let revisions = super::i18n::tr_plural(
15998        &headers,
15999        "{count} revision(s)",
16000        rows_deleted as i64,
16001        &[("count", &rows_deleted.to_string())],
16002    );
16003    let pages_ph = super::i18n::tr_plural(
16004        &headers,
16005        "{count} page(s)",
16006        pages_scanned as i64,
16007        &[("count", &pages_scanned.to_string())],
16008    );
16009    let kl = keep_latest.to_string();
16010    let kp = keep_published.to_string();
16011    redirect_named_with_message_args(
16012        "rcms-admin:reports:revisions",
16013        MsgLevel::Success,
16014        "Pruned {revisions} across {pages} (keep_latest={keep_latest}, keep_published={keep_published}).",
16015        &[
16016            ("revisions", revisions.as_str()),
16017            ("pages", pages_ph.as_str()),
16018            ("keep_latest", kl.as_str()),
16019            ("keep_published", kp.as_str()),
16020        ],
16021        &headers,
16022    )
16023}
16024
16025pub async fn workflows_report_csv(
16026    State(_state): State<super::AdminState>,
16027    tenant: Tenant,
16028    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
16029) -> Result<Response, AdminError> {
16030    let rows = workflows_report_rows(tenant.pool(), None)
16031        .await
16032        .unwrap_or_default();
16033    let mut out = String::with_capacity(256 + rows.len() * 192);
16034    out.push_str("workflow,page_id,page_title,page_url,status,current_task,requested_by,requested_at,finished_at\n");
16035    for r in &rows {
16036        out.push_str(&format!(
16037            "{},{},{},{},{},{},{},{},{}\n",
16038            csv_escape(
16039                r.get("workflow_name")
16040                    .and_then(|v| v.as_str())
16041                    .unwrap_or_default()
16042            ),
16043            r.get("page_id")
16044                .and_then(|v| v.as_i64())
16045                .unwrap_or_default(),
16046            csv_escape(
16047                r.get("page_title")
16048                    .and_then(|v| v.as_str())
16049                    .unwrap_or_default()
16050            ),
16051            csv_escape(
16052                r.get("page_url_path")
16053                    .and_then(|v| v.as_str())
16054                    .unwrap_or_default()
16055            ),
16056            csv_escape(r.get("status").and_then(|v| v.as_str()).unwrap_or_default()),
16057            csv_escape(
16058                r.get("current_task_name")
16059                    .and_then(|v| v.as_str())
16060                    .unwrap_or_default()
16061            ),
16062            csv_escape(
16063                r.get("requested_by_username")
16064                    .and_then(|v| v.as_str())
16065                    .unwrap_or_default()
16066            ),
16067            csv_escape(
16068                r.get("requested_at")
16069                    .and_then(|v| v.as_str())
16070                    .unwrap_or_default()
16071            ),
16072            csv_escape(
16073                r.get("finished_at")
16074                    .and_then(|v| v.as_str())
16075                    .unwrap_or_default()
16076            ),
16077        ));
16078    }
16079    Ok(csv_response("workflow-report", &out))
16080}
16081
16082// =====================================================================
16083// Global admin search (#77 — stage 0)
16084// =====================================================================
16085
16086/// Query for the global search. `q` is the search needle; when
16087/// `autocomplete=1` is set the handler returns a JSON shape suited
16088/// to the topbar dropdown (no surrounding chrome).
16089#[derive(Debug, Deserialize)]
16090pub struct AdminSearchQuery {
16091    #[serde(default)]
16092    pub q: Option<String>,
16093    #[serde(default)]
16094    pub autocomplete: Option<String>,
16095}
16096
16097/// Query string for `GET /cms-admin/__page-chooser`.
16098#[derive(Debug, Deserialize)]
16099pub struct PageChooserQuery {
16100    #[serde(default)]
16101    pub q: Option<String>,
16102}
16103
16104/// Query string for the generic `GET /cms-admin/__chooser/{slug}`.
16105#[derive(Debug, Default, Deserialize)]
16106pub struct ChooserSearchQuery {
16107    #[serde(default)]
16108    pub q: Option<String>,
16109}
16110
16111/// GET `/cms-admin/__chooser/{slug}?q=<needle>` — JSON endpoint
16112/// backing any `register_chooser!`ed model, generalising the three
16113/// bespoke choosers. Returns `{ "items": [ { id, title, sub, … } ] }`,
16114/// the shape the shared overlay (`cms-ux.js`) renders. Unknown slug → 404.
16115pub async fn chooser_search_json(
16116    State(_state): State<super::AdminState>,
16117    tenant: Tenant,
16118    Path(slug): Path<String>,
16119    Query(q): Query<ChooserSearchQuery>,
16120) -> Result<Response, AdminError> {
16121    let Some(cvs) = super::chooser::find(&slug) else {
16122        return Ok((axum::http::StatusCode::NOT_FOUND, "unknown chooser").into_response());
16123    };
16124    let items = (cvs.search_rows)(tenant.pool().clone(), q.q.unwrap_or_default()).await;
16125    let body = serde_json::json!({ "items": items });
16126    Ok((
16127        [(header::CONTENT_TYPE, "application/json")],
16128        serde_json::to_string(&body).unwrap_or_else(|_| "{}".to_owned()),
16129    )
16130        .into_response())
16131}
16132
16133/// Query string for `GET /cms-admin/__media-picker`.
16134#[derive(Debug, Default, Deserialize)]
16135pub struct MediaPickerQuery {
16136    #[serde(default)]
16137    pub q: Option<String>,
16138    /// Collection filter: omitted = all collections, `0` = uncategorized
16139    /// (NULL collection_id), any other value = that exact collection.
16140    #[serde(default)]
16141    pub collection: Option<i64>,
16142    /// `"image"` (default) | `"document"` | `"other"` | `"any"`.
16143    #[serde(default)]
16144    pub kind: Option<String>,
16145    /// Comma-separated media ids — resolve exactly these rows (any kind
16146    /// unless `kind` is set explicitly). Used by the widget-label
16147    /// hydration pass to turn a server-rendered `#42` into the title.
16148    #[serde(default)]
16149    pub ids: Option<String>,
16150    #[serde(default)]
16151    pub limit: Option<usize>,
16152    #[serde(default)]
16153    pub offset: Option<usize>,
16154}
16155
16156/// GET `/cms-admin/__media-picker` — the media picker's data endpoint.
16157///
16158/// Richer than the generic `/cms-admin/__chooser/media` (which stays for
16159/// back-compat): collection + kind filters, offset pagination, and
16160/// server-computed `thumb_url`/`preview_url` rendition URLs. The URLs are
16161/// built here (not in JS) because renditions can be signature-gated
16162/// and only the server can sign a spec.
16163///
16164/// Filtering is in-Rust over a full fetch — the crate's tri-dialect
16165/// convention (see `render_media_list`); no SQL LIKE.
16166pub async fn media_picker_json(
16167    State(_state): State<super::AdminState>,
16168    tenant: Tenant,
16169    Query(q): Query<MediaPickerQuery>,
16170) -> Result<Response, AdminError> {
16171    let body = media_picker_payload(tenant.pool(), &q).await?;
16172    Ok((
16173        [(header::CONTENT_TYPE, "application/json")],
16174        serde_json::to_string(&body).unwrap_or_else(|_| "{}".to_owned()),
16175    )
16176        .into_response())
16177}
16178
16179/// Core of [`media_picker_json`], split out so unit tests can drive it with
16180/// an in-memory pool (the handler's `Tenant`/`State` extractors need a full
16181/// admin app).
16182pub(crate) async fn media_picker_payload(
16183    pool: &rustango::sql::Pool,
16184    q: &MediaPickerQuery,
16185) -> Result<serde_json::Value, AdminError> {
16186    let mut rows: Vec<Media> = Media::objects()
16187        .order_by(&[("uploaded_at", true)])
16188        .fetch(pool)
16189        .await?;
16190
16191    // Explicit-id lookup (label hydration): keep exactly those rows, and
16192    // default the kind filter OFF — a video/document id must resolve too.
16193    let id_set: Option<std::collections::HashSet<i64>> = q.ids.as_deref().map(|s| {
16194        s.split(',')
16195            .filter_map(|t| t.trim().parse::<i64>().ok())
16196            .collect()
16197    });
16198    if let Some(ids) = &id_set {
16199        rows.retain(|m| m.id.get().copied().is_some_and(|id| ids.contains(&id)));
16200    }
16201    // Kind filter — the picker is image-first ("Choose an image…");
16202    // documents have their own chooser kind. `any` opts out.
16203    let kind = q
16204        .kind
16205        .as_deref()
16206        .unwrap_or(if id_set.is_some() { "any" } else { "image" });
16207    if kind != "any" {
16208        rows.retain(|m| m.kind == kind);
16209    }
16210    // Per-collection counts for the dropdown, computed over the kind-filtered
16211    // set (before collection/search narrow it) so the numbers answer
16212    // "how many would this filter show?".
16213    let mut collection_counts: std::collections::HashMap<i64, i64> =
16214        std::collections::HashMap::new();
16215    let mut uncategorized_count: i64 = 0;
16216    for m in &rows {
16217        match m.collection_id {
16218            Some(cid) => *collection_counts.entry(cid).or_default() += 1,
16219            None => uncategorized_count += 1,
16220        }
16221    }
16222    match q.collection {
16223        Some(0) => rows.retain(|m| m.collection_id.is_none()),
16224        Some(cid) => rows.retain(|m| m.collection_id == Some(cid)),
16225        None => {}
16226    }
16227    if let Some(needle) = q.q.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
16228        let needle = needle.to_lowercase();
16229        rows.retain(|m| {
16230            m.title.to_lowercase().contains(&needle)
16231                || m.filename.to_lowercase().contains(&needle)
16232                || m.alt_text.to_lowercase().contains(&needle)
16233                || m.description.to_lowercase().contains(&needle)
16234        });
16235    }
16236
16237    let total = rows.len();
16238    let limit = q.limit.unwrap_or(60).min(200);
16239    let offset = q.offset.unwrap_or(0).min(total);
16240    let has_more = offset + limit < total;
16241    let page: Vec<serde_json::Value> = rows[offset..(offset + limit).min(total)]
16242        .iter()
16243        .map(|m| {
16244            let id = m.id.get().copied().unwrap_or_default();
16245            let is_image = m.kind == "image";
16246            let thumb_url = is_image
16247                .then(|| {
16248                    crate::rendition::rendition_url_for(
16249                        id,
16250                        "fill-320x320|format-webp|quality-70",
16251                        Some(m.content_hash.as_str()),
16252                    )
16253                })
16254                .flatten();
16255            let preview_url = is_image
16256                .then(|| {
16257                    crate::rendition::rendition_url_for(
16258                        id,
16259                        "max-640x480|format-webp|quality-80",
16260                        Some(m.content_hash.as_str()),
16261                    )
16262                })
16263                .flatten();
16264            serde_json::json!({
16265                "id": id,
16266                "title": if m.title.is_empty() { m.filename.clone() } else { m.title.clone() },
16267                "filename": m.filename,
16268                "kind": m.kind,
16269                "mime": m.mime,
16270                "size": m.size,
16271                "width": m.width,
16272                "height": m.height,
16273                "collection_id": m.collection_id,
16274                "alt_text": m.alt_text,
16275                "uploaded_at": m.uploaded_at,
16276                "thumb_url": thumb_url,
16277                "preview_url": preview_url,
16278            })
16279        })
16280        .collect();
16281
16282    // Collections in DFS order so the dropdown nests visually
16283    // ("— Child" under its parent). A visited set guards against
16284    // accidental parent cycles.
16285    let cols: Vec<crate::media::MediaCollection> =
16286        crate::media::MediaCollection::objects().fetch(pool).await?;
16287    let mut children: std::collections::HashMap<Option<i64>, Vec<&crate::media::MediaCollection>> =
16288        std::collections::HashMap::new();
16289    for c in &cols {
16290        children.entry(c.parent_id).or_default().push(c);
16291    }
16292    for v in children.values_mut() {
16293        v.sort_by(|a, b| a.sort_order.cmp(&b.sort_order).then(a.name.cmp(&b.name)));
16294    }
16295    let mut ordered: Vec<serde_json::Value> = Vec::with_capacity(cols.len());
16296    let mut visited: std::collections::HashSet<i64> = std::collections::HashSet::new();
16297    let mut stack: Vec<(i64, usize)> = children
16298        .get(&None)
16299        .map(|roots| {
16300            roots
16301                .iter()
16302                .rev()
16303                .filter_map(|c| c.id.get().copied())
16304                .map(|id| (id, 0))
16305                .collect()
16306        })
16307        .unwrap_or_default();
16308    let by_id: std::collections::HashMap<i64, &crate::media::MediaCollection> = cols
16309        .iter()
16310        .filter_map(|c| c.id.get().copied().map(|id| (id, c)))
16311        .collect();
16312    while let Some((id, depth)) = stack.pop() {
16313        if !visited.insert(id) {
16314            continue;
16315        }
16316        if let Some(c) = by_id.get(&id) {
16317            ordered.push(serde_json::json!({
16318                "id": id,
16319                "name": c.name,
16320                "depth": depth,
16321                "count": collection_counts.get(&id).copied().unwrap_or(0),
16322            }));
16323            if let Some(kids) = children.get(&Some(id)) {
16324                for k in kids.iter().rev() {
16325                    if let Some(kid) = k.id.get().copied() {
16326                        stack.push((kid, depth + 1));
16327                    }
16328                }
16329            }
16330        }
16331    }
16332
16333    Ok(serde_json::json!({
16334        "items": page,
16335        "collections": ordered,
16336        "uncategorized_count": uncategorized_count,
16337        "total": total,
16338        "has_more": has_more,
16339    }))
16340}
16341
16342/// GET /cms-admin/__page-chooser?q=<needle> — JSON endpoint backing
16343/// the PageChooser widget. Returns the top-N matching
16344/// pages by title / slug / url_path (LIKE, lowercased), bounded at 50.
16345/// Empty `q` returns the most recently updated pages so the chooser
16346/// has something useful to show on first open.
16347pub async fn page_chooser_json(
16348    State(_state): State<super::AdminState>,
16349    tenant: Tenant,
16350    Query(q): Query<PageChooserQuery>,
16351) -> Result<Response, AdminError> {
16352    let needle =
16353        q.q.as_deref()
16354            .map(str::trim)
16355            .filter(|s| !s.is_empty())
16356            .map(str::to_lowercase);
16357
16358    let mut pages: Vec<Page> = Page::objects()
16359        .order_by(&[("updated_at", true)])
16360        .fetch(tenant.pool())
16361        .await
16362        .unwrap_or_default();
16363
16364    if let Some(n) = needle.as_ref() {
16365        pages.retain(|p| {
16366            p.title.to_lowercase().contains(n)
16367                || p.slug.to_lowercase().contains(n)
16368                || p.url_path.to_lowercase().contains(n)
16369        });
16370    }
16371
16372    let items: Vec<serde_json::Value> = pages
16373        .iter()
16374        .take(50)
16375        .map(|p| {
16376            serde_json::json!({
16377                "id": p.id.get().copied(),
16378                "title": p.title,
16379                "slug": p.slug,
16380                "url_path": p.url_path,
16381                "depth": p.depth,
16382                "parent_id": p.parent_id,
16383                "status": p.status,
16384            })
16385        })
16386        .collect();
16387
16388    let body = serde_json::json!({ "items": items });
16389    Ok((
16390        [(header::CONTENT_TYPE, "application/json")],
16391        serde_json::to_string(&body).unwrap_or_else(|_| "{}".to_owned()),
16392    )
16393        .into_response())
16394}
16395
16396/// Query string for `GET /cms-admin/__snippet-chooser`. Optional
16397/// `type_name` narrows to one snippet kind — the `data-chooser-filter`
16398/// attribute on the widget threads through.
16399#[derive(Debug, Deserialize)]
16400pub struct SnippetChooserQuery {
16401    #[serde(default)]
16402    pub q: Option<String>,
16403    #[serde(default)]
16404    pub type_name: Option<String>,
16405    /// Comma-separated snippet ids — resolve exactly these rows. Used by
16406    /// the widget-label hydration pass (a server-rendered value only has
16407    /// the raw id).
16408    #[serde(default)]
16409    pub ids: Option<String>,
16410}
16411
16412/// GET /cms-admin/__snippet-chooser?q=…&type_name=… — JSON endpoint
16413/// backing the SnippetChooser widget. Returns the
16414/// top-50 matching snippets by title / slug; optionally filtered
16415/// to a single `type_name`.
16416pub async fn snippet_chooser_json(
16417    State(_state): State<super::AdminState>,
16418    tenant: Tenant,
16419    Query(q): Query<SnippetChooserQuery>,
16420) -> Result<Response, AdminError> {
16421    let needle =
16422        q.q.as_deref()
16423            .map(str::trim)
16424            .filter(|s| !s.is_empty())
16425            .map(str::to_lowercase);
16426    let type_filter = q
16427        .type_name
16428        .as_deref()
16429        .map(str::trim)
16430        .filter(|s| !s.is_empty())
16431        .map(str::to_owned);
16432
16433    let mut snippets: Vec<crate::snippet::Snippet> = crate::snippet::Snippet::objects()
16434        .order_by(&[("updated_at", true)])
16435        .fetch(tenant.pool())
16436        .await
16437        .unwrap_or_default();
16438
16439    if let Some(ids) = q.ids.as_deref() {
16440        let id_set: std::collections::HashSet<i64> = ids
16441            .split(',')
16442            .filter_map(|t| t.trim().parse::<i64>().ok())
16443            .collect();
16444        snippets.retain(|s| s.id.get().copied().is_some_and(|id| id_set.contains(&id)));
16445    }
16446    if let Some(tn) = type_filter.as_ref() {
16447        snippets.retain(|s| &s.type_name == tn);
16448    }
16449    if let Some(n) = needle.as_ref() {
16450        snippets
16451            .retain(|s| s.title.to_lowercase().contains(n) || s.slug.to_lowercase().contains(n));
16452    }
16453
16454    let items: Vec<serde_json::Value> = snippets
16455        .iter()
16456        .take(50)
16457        .map(|s| {
16458            serde_json::json!({
16459                "id": s.id.get().copied(),
16460                "title": s.title,
16461                "slug": s.slug,
16462                "type_name": s.type_name,
16463            })
16464        })
16465        .collect();
16466
16467    let body = serde_json::json!({ "items": items });
16468    Ok((
16469        [(header::CONTENT_TYPE, "application/json")],
16470        serde_json::to_string(&body).unwrap_or_else(|_| "{}".to_owned()),
16471    )
16472        .into_response())
16473}
16474
16475/// Query string for `GET /cms-admin/__document-chooser`.
16476#[derive(Debug, Deserialize)]
16477pub struct DocumentChooserQuery {
16478    #[serde(default)]
16479    pub q: Option<String>,
16480}
16481
16482/// GET /cms-admin/__document-chooser?q=… — JSON endpoint backing
16483/// the DocumentChooser widget. Returns top-50 media
16484/// rows where `kind = "document"` (i.e. non-images), filtered by
16485/// title / filename.
16486pub async fn document_chooser_json(
16487    State(_state): State<super::AdminState>,
16488    tenant: Tenant,
16489    Query(q): Query<DocumentChooserQuery>,
16490) -> Result<Response, AdminError> {
16491    let needle =
16492        q.q.as_deref()
16493            .map(str::trim)
16494            .filter(|s| !s.is_empty())
16495            .map(str::to_lowercase);
16496
16497    let mut rows: Vec<Media> = Media::objects()
16498        .where_(Media::kind.eq("document".to_owned()))
16499        .order_by(&[("uploaded_at", true)])
16500        .fetch(tenant.pool())
16501        .await
16502        .unwrap_or_default();
16503
16504    if let Some(n) = needle.as_ref() {
16505        rows.retain(|m| {
16506            m.title.to_lowercase().contains(n) || m.filename.to_lowercase().contains(n)
16507        });
16508    }
16509
16510    let items: Vec<serde_json::Value> = rows
16511        .iter()
16512        .take(50)
16513        .map(|m| {
16514            serde_json::json!({
16515                "id": m.id.get().copied(),
16516                "title": m.title,
16517                "filename": m.filename,
16518                "kind": m.kind,
16519                "mime": m.mime,
16520            })
16521        })
16522        .collect();
16523
16524    let body = serde_json::json!({ "items": items });
16525    Ok((
16526        [(header::CONTENT_TYPE, "application/json")],
16527        serde_json::to_string(&body).unwrap_or_else(|_| "{}".to_owned()),
16528    )
16529        .into_response())
16530}
16531
16532/// GET /cms-admin/search?q=<needle>[&autocomplete=1] — unified search
16533/// across pages, snippets, and media. In-memory case-insensitive
16534/// substring match only; the ranked `crate::search` backend is not
16535/// wired into this handler.
16536pub async fn admin_search(
16537    State(state): State<super::AdminState>,
16538    tenant: Tenant,
16539    headers: HeaderMap,
16540    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
16541    Query(q): Query<AdminSearchQuery>,
16542) -> Result<Response, AdminError> {
16543    let needle =
16544        q.q.as_deref()
16545            .map(str::trim)
16546            .filter(|s| !s.is_empty())
16547            .map(str::to_lowercase);
16548    let autocomplete = q.autocomplete.as_deref() == Some("1");
16549
16550    // #143 — log every non-empty query. Best-effort; never blocks
16551    // the response. Skip autocomplete pings so the analytics surface
16552    // tracks user-intent queries, not keystroke-level ones.
16553    if !autocomplete {
16554        if let Some(raw) = q.q.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
16555            if let Err(e) = crate::search_promotion::log_query(tenant.pool(), raw).await {
16556                tracing::debug!(
16557                    target: "rustango_cms::search",
16558                    error = %e,
16559                    "search query log failed (best-effort)",
16560                );
16561            }
16562        }
16563    }
16564
16565    let mut pages_out: Vec<serde_json::Value> = Vec::new();
16566    let mut snippets_out: Vec<serde_json::Value> = Vec::new();
16567    let mut media_out: Vec<serde_json::Value> = Vec::new();
16568
16569    if let Some(needle) = needle.as_ref() {
16570        // Pages. #204 — recall extends from title/slug/url to also
16571        // include seo_title, seo_description, og_title, og_description
16572        // and (best-effort) the page-type extension's `load_extension`
16573        // JSON. Title hits float to the top — they're more relevant
16574        // than a stray match in a body paragraph.
16575        let all_pages: Vec<Page> = Page::objects()
16576            .order_by(&[("updated_at", true)])
16577            .fetch(tenant.pool())
16578            .await
16579            .unwrap_or_default();
16580        let page_types: Vec<PageType> = PageType::objects()
16581            .fetch(tenant.pool())
16582            .await
16583            .unwrap_or_default();
16584        let page_type_by_id: std::collections::HashMap<i64, String> = page_types
16585            .into_iter()
16586            .filter_map(|pt| pt.id.get().copied().map(|id| (id, pt.type_name)))
16587            .collect();
16588        let mut title_hits: Vec<serde_json::Value> = Vec::new();
16589        let mut body_hits: Vec<serde_json::Value> = Vec::new();
16590        for p in all_pages {
16591            if title_hits.len() + body_hits.len() >= 20 {
16592                break;
16593            }
16594            let title = p.title.to_lowercase();
16595            let slug = p.slug.to_lowercase();
16596            let url_path = p.url_path.to_lowercase();
16597            let primary_hit =
16598                title.contains(needle) || slug.contains(needle) || url_path.contains(needle);
16599
16600            // Wider body search — SEO/OG fields + extension JSON.
16601            let mut body_match = false;
16602            if !primary_hit {
16603                if p.seo_title.to_lowercase().contains(needle)
16604                    || p.seo_description.to_lowercase().contains(needle)
16605                    || p.og_title.to_lowercase().contains(needle)
16606                    || p.og_description.to_lowercase().contains(needle)
16607                {
16608                    body_match = true;
16609                }
16610                if !body_match {
16611                    if let Some(type_name) = page_type_by_id.get(&p.page_type_id) {
16612                        if let Some(handler) = crate::page_type::find_handler(type_name) {
16613                            let page_id = p.id.get().copied().unwrap_or_default();
16614                            if let Ok(ext) = handler.load_extension(tenant.pool(), page_id).await {
16615                                body_match = json_contains_needle(&ext, needle);
16616                            }
16617                        }
16618                    }
16619                }
16620            }
16621
16622            if primary_hit || body_match {
16623                let row = serde_json::json!({
16624                    "id": p.id.get().copied(),
16625                    "title": p.title,
16626                    "slug": p.slug,
16627                    "url_path": p.url_path,
16628                    "status": p.status,
16629                });
16630                if primary_hit {
16631                    title_hits.push(row);
16632                } else {
16633                    body_hits.push(row);
16634                }
16635            }
16636        }
16637        // Title-first ordering — primary hits float above body hits.
16638        pages_out.extend(title_hits);
16639        pages_out.extend(body_hits);
16640        if pages_out.len() > 20 {
16641            pages_out.truncate(20);
16642        }
16643
16644        // Snippets.
16645        let all_snippets: Vec<crate::snippet::Snippet> = crate::snippet::Snippet::objects()
16646            .order_by(&[("updated_at", true)])
16647            .fetch(tenant.pool())
16648            .await
16649            .unwrap_or_default();
16650        for s in all_snippets {
16651            if snippets_out.len() >= 20 {
16652                break;
16653            }
16654            let title = s.title.to_lowercase();
16655            let slug = s.slug.to_lowercase();
16656            if title.contains(needle) || slug.contains(needle) {
16657                snippets_out.push(serde_json::json!({
16658                    "id": s.id.get().copied(),
16659                    "title": s.title,
16660                    "slug": s.slug,
16661                    "type_name": s.type_name,
16662                }));
16663            }
16664        }
16665
16666        // Media.
16667        let all_media: Vec<crate::media::Media> = crate::media::Media::objects()
16668            .order_by(&[("created_at", true)])
16669            .fetch(tenant.pool())
16670            .await
16671            .unwrap_or_default();
16672        for m in all_media {
16673            if media_out.len() >= 20 {
16674                break;
16675            }
16676            let title = m.title.to_lowercase();
16677            let filename = m.filename.to_lowercase();
16678            let alt = m.alt_text.to_lowercase();
16679            if title.contains(needle) || filename.contains(needle) || alt.contains(needle) {
16680                media_out.push(serde_json::json!({
16681                    "id": m.id.get().copied(),
16682                    "title": m.title,
16683                    "filename": m.filename,
16684                    "alt_text": m.alt_text,
16685                    "kind": m.kind,
16686                }));
16687            }
16688        }
16689    }
16690
16691    // #107 — plugin-contributed search sources
16692    // (`register_admin_search_area!`). Each area returns its own
16693    // hit list keyed by area label. Empty when no query.
16694    let plugin_areas: Vec<serde_json::Value> = if let Some(query) = q.q.as_deref() {
16695        let trimmed = query.trim();
16696        if trimmed.is_empty() {
16697            Vec::new()
16698        } else {
16699            crate::hooks::run_admin_search_areas(
16700                crate::hooks::HookCtx::new(
16701                    tenant.pool(),
16702                    &tenant.org.slug,
16703                    session_user.as_ref().and_then(|u| u.id.get().copied()),
16704                ),
16705                trimmed,
16706            )
16707            .await
16708            .into_iter()
16709                .map(|(label, hits)| {
16710                    serde_json::json!({
16711                        "label": label,
16712                        "hits": hits,
16713                    })
16714                })
16715                .collect()
16716        }
16717    } else {
16718        Vec::new()
16719    };
16720
16721    if autocomplete {
16722        // Compact JSON shape for the topbar dropdown.
16723        let payload = serde_json::json!({
16724            "q": q.q,
16725            "pages": pages_out.iter().take(5).collect::<Vec<_>>(),
16726            "snippets": snippets_out.iter().take(5).collect::<Vec<_>>(),
16727            "media": media_out.iter().take(5).collect::<Vec<_>>(),
16728            "plugin_areas": plugin_areas,
16729        });
16730        return Ok((
16731            [(header::CONTENT_TYPE, "application/json")],
16732            serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_owned()),
16733        )
16734            .into_response());
16735    }
16736
16737    let mut ctx = Context::new();
16738    add_chrome(&mut ctx, &tenant, "search", session_user.as_ref()).await;
16739    add_admin_theme(&mut ctx, tenant.pool()).await;
16740    ctx.insert("query", &q.q.unwrap_or_default());
16741    ctx.insert("pages", &pages_out);
16742    ctx.insert("snippets", &snippets_out);
16743    ctx.insert("media", &media_out);
16744    let plugin_hit_count: usize = plugin_areas
16745        .iter()
16746        .filter_map(|a| a.get("hits").and_then(|h| h.as_array()).map(Vec::len))
16747        .sum();
16748    ctx.insert("plugin_search_areas", &plugin_areas);
16749    ctx.insert(
16750        "total_hits",
16751        &(pages_out.len() + snippets_out.len() + media_out.len() + plugin_hit_count),
16752    );
16753    render_with_csrf(&state, &headers, "rcms_admin/admin_search.html", &mut ctx)
16754}
16755
16756// =====================================================================
16757// Navigation menus (#22)
16758// =====================================================================
16759
16760/// GET /cms-admin/navigation — list every menu.
16761pub async fn navigation_list(
16762    State(state): State<super::AdminState>,
16763    tenant: Tenant,
16764    headers: HeaderMap,
16765    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
16766) -> Result<Response, AdminError> {
16767    // Not paged: one row per menu slot a theme renders (header, footer…).
16768    let menus: Vec<crate::navigation::Menu> = crate::navigation::Menu::objects()
16769        .order_by(&[("name", false)])
16770        .fetch(tenant.pool())
16771        .await?;
16772    // Per-menu item count so the list view shows "(N items)", in SQL.
16773    let counts =
16774        counts_by(tenant.pool(), crate::navigation::MenuItem::objects(), "menu_id").await?;
16775    let rows: Vec<serde_json::Value> = menus
16776        .iter()
16777        .map(|m| {
16778            let id = m.id.get().copied().unwrap_or_default();
16779            serde_json::json!({
16780                "id": id,
16781                "slug": m.slug,
16782                "name": m.name,
16783                "item_count": counts.get(&id).copied().unwrap_or(0),
16784                "created_at": m.created_at.get().copied(),
16785            })
16786        })
16787        .collect();
16788
16789    let mut ctx = Context::new();
16790    add_chrome(&mut ctx, &tenant, "navigation", session_user.as_ref()).await;
16791    add_admin_theme(&mut ctx, tenant.pool()).await;
16792    ctx.insert("menus", &rows);
16793    render_with_csrf(
16794        &state,
16795        &headers,
16796        "rcms_admin/navigation_list.html",
16797        &mut ctx,
16798    )
16799}
16800
16801/// Form payload for create / rename of a menu.
16802#[derive(Debug, Deserialize)]
16803pub struct MenuForm {
16804    pub slug: String,
16805    pub name: String,
16806}
16807
16808/// POST /cms-admin/navigation/new — create a new menu.
16809pub async fn navigation_create_submit(
16810    State(_state): State<super::AdminState>,
16811    tenant: Tenant,
16812    headers: HeaderMap,
16813    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
16814    Form(form): Form<MenuForm>,
16815) -> Result<Response, AdminError> {
16816    let slug = form.slug.trim().to_lowercase();
16817    let name = form.name.trim().to_owned();
16818    if slug.is_empty() || name.is_empty() {
16819        return redirect_named_with_message(
16820            "rcms-admin:navigation:list",
16821            MsgLevel::Warning,
16822            "Menu slug + name are both required.",
16823            &headers,
16824        );
16825    }
16826    let mut row = crate::navigation::Menu {
16827        id: rustango::sql::Auto::Unset,
16828        slug: slug.clone(),
16829        name,
16830        created_at: rustango::sql::Auto::Unset,
16831    };
16832    row.insert(tenant.pool()).await?;
16833    redirect_named_with_message_args(
16834        "rcms-admin:navigation:list",
16835        MsgLevel::Success,
16836        "Menu “{slug}” created.",
16837        &[("slug", slug.as_str())],
16838        &headers,
16839    )
16840}
16841
16842/// POST /cms-admin/navigation/{id}/delete — delete a menu (cascade
16843/// deletes its items via the schema FK).
16844pub async fn navigation_delete_submit(
16845    State(_state): State<super::AdminState>,
16846    tenant: Tenant,
16847    headers: HeaderMap,
16848    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
16849    Path(id): Path<i64>,
16850) -> Result<Response, AdminError> {
16851    let menu = crate::navigation::Menu::objects()
16852        .where_(crate::navigation::Menu::id.eq(id))
16853        .first(tenant.pool())
16854        .await?
16855        .ok_or(AdminError::NotFound(id))?;
16856    // Items, their translations, then the menu — all in one transaction.
16857    // This used to delete items in fetch order with pool-level writes, so
16858    // a nested menu tripped the self-FK partway through and left the menu
16859    // half-deleted, and a translated item made it fail every time.
16860    let items: Vec<crate::navigation::MenuItem> = crate::navigation::MenuItem::objects()
16861        .where_(crate::navigation::MenuItem::menu_id.eq(id))
16862        .fetch(tenant.pool())
16863        .await?;
16864    rustango::atomic!(tenant.pool(), |tx| {
16865        let mut guard = tx.lock().await?;
16866        let tx = &mut *guard;
16867        delete_menu_items_tx(tx, items).await?;
16868        menu.delete_tx(tx).await?;
16869        Ok::<_, rustango::sql::ExecError>(())
16870    })
16871    .await?;
16872    redirect_named_with_message(
16873        "rcms-admin:navigation:list",
16874        MsgLevel::Success,
16875        "Menu deleted.",
16876        &headers,
16877    )
16878}
16879
16880/// POST /cms-admin/navigation/{id}/clone — duplicate a menu + all
16881/// its items. The new menu inherits the same item tree
16882/// (parent_id pointers remapped to the new MenuItem ids); page links
16883/// stay pointed at the same pages (no page duplication). Slug gets a
16884/// "-copy" suffix, then "-copy-2" / "-copy-3" / … to dodge the
16885/// unique constraint on `Menu.slug`. Name gets " (copy)" appended.
16886pub async fn navigation_clone_submit(
16887    State(_state): State<super::AdminState>,
16888    tenant: Tenant,
16889    headers: HeaderMap,
16890    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
16891    Path(id): Path<i64>,
16892) -> Result<Response, AdminError> {
16893    let source = crate::navigation::Menu::objects()
16894        .where_(crate::navigation::Menu::id.eq(id))
16895        .first(tenant.pool())
16896        .await?
16897        .ok_or(AdminError::NotFound(id))?;
16898
16899    // Pick a unique slug. Menu.slug is unique across the tenant.
16900    let base = source.slug.trim_matches('-').to_owned();
16901    let desired = format!("{base}-copy");
16902    let existing_slugs: std::collections::HashSet<String> = crate::navigation::Menu::objects()
16903        .fetch(tenant.pool())
16904        .await?
16905        .into_iter()
16906        .map(|m| m.slug)
16907        .collect();
16908    let slug = if !existing_slugs.contains(&desired) {
16909        desired
16910    } else {
16911        let mut chosen = None;
16912        for n in 2..=100 {
16913            let candidate = format!("{desired}-{n}");
16914            if !existing_slugs.contains(&candidate) {
16915                chosen = Some(candidate);
16916                break;
16917            }
16918        }
16919        chosen.ok_or_else(|| {
16920            AdminError::Validation(
16921                "Could not allocate a unique slug for the cloned menu.".to_owned(),
16922            )
16923        })?
16924    };
16925
16926    let mut clone_menu = crate::navigation::Menu {
16927        id: rustango::sql::Auto::Unset,
16928        slug,
16929        name: format!("{} (copy)", source.name),
16930        created_at: rustango::sql::Auto::Unset,
16931    };
16932    // Clone items. `parent_id` needs remapping from source ids to the
16933    // freshly-inserted clone ids, so a parent must be inserted before its
16934    // children. `(parent_id.is_some(), sort_order, id)` is NOT that
16935    // order: it puts every non-root in one bucket sorted by `sort_order`,
16936    // which says nothing about depth. `seed_from_pages` numbers
16937    // `sort_order` per sibling bucket, so a grandchild routinely sorts
16938    // ahead of its parent — cloning a three-level menu then failed
16939    // partway and, with no transaction, left a junk `*-copy` behind.
16940    // Pre-order is the guarantee we actually need.
16941    let items = crate::navigation::order_pre_order(
16942        crate::navigation::MenuItem::objects()
16943            .where_(crate::navigation::MenuItem::menu_id.eq(id))
16944            .order_by(&[("sort_order", false), ("id", false)])
16945            .fetch(tenant.pool())
16946            .await?,
16947    );
16948    let count = items.len().to_string();
16949
16950    // Menu row and items together: a failure halfway through used to
16951    // leave the tenant with an empty, half-built `*-copy` menu.
16952    let new_menu_id = rustango::atomic!(tenant.pool(), |tx| {
16953        let mut guard = tx.lock().await?;
16954        let tx = &mut *guard;
16955        clone_menu.save_tx(tx).await?;
16956        let new_menu_id = clone_menu.id.get().copied().unwrap_or_default();
16957
16958        let mut id_map: std::collections::HashMap<i64, i64> = std::collections::HashMap::new();
16959        for item in &items {
16960            let old_id = item.id.get().copied().unwrap_or_default();
16961            // Pre-order guarantees the parent is mapped. An unreachable
16962            // item (orphan or cycle) is appended by `order_pre_order`
16963            // and re-parents to the root rather than aborting the clone
16964            // — losing the nesting of already-broken data beats refusing
16965            // to copy the menu at all.
16966            let new_parent = item.parent_id.and_then(|p| id_map.get(&p).copied());
16967            let mut clone_item = crate::navigation::MenuItem {
16968                id: rustango::sql::Auto::Unset,
16969                menu_id: new_menu_id,
16970                parent_id: new_parent,
16971                sort_order: item.sort_order,
16972                label: item.label.clone(),
16973                page_id: item.page_id,
16974                external_url: item.external_url.clone(),
16975                open_in_new_tab: item.open_in_new_tab,
16976            };
16977            clone_item.save_tx(tx).await?;
16978            id_map.insert(old_id, clone_item.id.get().copied().unwrap_or_default());
16979        }
16980        Ok::<_, rustango::sql::ExecError>(new_menu_id)
16981    })
16982    .await?;
16983
16984    redirect_named_with_params_and_message_args(
16985        "rcms-admin:navigation:edit",
16986        &[("id", new_menu_id.to_string())],
16987        MsgLevel::Success,
16988        "Cloned “{name}” with {count} items.",
16989        &[("name", source.name.as_str()), ("count", count.as_str())],
16990        &headers,
16991    )
16992}
16993
16994/// POST /cms-admin/navigation/{id}/seed-from-pages — Option B.
16995/// Replaces this menu's items with a tree
16996/// seeded from every published page that has `show_in_menus = true`.
16997/// The page tree's structure is preserved: a child MenuItem points
16998/// at its parent MenuItem when both pages are in the menu set; if a
16999/// page's parent is NOT in the menu set, the menu item lands at
17000/// the top level.
17001///
17002/// Idempotent — running it twice rebuilds the same tree (page ids
17003/// stay constant, so the second pass produces identical items).
17004/// Drops the existing menu items first; failure rolls back via
17005/// the per-row delete loop (matches the save-tree handler's
17006/// drop-and-rebuild approach).
17007pub async fn navigation_seed_from_pages_submit(
17008    State(_state): State<super::AdminState>,
17009    tenant: Tenant,
17010    headers: HeaderMap,
17011    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
17012    Path(id): Path<i64>,
17013) -> Result<Response, AdminError> {
17014    use rustango::core::Column as _;
17015    use rustango::sql::FetcherPool as _;
17016
17017    let menu = crate::navigation::Menu::objects()
17018        .where_(crate::navigation::Menu::id.eq(id))
17019        .first(tenant.pool())
17020        .await?
17021        .ok_or(AdminError::NotFound(id))?;
17022
17023    // Step 1: collect what is there now. Deleted inside the transaction
17024    // below, not here — this used to delete row by row on the pool, in
17025    // fetch order, so re-seeding a nested menu tripped the self-FK
17026    // partway through and left the menu wiped with nothing re-inserted.
17027    // A second click on an "idempotent" button was straight data loss.
17028    let existing: Vec<crate::navigation::MenuItem> = crate::navigation::MenuItem::objects()
17029        .where_(crate::navigation::MenuItem::menu_id.eq(id))
17030        .fetch(tenant.pool())
17031        .await?;
17032
17033    // Step 2: fetch every menu-eligible page in materialized-path
17034    // order (tree-pre-order: a parent always appears before its
17035    // children, so the parent's new MenuItem id is mapped by the
17036    // time the child's row is processed).
17037    let mut pages: Vec<crate::page::Page> = crate::page::Page::objects()
17038        .where_(crate::page::Page::show_in_menus.eq(true))
17039        .where_(crate::page::Page::status.eq("published".to_owned()))
17040        .order_by(&[("path", false), ("id", false)])
17041        .fetch(tenant.pool())
17042        .await?;
17043    // Error pages are routing furniture, not navigation — excluded here
17044    // as `auto_menu`, `sitemap` and the tree endpoint all exclude them.
17045    // A 404 handler marked "Show in menus" used to land in the navbar.
17046    let error_tid = crate::error_pages::error_page_type_id(tenant.pool()).await;
17047    pages.retain(|p| error_tid.is_none_or(|tid| p.page_type_id != tid));
17048
17049    // Step 3: insert one MenuItem per page, mapping page.parent_id →
17050    // the freshly-inserted MenuItem id of that parent (if the parent
17051    // is also in the menu set). sort_order mirrors the sibling-
17052    // relative order in the page tree.
17053    let mut page_to_item: std::collections::HashMap<i64, i64> = std::collections::HashMap::new();
17054    let mut sibling_counter: std::collections::HashMap<Option<i64>, i32> =
17055        std::collections::HashMap::new();
17056    // One item per eligible page, so the count is known before the write
17057    // — and reading a counter mutated inside the transaction closure
17058    // would always have returned 0 anyway.
17059    let inserted = pages.len();
17060    rustango::atomic!(tenant.pool(), |tx| {
17061        let mut guard = tx.lock().await?;
17062        let tx = &mut *guard;
17063    delete_menu_items_tx(tx, existing).await?;
17064    for page in &pages {
17065        let page_id = page.id.get().copied().unwrap_or_default();
17066        let parent_menu_item_id: Option<i64> = page
17067            .parent_id
17068            .and_then(|pid| page_to_item.get(&pid).copied());
17069        // Sort order: monotonically increasing within each
17070        // parent-bucket so the menu builder shows pages in the same
17071        // sibling order the page tree has.
17072        let bucket = parent_menu_item_id;
17073        let sort_order = *sibling_counter
17074            .entry(bucket)
17075            .and_modify(|n| *n += 1)
17076            .or_insert(0);
17077        let mut item = crate::navigation::MenuItem {
17078            id: rustango::sql::Auto::Unset,
17079            menu_id: id,
17080            parent_id: parent_menu_item_id,
17081            sort_order,
17082            label: page.title.clone(),
17083            page_id: Some(page_id),
17084            external_url: None,
17085            open_in_new_tab: false,
17086        };
17087        item.save_tx(tx).await?;
17088        let new_item_id = item.id.get().copied().unwrap_or_default();
17089        page_to_item.insert(page_id, new_item_id);
17090    }
17091    Ok::<_, rustango::sql::ExecError>(())
17092    })
17093    .await?;
17094
17095    redirect_named_with_params_and_message_plural(
17096        "rcms-admin:navigation:edit",
17097        &[("id", id.to_string())],
17098        MsgLevel::Success,
17099        "Seeded “{name}” with {count} item(s) from pages marked Show in menus.",
17100        inserted as i64,
17101        &[
17102            ("name", menu.name.as_str()),
17103            ("count", &inserted.to_string()),
17104        ],
17105        &headers,
17106    )
17107}
17108
17109/// Delete menu items and their translations inside a transaction.
17110///
17111/// `cms_menu_item_translation.item_id` and `cms_menu_item.parent_id` are
17112/// both FKs with no `ON DELETE`, so the order is forced: translations
17113/// first, then items deepest-first. Three handlers got this wrong in
17114/// three different ways before it lived in one place — the menu delete
17115/// ignored translations entirely, the re-seed deleted in fetch order, and
17116/// save-tree sorted on `parent_id.is_none()`, which ties every non-root.
17117async fn delete_menu_items_tx(
17118    tx: &mut rustango::sql::PoolTx<'_>,
17119    items: Vec<crate::navigation::MenuItem>,
17120) -> Result<(), rustango::sql::ExecError> {
17121    use crate::menu_item_translation::MenuItemTranslation;
17122    if items.is_empty() {
17123        return Ok(());
17124    }
17125    let ids: Vec<i64> = items.iter().filter_map(|it| it.id.get().copied()).collect();
17126    if !ids.is_empty() {
17127        let orphans: Vec<MenuItemTranslation> = MenuItemTranslation::objects()
17128            .where_(MenuItemTranslation::item_id.is_in(ids))
17129            .fetch_tx(tx)
17130            .await?;
17131        for row in orphans {
17132            row.delete_tx(tx).await?;
17133        }
17134    }
17135    for it in crate::navigation::order_deepest_first(items) {
17136        it.delete_tx(tx).await?;
17137    }
17138    Ok(())
17139}
17140
17141/// POST /cms-admin/navigation/{id}/save-tree — WP-style menu builder
17142/// save. Accepts a JSON array of items in display order; each
17143/// entry's `local_id` is its position in the array (0-indexed) and
17144/// `parent_local_id` references the array index of the parent (null
17145/// for top-level). The handler:
17146///
17147///   1. Validates that the tree is acyclic + every parent_local_id
17148///      < the child's local_id (insert-order invariant).
17149///   2. Updates rows the payload still carries an `id` for, **in
17150///      place**, and inserts the rest.
17151///   3. Deletes the rows the payload dropped, children before parents.
17152///
17153/// It used to delete every row and re-insert, which meant a menu item's
17154/// id changed on every save. That was survivable while nothing
17155/// referenced those ids — and stopped being survivable the moment
17156/// `cms_menu_item_translation` keyed translations on `item_id`, since a
17157/// reorder would silently discard every translated label. Ids are now
17158/// stable across a save.
17159///
17160/// Failure rolls back; no half-saved state.
17161#[derive(Debug, Deserialize)]
17162pub struct SaveTreeItem {
17163    /// Existing `cms_menu_item.id`. `None` for items added in this
17164    /// session, in which case the handler inserts a new row. An id that
17165    /// doesn't belong to this menu is treated the same way, so a stale
17166    /// or forged id can't reassign another menu's item.
17167    #[serde(default)]
17168    pub id: Option<i64>,
17169    /// 0-indexed position in the submitted array.
17170    pub local_id: i32,
17171    /// Array index of the parent, or `None` for top-level.
17172    #[serde(default)]
17173    pub parent_local_id: Option<i32>,
17174    pub label: String,
17175    #[serde(default)]
17176    pub page_id: Option<i64>,
17177    #[serde(default)]
17178    pub external_url: Option<String>,
17179    #[serde(default)]
17180    pub open_in_new_tab: bool,
17181}
17182
17183#[derive(Debug, Deserialize)]
17184pub struct SaveTreePayload {
17185    pub items: Vec<SaveTreeItem>,
17186}
17187
17188pub async fn navigation_save_tree_submit(
17189    State(_state): State<super::AdminState>,
17190    tenant: Tenant,
17191    Path(id): Path<i64>,
17192    axum::Json(payload): axum::Json<SaveTreePayload>,
17193) -> Result<Response, AdminError> {
17194    // Validate tree shape: every parent_local_id must reference an
17195    // earlier index (so we can insert in order without two passes).
17196    for (i, item) in payload.items.iter().enumerate() {
17197        if item.local_id as usize != i {
17198            return Err(AdminError::Validation(format!(
17199                "items[{i}].local_id must equal its array index"
17200            )));
17201        }
17202        if let Some(p) = item.parent_local_id {
17203            if (p as usize) >= i {
17204                return Err(AdminError::Validation(format!(
17205                    "items[{i}].parent_local_id {p} must reference an earlier item"
17206                )));
17207            }
17208        }
17209    }
17210
17211    // Exactly one link target, and lengths the columns can hold. The
17212    // form handler enforced this and `save-tree` did not, so the builder
17213    // could store an item with both (`page_id` silently wins, and
17214    // unpublishing that page drops an item carrying a perfectly good
17215    // external fallback) or with neither (rendered as a link to `/`,
17216    // indistinguishable from a grouping header). An over-long label
17217    // reached the driver as a raw error and surfaced as a 500.
17218    for (i, item) in payload.items.iter().enumerate() {
17219        let external = item
17220            .external_url
17221            .as_deref()
17222            .map(str::trim)
17223            .filter(|s| !s.is_empty());
17224        match (item.page_id, external) {
17225            (Some(_), Some(_)) => {
17226                return Err(AdminError::Validation(format!(
17227                    "items[{i}] sets both a page and an external URL — pick one"
17228                )))
17229            }
17230            (None, None) => {
17231                return Err(AdminError::Validation(format!(
17232                    "items[{i}] has no link target — set a page or an external URL"
17233                )))
17234            }
17235            _ => {}
17236        }
17237        if item.label.chars().count() > 200 {
17238            return Err(AdminError::Validation(format!(
17239                "items[{i}].label is too long (max 200 characters)"
17240            )));
17241        }
17242        if external.is_some_and(|u| u.chars().count() > 500) {
17243            return Err(AdminError::Validation(format!(
17244                "items[{i}].external_url is too long (max 500 characters)"
17245            )));
17246        }
17247    }
17248
17249    // An id may appear at most once. The upsert below claims each kept row
17250    // out of `existing_by_id`, so a repeat would find the row already
17251    // taken — previously an `.expect` that panicked mid-transaction.
17252    let mut seen: std::collections::HashSet<i64> = std::collections::HashSet::new();
17253    for (i, item) in payload.items.iter().enumerate() {
17254        if let Some(iid) = item.id {
17255            if !seen.insert(iid) {
17256                return Err(AdminError::Validation(format!(
17257                    "items[{i}].id {iid} appears more than once"
17258                )));
17259            }
17260        }
17261    }
17262
17263    // Every sibling handler verifies the menu first; this one went
17264    // straight to inserting rows with `menu_id: id`, so a stale or
17265    // mistyped id surfaced as a raw FK violation (a 500) instead of a
17266    // 404.
17267    if crate::navigation::Menu::objects()
17268        .where_(crate::navigation::Menu::id.eq(id))
17269        .first(tenant.pool())
17270        .await?
17271        .is_none()
17272    {
17273        return Err(AdminError::NotFound(id));
17274    }
17275
17276    let existing: Vec<crate::navigation::MenuItem> = crate::navigation::MenuItem::objects()
17277        .where_(crate::navigation::MenuItem::menu_id.eq(id))
17278        .fetch(tenant.pool())
17279        .await?;
17280    let mut existing_by_id: std::collections::HashMap<i64, crate::navigation::MenuItem> = existing
17281        .into_iter()
17282        .filter_map(|it| it.id.get().copied().map(|iid| (iid, it)))
17283        .collect();
17284
17285    // Claim each payload entry's existing row up front, so the write loop
17286    // below has no fallible lookup left to make. `Some(row)` updates in
17287    // place (keeping the id, and with it the item's translations);
17288    // `None` inserts. An id from another menu, or one that isn't in this
17289    // menu at all, resolves to `None` rather than stealing that row.
17290    let plan: Vec<Option<crate::navigation::MenuItem>> = payload
17291        .items
17292        .iter()
17293        .map(|it| it.id.and_then(|iid| existing_by_id.remove(&iid)))
17294        .collect();
17295
17296    let items_saved = payload.items.len();
17297    rustango::atomic!(tenant.pool(), |tx| {
17298        let mut guard = tx.lock().await?;
17299        let tx = &mut *guard;
17300        // Upsert in array order, resolving each item's parent from the
17301        // slot its `local_id` indexes. The validation above pins
17302        // `local_id` to the array index and requires
17303        // `parent_local_id < local_id`, so a parent's slot is always
17304        // filled before a child reads it — no fallible lookup here, and
17305        // no way to express one.
17306        let mut resolved: Vec<i64> = Vec::with_capacity(payload.items.len());
17307        for ((i, item), claimed) in payload.items.iter().enumerate().zip(plan) {
17308            let parent_id = item.parent_local_id.map(|p| resolved[p as usize]);
17309            let external_url = item
17310                .external_url
17311                .as_ref()
17312                .filter(|s| !s.trim().is_empty())
17313                .cloned();
17314            let sort_order = (i as i32) * 10;
17315
17316            let new_id = match claimed {
17317                Some(mut row) => {
17318                    // Update in place — this is what keeps the id, and
17319                    // therefore the item's translations, alive.
17320                    let iid = row.id.get().copied().unwrap_or_default();
17321                    row.parent_id = parent_id;
17322                    row.sort_order = sort_order;
17323                    row.label = item.label.clone();
17324                    row.page_id = item.page_id;
17325                    row.external_url = external_url;
17326                    row.open_in_new_tab = item.open_in_new_tab;
17327                    row.save_tx(tx).await?;
17328                    iid
17329                }
17330                None => {
17331                    let mut row = crate::navigation::MenuItem {
17332                        id: rustango::sql::Auto::Unset,
17333                        menu_id: id,
17334                        parent_id,
17335                        sort_order,
17336                        label: item.label.clone(),
17337                        page_id: item.page_id,
17338                        external_url,
17339                        open_in_new_tab: item.open_in_new_tab,
17340                    };
17341                    row.save_tx(tx).await?;
17342                    row.id.get().copied().unwrap_or_default()
17343                }
17344            };
17345            resolved.push(new_id);
17346        }
17347
17348        // Whatever the payload dropped. Every surviving row has already
17349        // been repointed above, so nothing still references these — but
17350        // they may reference each other, and `MenuItem.parent_id` is an
17351        // FK to `cms_menu_item.id` with no `ON DELETE`, so a parent can
17352        // only go once its children are gone.
17353        delete_menu_items_tx(tx, existing_by_id.into_values().collect()).await?;
17354        Ok::<_, rustango::sql::ExecError>(())
17355    })
17356    .await?;
17357
17358    Ok(axum::Json(serde_json::json!({
17359        "ok": true,
17360        "items_saved": items_saved,
17361    }))
17362    .into_response())
17363}
17364
17365/// GET /cms-admin/navigation/{id}/edit — item editor for one menu.
17366pub async fn navigation_edit_form(
17367    State(state): State<super::AdminState>,
17368    tenant: Tenant,
17369    headers: HeaderMap,
17370    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
17371    Path(id): Path<i64>,
17372    Query(q): Query<EditQuery>,
17373) -> Result<Response, AdminError> {
17374    let menu = crate::navigation::Menu::objects()
17375        .where_(crate::navigation::Menu::id.eq(id))
17376        .first(tenant.pool())
17377        .await?
17378        .ok_or(AdminError::NotFound(id))?;
17379    // Pre-order, not `ORDER BY parent_id`. The builder derives each
17380    // item's parent from DOM adjacency on save, so the DOM has to start
17381    // in pre-order or merely opening a menu and pressing Save rewrites
17382    // its nesting — see `navigation::order_pre_order`.
17383    let items = crate::navigation::order_pre_order(
17384        crate::navigation::MenuItem::objects()
17385            .where_(crate::navigation::MenuItem::menu_id.eq(id))
17386            .order_by(&[("sort_order", false), ("id", false)])
17387            .fetch(tenant.pool())
17388            .await?,
17389    );
17390    // Pages flagged `show_in_menus = true` are the suggested-picker
17391    // entries; fall back to "every page" if no editor has opted any
17392    // pages in yet.
17393    let suggested: Vec<Page> = Page::objects()
17394        .where_(Page::show_in_menus.eq(true))
17395        .order_by(&[("title", false)])
17396        .fetch(tenant.pool())
17397        .await?;
17398    // WP-style builder (#44): the picker always shows every page so
17399    // editors can drop any of them in. The legacy curated flag stays
17400    // available for downstream theme rendering but no longer hides
17401    // pages from the admin picker.
17402    let all_pages: Vec<Page> = Page::objects()
17403        .order_by(&[("title", false)])
17404        .fetch(tenant.pool())
17405        .await?;
17406
17407    // Resolve item rows into a render-friendly shape (label, url,
17408    // page title for the dropdown when set).
17409    let by_page_id: std::collections::HashMap<i64, &Page> = all_pages
17410        .iter()
17411        .filter_map(|p| p.id.get().copied().map(|id| (id, p)))
17412        .collect();
17413    // ?locale=<non-default> switches the editor into translation mode:
17414    // the tree builder still edits canonical structure, and a second
17415    // panel edits this locale's label overrides. Same shape as the page
17416    // and snippet editors, so the locale switcher behaves identically
17417    // wherever an editor meets one.
17418    let locales: Vec<Locale> = Locale::objects()
17419        .where_(Locale::active.eq(true))
17420        .order_by(&[("is_default", true), ("code", false)])
17421        .fetch(tenant.pool())
17422        .await?;
17423    let editing_locale: Option<Locale> = match q.locale.as_deref().filter(|c| !c.is_empty()) {
17424        Some(code) => locales.iter().find(|l| l.code == code).cloned(),
17425        None => None,
17426    };
17427    let translation_mode = editing_locale.as_ref().is_some_and(|l| !l.is_default);
17428    let item_translations = match editing_locale.as_ref().filter(|l| !l.is_default) {
17429        Some(loc) => {
17430            let lid = loc.id.get().copied().unwrap_or_default();
17431            let ids: Vec<i64> = items.iter().filter_map(|it| it.id.get().copied()).collect();
17432            crate::menu_item_translation::fetch_for_items(tenant.pool(), &ids, lid).await?
17433        }
17434        None => std::collections::HashMap::new(),
17435    };
17436
17437    let item_rows: Vec<serde_json::Value> = items
17438        .iter()
17439        .map(|it| {
17440            let resolved_label = if it.label.trim().is_empty() {
17441                it.page_id
17442                    .and_then(|pid| by_page_id.get(&pid).map(|p| p.title.clone()))
17443                    .unwrap_or_default()
17444            } else {
17445                it.label.clone()
17446            };
17447            let resolved_url = match (it.page_id, it.external_url.clone()) {
17448                (Some(pid), _) => by_page_id
17449                    .get(&pid)
17450                    .map(|p| p.url_path.clone())
17451                    .unwrap_or_else(|| "—".to_owned()),
17452                (None, Some(url)) => url,
17453                _ => "—".to_owned(),
17454            };
17455            let tr = it
17456                .id
17457                .get()
17458                .and_then(|iid| item_translations.get(iid));
17459            serde_json::json!({
17460                "id": it.id.get().copied(),
17461                "label": it.label,
17462                "resolved_label": resolved_label,
17463                "page_id": it.page_id,
17464                "external_url": it.external_url,
17465                "parent_id": it.parent_id,
17466                "sort_order": it.sort_order,
17467                "open_in_new_tab": it.open_in_new_tab,
17468                "resolved_url": resolved_url,
17469                "tr_label": tr.and_then(|m| m.get("label")).cloned().unwrap_or_default(),
17470                "tr_external_url": tr
17471                    .and_then(|m| m.get("external_url"))
17472                    .cloned()
17473                    .unwrap_or_default(),
17474            })
17475        })
17476        .collect();
17477
17478    // Error pages are served for a status code; a menu never links one.
17479    let error_tid = crate::error_pages::error_page_type_id(tenant.pool()).await;
17480    let linkable = |p: &&Page| error_tid.map_or(true, |tid| p.page_type_id != tid);
17481    let picker_pages: Vec<serde_json::Value> = all_pages
17482        .iter()
17483        .filter(linkable)
17484        .map(|p| {
17485            serde_json::json!({
17486                "id": p.id.get().copied(),
17487                "title": p.title,
17488                "url_path": p.url_path,
17489            })
17490        })
17491        .collect();
17492
17493    // #49c — recent-pages tab. 20 most-recently-updated pages so
17494    // editors who just published something can drop it into the menu
17495    // without scrolling the full picker. Fetched via a separate
17496    // updated_at-desc query so the existing alphabetical picker
17497    // stays unchanged.
17498    let recent_pages_raw: Vec<Page> = Page::objects()
17499        .order_by(&[("updated_at", true)])
17500        .fetch(tenant.pool())
17501        .await?;
17502    let picker_recent: Vec<serde_json::Value> = recent_pages_raw
17503        .iter()
17504        .filter(linkable)
17505        .take(20)
17506        .map(|p| {
17507            serde_json::json!({
17508                "id": p.id.get().copied(),
17509                "title": p.title,
17510                "url_path": p.url_path,
17511                "updated_at": p.updated_at,
17512            })
17513        })
17514        .collect();
17515
17516    // #49d — Library tab. Each registered `LibraryTypeHandler` opts
17517    // in via `menu_picker_entries(pool)`; we flatten the result
17518    // across every handler and tag each entry with the contributing
17519    // type's verbose_name so editors can tell where an entry came
17520    // from. Failure in any handler short-circuits the response so
17521    // bugs surface loudly instead of silently hiding entries.
17522    let mut picker_library: Vec<serde_json::Value> = Vec::new();
17523    for handler in crate::library::registered_handlers() {
17524        let entries = handler
17525            .menu_picker_entries(tenant.pool())
17526            .await
17527            .map_err(|e| {
17528                AdminError::Validation(format!(
17529                    "library `{}::menu_picker_entries` failed: {e}",
17530                    handler.type_name()
17531                ))
17532            })?;
17533        for entry in entries {
17534            picker_library.push(serde_json::json!({
17535                "label": entry.label,
17536                "url": entry.url,
17537                "kind_hint": entry.kind_hint,
17538                "library_type": handler.verbose_name(),
17539            }));
17540        }
17541    }
17542
17543    let mut ctx = Context::new();
17544    add_chrome(&mut ctx, &tenant, "navigation", session_user.as_ref()).await;
17545    add_admin_theme(&mut ctx, tenant.pool()).await;
17546    ctx.insert("menu_id", &menu.id.get().copied());
17547    ctx.insert("menu_slug", &menu.slug);
17548    ctx.insert("menu_name", &menu.name);
17549    ctx.insert("items", &item_rows);
17550    ctx.insert("picker_pages", &picker_pages);
17551    ctx.insert("picker_recent", &picker_recent);
17552    ctx.insert("picker_library", &picker_library);
17553    ctx.insert("has_library_picker", &!picker_library.is_empty());
17554    ctx.insert("has_curated_picker", &!suggested.is_empty());
17555    ctx.insert("locales", &locales);
17556    ctx.insert("editing_locale", &editing_locale);
17557    ctx.insert("translation_mode", &translation_mode);
17558    render_with_csrf(
17559        &state,
17560        &headers,
17561        "rcms_admin/navigation_edit.html",
17562        &mut ctx,
17563    )
17564}
17565
17566/// POST /cms-admin/navigation/{id}/translate?locale=<code> — save this
17567/// locale's label overrides for a menu's items.
17568///
17569/// Separate from the tree save on purpose. The builder posts JSON and
17570/// owns *structure*; this posts a form and owns *text*, so an editor
17571/// translating labels cannot accidentally reshape the menu, and a
17572/// reorder cannot drop a translation.
17573///
17574/// Field names are `tr__<item id>__<field>`. An empty value deletes the
17575/// override rather than storing a blank, which is what makes the
17576/// canonical label show through again.
17577pub async fn navigation_translate_submit(
17578    State(_state): State<super::AdminState>,
17579    tenant: Tenant,
17580    Path(id): Path<i64>,
17581    Query(q): Query<EditQuery>,
17582    Form(form): Form<std::collections::HashMap<String, String>>,
17583) -> Result<Response, AdminError> {
17584    use crate::menu_item_translation::MenuItemTranslation;
17585
17586    let code = q
17587        .locale
17588        .as_deref()
17589        .filter(|c| !c.is_empty())
17590        .ok_or_else(|| AdminError::Validation("translate requires ?locale=".to_owned()))?;
17591    let locale = Locale::objects()
17592        .where_(Locale::code.eq(code.to_owned()))
17593        .where_(Locale::active.eq(true))
17594        .first(tenant.pool())
17595        .await?
17596        .ok_or_else(|| AdminError::Validation(format!("unknown locale `{code}`")))?;
17597    if locale.is_default {
17598        return Ok((
17599            axum::http::StatusCode::BAD_REQUEST,
17600            "cannot translate INTO the default locale; canonical labels live on cms_menu_item",
17601        )
17602            .into_response());
17603    }
17604    let locale_id = locale
17605        .id
17606        .get()
17607        .copied()
17608        .ok_or_else(|| AdminError::Validation("locale row missing id".to_owned()))?;
17609
17610    // Only this menu's items are editable here — the field names carry
17611    // item ids, and without this check a crafted post could write
17612    // translations for another menu's items.
17613    let own_items: std::collections::HashSet<i64> = crate::navigation::MenuItem::objects()
17614        .where_(crate::navigation::MenuItem::menu_id.eq(id))
17615        .fetch(tenant.pool())
17616        .await?
17617        .iter()
17618        .filter_map(|it| it.id.get().copied())
17619        .collect();
17620
17621    let mut updates: Vec<(i64, String, String)> = Vec::new();
17622    for (k, v) in &form {
17623        let Some(rest) = k.strip_prefix("tr__") else {
17624            continue;
17625        };
17626        let Some((raw_id, raw_field)) = rest.split_once("__") else {
17627            continue;
17628        };
17629        let Ok(item_id) = raw_id.parse::<i64>() else {
17630            continue;
17631        };
17632        if !own_items.contains(&item_id) {
17633            continue;
17634        }
17635        // A malformed field is skipped rather than 400-ing the batch, so
17636        // one bad input doesn't discard an editor's other edits.
17637        if let Ok(field) = crate::menu_item_translation::validate_field_path(raw_field) {
17638            updates.push((item_id, field, v.trim().to_owned()));
17639        }
17640    }
17641
17642    rustango::atomic!(tenant.pool(), |tx| {
17643        let mut guard = tx.lock().await?;
17644        let tx = &mut *guard;
17645        for (item_id, field, value) in updates {
17646            let existing: Vec<MenuItemTranslation> = MenuItemTranslation::objects()
17647                .where_(MenuItemTranslation::item_id.eq(item_id))
17648                .where_(MenuItemTranslation::locale_id.eq(locale_id))
17649                .where_(MenuItemTranslation::field_path.eq(field.clone()))
17650                .fetch_tx(tx)
17651                .await?;
17652            if value.is_empty() {
17653                for row in existing {
17654                    row.delete_tx(tx).await?;
17655                }
17656            } else if let Some(mut row) = existing.into_iter().next() {
17657                row.value = value;
17658                row.save_tx(tx).await?;
17659            } else {
17660                let mut row = MenuItemTranslation {
17661                    id: rustango::sql::Auto::Unset,
17662                    item_id,
17663                    locale_id,
17664                    field_path: field,
17665                    value,
17666                    updated_at: rustango::sql::Auto::Unset,
17667                };
17668                row.save_tx(tx).await?;
17669            }
17670        }
17671        Ok::<_, rustango::sql::ExecError>(())
17672    })
17673    .await?;
17674
17675    Ok(Redirect::to(&format!(
17676        "/cms-admin/navigation/{id}/edit?locale={code}"
17677    ))
17678    .into_response())
17679}
17680
17681/// Form payload for adding / updating a menu item. Empty strings on
17682/// `page_id` and `external_url` map to None; the validator enforces
17683/// "exactly one of the two".
17684#[derive(Debug, Deserialize)]
17685pub struct MenuItemForm {
17686    pub label: String,
17687    #[serde(default, deserialize_with = "super::deserialize_optional_i64")]
17688    pub page_id: Option<i64>,
17689    #[serde(default)]
17690    pub external_url: Option<String>,
17691    #[serde(default, deserialize_with = "super::deserialize_optional_i64")]
17692    pub parent_id: Option<i64>,
17693    #[serde(default)]
17694    pub sort_order: Option<i32>,
17695    #[serde(default)]
17696    pub open_in_new_tab: Option<String>,
17697}
17698
17699/// Reject a `parent_id` that does not belong to `menu_id`.
17700///
17701/// The form took the value straight from the request, so an item could be
17702/// parented into another menu — leaving it invisible in *both* (each
17703/// resolver buckets by its own `menu_id`, so the child is unreachable in
17704/// one and filtered out of the other) and making the other menu
17705/// permanently undeletable, because its item is now referenced by a row
17706/// the delete never sees.
17707async fn validate_menu_parent(
17708    tenant: &Tenant,
17709    menu_id: i64,
17710    parent_id: Option<i64>,
17711) -> Result<(), AdminError> {
17712    let Some(pid) = parent_id else {
17713        return Ok(());
17714    };
17715    let parent = crate::navigation::MenuItem::objects()
17716        .where_(crate::navigation::MenuItem::id.eq(pid))
17717        .first(tenant.pool())
17718        .await?;
17719    match parent {
17720        Some(p) if p.menu_id == menu_id => Ok(()),
17721        Some(_) => Err(AdminError::Validation(
17722            "That parent item belongs to a different menu.".to_owned(),
17723        )),
17724        None => Err(AdminError::Validation(
17725            "That parent item no longer exists.".to_owned(),
17726        )),
17727    }
17728}
17729
17730impl MenuItemForm {
17731    fn parsed_external_url(&self) -> Option<String> {
17732        self.external_url
17733            .as_deref()
17734            .map(str::trim)
17735            .filter(|s| !s.is_empty())
17736            .map(str::to_owned)
17737    }
17738}
17739
17740/// POST /cms-admin/navigation/{id}/items — create a new menu item.
17741pub async fn navigation_item_create(
17742    State(_state): State<super::AdminState>,
17743    tenant: Tenant,
17744    headers: HeaderMap,
17745    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
17746    Path(menu_id): Path<i64>,
17747    Form(form): Form<MenuItemForm>,
17748) -> Result<Response, AdminError> {
17749    let external = form.parsed_external_url();
17750    // "Exactly one of page_id / external_url" — fail soft to the
17751    // edit page with a warning message.
17752    if form.page_id.is_some() == external.is_some() {
17753        return redirect_named_with_params_and_message(
17754            "rcms-admin:navigation:edit",
17755            &[("id", menu_id.to_string())],
17756            MsgLevel::Warning,
17757            "Pick exactly one of: a page link, or a custom URL.",
17758            &headers,
17759        );
17760    }
17761    // The parent must live in this menu — see `validate_menu_parent`.
17762    validate_menu_parent(&tenant, menu_id, form.parent_id).await?;
17763    let mut row = crate::navigation::MenuItem {
17764        id: rustango::sql::Auto::Unset,
17765        menu_id,
17766        parent_id: form.parent_id,
17767        sort_order: form.sort_order.unwrap_or(100),
17768        label: form.label.trim().to_owned(),
17769        page_id: form.page_id,
17770        external_url: external,
17771        open_in_new_tab: form.open_in_new_tab.is_some(),
17772    };
17773    row.insert(tenant.pool()).await?;
17774    redirect_named_with_params_and_message(
17775        "rcms-admin:navigation:edit",
17776        &[("id", menu_id.to_string())],
17777        MsgLevel::Success,
17778        "Item added.",
17779        &headers,
17780    )
17781}
17782
17783/// POST /cms-admin/navigation/{menu_id}/items/{id}/delete.
17784pub async fn navigation_item_delete(
17785    State(_state): State<super::AdminState>,
17786    tenant: Tenant,
17787    headers: HeaderMap,
17788    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
17789    Path((menu_id, id)): Path<(i64, i64)>,
17790) -> Result<Response, AdminError> {
17791    let row = crate::navigation::MenuItem::objects()
17792        .where_(crate::navigation::MenuItem::id.eq(id))
17793        .where_(crate::navigation::MenuItem::menu_id.eq(menu_id))
17794        .first(tenant.pool())
17795        .await?
17796        .ok_or(AdminError::NotFound(id))?;
17797    // Re-parent any children to the deleted item's parent so the
17798    // tree doesn't orphan a whole subtree.
17799    let children: Vec<crate::navigation::MenuItem> = crate::navigation::MenuItem::objects()
17800        .where_(crate::navigation::MenuItem::parent_id.eq(Some(id)))
17801        .fetch(tenant.pool())
17802        .await?;
17803    for mut c in children {
17804        c.parent_id = row.parent_id;
17805        c.save(tenant.pool()).await?;
17806    }
17807    row.delete(tenant.pool()).await?;
17808    redirect_named_with_params_and_message(
17809        "rcms-admin:navigation:edit",
17810        &[("id", menu_id.to_string())],
17811        MsgLevel::Success,
17812        "Item deleted.",
17813        &headers,
17814    )
17815}
17816
17817// =====================================================================
17818// Page types — usage dashboard (#16)
17819// =====================================================================
17820
17821/// The newest `published_at` among the pages of `type_id`, counting a
17822/// never-published page by its `created_at`.
17823async fn latest_page_activity(
17824    pool: &rustango::sql::Pool,
17825    type_id: i64,
17826) -> Result<Option<chrono::DateTime<chrono::Utc>>, rustango::sql::ExecError> {
17827    let of_type = || Page::objects().where_(Page::page_type_id.eq(type_id));
17828    let published: Option<Page> = of_type()
17829        .where_(Page::published_at.is_not_null())
17830        .order_by(&[("published_at", true)])
17831        .first(pool)
17832        .await?;
17833    let created: Option<Page> = of_type()
17834        .where_(Page::published_at.is_null())
17835        .order_by(&[("created_at", true)])
17836        .first(pool)
17837        .await?;
17838    Ok(published
17839        .and_then(|p| p.published_at)
17840        .max(created.and_then(|p| p.created_at.get().copied())))
17841}
17842
17843/// GET /cms-admin/page-types — registry of every page type the host
17844/// has compiled in, with how many pages of each currently exist + the
17845/// most-recent one. Useful before deprecating a type or refactoring
17846/// its declared fields.
17847pub async fn page_types_dashboard(
17848    State(state): State<super::AdminState>,
17849    tenant: Tenant,
17850    headers: HeaderMap,
17851    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
17852) -> Result<Response, AdminError> {
17853    // Not paged: one row per page type compiled in or created in the
17854    // admin. The pages themselves are counted in SQL, not loaded.
17855    let page_types: Vec<PageType> = PageType::objects().fetch(tenant.pool()).await?;
17856    let counts = counts_by(tenant.pool(), Page::objects(), "page_type_id").await?;
17857    let mut latest: std::collections::HashMap<i64, chrono::DateTime<chrono::Utc>> =
17858        std::collections::HashMap::new();
17859    for &type_id in counts.keys() {
17860        if let Some(when) = latest_page_activity(tenant.pool(), type_id).await? {
17861            latest.insert(type_id, when);
17862        }
17863    }
17864
17865    let type_id_by_name: std::collections::HashMap<&str, i64> = page_types
17866        .iter()
17867        .filter_map(|t| t.id.get().copied().map(|id| (t.type_name.as_str(), id)))
17868        .collect();
17869
17870    // Cross-reference the in-process handler registry with the DB
17871    // `cms_page_type` rows so unregistered + un-seeded types both
17872    // surface (handler-only = "compiled in but never used"; row-only
17873    // = "DB drift from an old build").
17874    let mut handler_names = std::collections::BTreeSet::new();
17875    let mut rows: Vec<serde_json::Value> = Vec::new();
17876    for handler in crate::page_type::registered_handlers() {
17877        let name = handler.type_name().to_owned();
17878        handler_names.insert(name.clone());
17879        let row_id = type_id_by_name.get(name.as_str()).copied();
17880        let count = row_id.and_then(|id| counts.get(&id).copied()).unwrap_or(0);
17881        let last = row_id.and_then(|id| latest.get(&id).copied());
17882        rows.push(serde_json::json!({
17883            "type_name": name,
17884            "verbose_name": handler.verbose_name(),
17885            "app_label": handler.app_label(),
17886            "icon": handler.icon(),
17887            "description": handler.description(),
17888            "default_template": handler.default_template(),
17889            "feed_kind": handler.feed_kind(),
17890            "allowed_parents": handler.allowed_parent_types(),
17891            "allowed_children": handler.allowed_child_types(),
17892            "is_creatable": handler.is_creatable(),
17893            "count": count,
17894            "latest": last,
17895            "registered": true,
17896            "row_id": row_id,
17897        }));
17898    }
17899
17900    // DB-only types — appear in `cms_page_type` but no handler is
17901    // compiled in. Two flavours: UI-created types (#566,
17902    // `app_label = "cms_ui"`, first-class — creatable + deletable) and
17903    // build drift (a stale row from an old binary — surfaced so editors
17904    // notice). Only UI types get a delete affordance, and only while no
17905    // pages use them; code types are never deletable from the UI.
17906    for t in &page_types {
17907        if !handler_names.contains(&t.type_name) {
17908            let id = t.id.get().copied().unwrap_or_default();
17909            let count = counts.get(&id).copied().unwrap_or(0);
17910            let ui_type = t.app_label == "cms_ui";
17911            rows.push(serde_json::json!({
17912                "type_name": t.type_name,
17913                "verbose_name": t.verbose_name,
17914                "app_label": t.app_label,
17915                "icon": if ui_type { serde_json::Value::String("dashboard_customize".to_owned()) } else { serde_json::Value::Null },
17916                "description": serde_json::Value::Null,
17917                "default_template": t.default_template,
17918                "feed_kind": serde_json::Value::Null,
17919                "allowed_parents": t.allowed_parent_types.clone(),
17920                "allowed_children": t.allowed_child_types.clone(),
17921                "is_creatable": ui_type && t.is_creatable,
17922                "count": count,
17923                "latest": latest.get(&id).copied(),
17924                "registered": false,
17925                "row_id": id,
17926                "ui_type": ui_type,
17927                "deletable": ui_type && count == 0,
17928            }));
17929        }
17930    }
17931    // Sort: most-used first; ties break by verbose_name.
17932    rows.sort_by(|a, b| {
17933        let ac = a.get("count").and_then(|v| v.as_i64()).unwrap_or(0);
17934        let bc = b.get("count").and_then(|v| v.as_i64()).unwrap_or(0);
17935        bc.cmp(&ac).then_with(|| {
17936            a.get("verbose_name")
17937                .and_then(|v| v.as_str())
17938                .unwrap_or("")
17939                .cmp(b.get("verbose_name").and_then(|v| v.as_str()).unwrap_or(""))
17940        })
17941    });
17942
17943    let mut ctx = Context::new();
17944    add_chrome(&mut ctx, &tenant, "page-types", session_user.as_ref()).await;
17945    add_admin_theme(&mut ctx, tenant.pool()).await;
17946    ctx.insert("rows", &rows);
17947    ctx.insert("total_pages", &counts.values().sum::<i64>());
17948    ctx.insert("total_types", &rows.len());
17949    // #566 — the New-page-type affordance is Developer-gated (same
17950    // codename as the field builder). The template also checks the flag.
17951    let can_build = session_user.as_ref().is_some_and(|u| u.is_superuser)
17952        || crate::permissions::user_codenames(
17953            tenant.pool(),
17954            session_user
17955                .as_ref()
17956                .and_then(|u| u.id.get().copied())
17957                .unwrap_or_default(),
17958        )
17959        .await
17960        .unwrap_or_default()
17961        .contains("cms_page_type.build");
17962    ctx.insert("can_build_types", &can_build);
17963    ctx.insert("new_type_url", "/cms-admin/page-types/new");
17964    render_with_csrf(&state, &headers, "rcms_admin/page_types.html", &mut ctx)
17965}
17966
17967// =====================================================================
17968// Users / Roles — native CMS surface (#9). Replaces the prior
17969// `Redirect::to("/admin/rustango_users")` stub.
17970// =====================================================================
17971
17972/// User management is a **superuser-only** operation.
17973///
17974/// The create/edit handlers set `is_superuser`, `active`, and role
17975/// memberships straight from the submitted form, and the handlers
17976/// themselves previously performed no authorization at all — so any user
17977/// whose request reached the admin router could mint a superuser or
17978/// assign themselves a privileged role. Because *every* one of those
17979/// fields is a privilege the caller might not hold, the safe invariant
17980/// is to restrict the whole user-management surface to superusers rather
17981/// than try to police individual field grants. (Delegated, codename-
17982/// scoped user management that forbids privilege escalation can be added
17983/// later as a deliberate feature.)
17984///
17985/// The same gate covers roles and SSO providers, which decide who
17986/// a user *is* as much as the user rows do: a role editor could grant its
17987/// own role every codename, and an SSO-provider editor could point an
17988/// issuer at an IdP it controls and sign in as any user by email.
17989///
17990/// Returns `Some(redirect)` when denied — anonymous → login, an
17991/// authenticated non-superuser → the no-access page — and `None` when
17992/// the caller is a superuser and may proceed.
17993fn require_superuser_for_user_admin(
17994    user: Option<&rustango::tenancy::auth::User>,
17995) -> Option<Response> {
17996    use axum::response::{IntoResponse, Redirect};
17997    user_admin_denial_target(user.map(|u| u.is_superuser))
17998        .map(|path| Redirect::to(path).into_response())
17999}
18000
18001/// The redirect target for a user-management request, or `None` when the
18002/// caller (identified only by their superuser status: `None` = anonymous,
18003/// `Some(false)` = signed-in non-superuser, `Some(true)` = superuser) may
18004/// proceed. Split out from [`require_superuser_for_user_admin`] so the
18005/// deny/allow decision is unit-testable without constructing a framework
18006/// `User` (which has no `Default`).
18007fn user_admin_denial_target(is_superuser: Option<bool>) -> Option<&'static str> {
18008    match is_superuser {
18009        Some(true) => None,
18010        Some(false) => Some("/cms-admin/no-access"),
18011        None => Some("/login"),
18012    }
18013}
18014
18015/// GET /cms-admin/users — every tenant user with their assigned
18016/// roles + a delta-since indicator on the last password rotation.
18017pub async fn users_list(
18018    State(state): State<super::AdminState>,
18019    tenant: Tenant,
18020    headers: HeaderMap,
18021    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
18022    Query(paging): Query<crate::admin::pagination::PageQuery>,
18023    axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
18024) -> Result<Response, AdminError> {
18025    use rustango::tenancy::auth::User;
18026    use rustango::tenancy::permissions::UserRole;
18027    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
18028        return Ok(redirect);
18029    }
18030    // One page of users, and only their role links (#627).
18031    let total_users = User::objects().count(tenant.pool()).await?;
18032    let active_users = User::objects().where_(User::active.eq(true)).count(tenant.pool()).await?;
18033    let window = paging.window(usize::try_from(total_users).unwrap_or_default());
18034    let users: Vec<User> = User::objects()
18035        .order_by(&[("username", false)])
18036        .limit(window.limit)
18037        .offset(window.offset)
18038        .fetch(tenant.pool())
18039        .await?;
18040    let roles: Vec<rustango::tenancy::permissions::Role> =
18041        rustango::tenancy::permissions::Role::objects()
18042            .fetch(tenant.pool())
18043            .await?;
18044    let user_ids: Vec<i64> = users.iter().filter_map(|u| u.id.get().copied()).collect();
18045    let user_roles: Vec<UserRole> = if user_ids.is_empty() {
18046        Vec::new()
18047    } else {
18048        UserRole::objects()
18049            .where_(UserRole::user_id.is_in(user_ids))
18050            .fetch(tenant.pool())
18051            .await?
18052    };
18053
18054    let roles_by_id: std::collections::HashMap<i64, &rustango::tenancy::permissions::Role> = roles
18055        .iter()
18056        .filter_map(|r| r.id.get().copied().map(|id| (id, r)))
18057        .collect();
18058    let mut roles_by_user: std::collections::HashMap<i64, Vec<String>> =
18059        std::collections::HashMap::new();
18060    for ur in &user_roles {
18061        if let Some(role) = roles_by_id.get(&ur.role_id) {
18062            roles_by_user
18063                .entry(ur.user_id)
18064                .or_default()
18065                .push(role.name.clone());
18066        }
18067    }
18068
18069    let rows: Vec<serde_json::Value> = users
18070        .iter()
18071        .map(|u| {
18072            let id = u.id.get().copied();
18073            serde_json::json!({
18074                "id": id,
18075                "username": u.username,
18076                "email": user_email(u),
18077                "is_superuser": u.is_superuser,
18078                "active": u.active,
18079                "created_at": u.created_at,
18080                "password_changed_at": u.password_changed_at,
18081                "roles": id.and_then(|i| roles_by_user.get(&i).cloned()).unwrap_or_default(),
18082            })
18083        })
18084        .collect();
18085
18086    let mut ctx = Context::new();
18087    add_chrome(&mut ctx, &tenant, "users", session_user.as_ref()).await;
18088    add_admin_theme(&mut ctx, tenant.pool()).await;
18089    ctx.insert("users", &rows);
18090    ctx.insert("total_users", &total_users);
18091    ctx.insert("active_users", &active_users);
18092    ctx.insert("pagination", &window.context);
18093    ctx.insert("query_string", &raw_query.unwrap_or_default());
18094    render_with_csrf(&state, &headers, "rcms_admin/users_list.html", &mut ctx)
18095}
18096
18097/// Query string for the security log: filters plus pagination. Not a
18098/// flattened [`crate::security_log::Filter`]: serde's `flatten` reads
18099/// every query value as a string, which breaks the numeric fields.
18100#[derive(Debug, Deserialize)]
18101pub struct SecurityLogQuery {
18102    #[serde(default)]
18103    pub event: String,
18104    #[serde(default)]
18105    pub username: String,
18106    #[serde(default)]
18107    pub page: Option<i64>,
18108    #[serde(default)]
18109    pub per_page: Option<usize>,
18110}
18111
18112/// The tag colour a security event shows in.
18113fn security_event_tone(event: &str) -> &'static str {
18114    use crate::security_log as log;
18115    match event {
18116        log::EVENT_LOGIN => "published",
18117        log::EVENT_LOGIN_FAILED => "scheduled",
18118        log::EVENT_LOCKOUT => "expired",
18119        log::EVENT_PERMISSIONS_CHANGED => "archived",
18120        _ => "draft",
18121    }
18122}
18123
18124/// GET /cms-admin/security-log — sign-ins, lockouts, sign-outs, password
18125/// resets and permission changes, newest first (#433). Superuser-only,
18126/// like the user and role screens it audits.
18127pub async fn security_log_page(
18128    State(state): State<super::AdminState>,
18129    tenant: Tenant,
18130    headers: HeaderMap,
18131    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
18132    Query(q): Query<SecurityLogQuery>,
18133) -> Result<Response, AdminError> {
18134    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
18135        return Ok(redirect);
18136    }
18137    let per_page = crate::admin::pagination::clamp_per_page(q.per_page);
18138    let filter = crate::security_log::Filter {
18139        event: q.event.trim().to_owned(),
18140        username: q.username.trim().to_owned(),
18141    };
18142    let total = crate::security_log::count(tenant.pool(), &filter).await?;
18143    let pagination = crate::admin::pagination::context(
18144        q.page.unwrap_or(1),
18145        per_page,
18146        usize::try_from(total).unwrap_or(0),
18147    );
18148    // Clamped into range, so a page past the end shows the last one.
18149    let page = pagination["page"].as_i64().unwrap_or(1);
18150    let events = crate::security_log::list(
18151        tenant.pool(),
18152        &filter,
18153        per_page as i64,
18154        crate::admin::pagination::offset(page, per_page),
18155    )
18156    .await?;
18157    let rows: Vec<serde_json::Value> = events
18158        .iter()
18159        .map(|e| {
18160            serde_json::json!({
18161                "event": e.event,
18162                "tone": security_event_tone(&e.event),
18163                "source": e.source,
18164                "user_id": e.user_id,
18165                "username": e.username,
18166                "reason": e.reason,
18167                "actor": e.actor,
18168                "detail": e.detail,
18169                "ip_address": e.ip_address,
18170                "user_agent": e.user_agent,
18171                "created_at": e.created_at.get().copied(),
18172            })
18173        })
18174        .collect();
18175
18176    let mut ctx = Context::new();
18177    add_chrome(&mut ctx, &tenant, "security-log", session_user.as_ref()).await;
18178    add_admin_theme(&mut ctx, tenant.pool()).await;
18179    ctx.insert("rows", &rows);
18180    ctx.insert("total", &total);
18181    ctx.insert("events", crate::security_log::EVENTS);
18182    ctx.insert("filter_event", &filter.event);
18183    ctx.insert("filter_username", &filter.username);
18184    ctx.insert("pagination", &pagination);
18185    render_with_csrf(&state, &headers, "rcms_admin/security_log.html", &mut ctx)
18186}
18187
18188/// GET /cms-admin/roles — list every role with its permission count
18189/// and member count.
18190pub async fn roles_list(
18191    State(state): State<super::AdminState>,
18192    tenant: Tenant,
18193    headers: HeaderMap,
18194    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
18195) -> Result<Response, AdminError> {
18196    // Identity administration is superuser-only (#672).
18197    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
18198        return Ok(redirect);
18199    }
18200    // Not paged: one row per role an administrator defined. Grants and
18201    // members are counted in SQL — members grow with the user base.
18202    let roles: Vec<rustango::tenancy::permissions::Role> =
18203        rustango::tenancy::permissions::Role::objects()
18204            .order_by(&[("name", false)])
18205            .fetch(tenant.pool())
18206            .await?;
18207    let perm_counts = counts_by(
18208        tenant.pool(),
18209        rustango::tenancy::permissions::RolePermission::objects(),
18210        "role_id",
18211    )
18212    .await?;
18213    let member_counts = counts_by(
18214        tenant.pool(),
18215        rustango::tenancy::permissions::UserRole::objects(),
18216        "role_id",
18217    )
18218    .await?;
18219
18220    let rows: Vec<serde_json::Value> = roles
18221        .iter()
18222        .map(|r| {
18223            let id = r.id.get().copied().unwrap_or_default();
18224            serde_json::json!({
18225                "id": id,
18226                "name": r.name,
18227                "description": r.description,
18228                "perm_count": perm_counts.get(&id).copied().unwrap_or(0),
18229                "member_count": member_counts.get(&id).copied().unwrap_or(0),
18230            })
18231        })
18232        .collect();
18233    let mut ctx = Context::new();
18234    add_chrome(&mut ctx, &tenant, "roles", session_user.as_ref()).await;
18235    add_admin_theme(&mut ctx, tenant.pool()).await;
18236    ctx.insert("roles", &rows);
18237    render_with_csrf(&state, &headers, "rcms_admin/roles_list.html", &mut ctx)
18238}
18239
18240/// GET `/cms-admin/permissions` — tenant-wide permission
18241/// overview matrix. The role editor matrix shows one role at a time;
18242/// this is the read-only birds-eye: every resource (grouped by section)
18243/// × every role, each cell listing the granted actions. Answers "who
18244/// can publish pages?" / "what can this role touch?" at a glance.
18245pub async fn permissions_overview(
18246    State(state): State<super::AdminState>,
18247    tenant: Tenant,
18248    headers: HeaderMap,
18249    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
18250) -> Result<Response, AdminError> {
18251    let roles: Vec<rustango::tenancy::permissions::Role> =
18252        rustango::tenancy::permissions::Role::objects()
18253            .order_by(&[("name", false)])
18254            .fetch(tenant.pool())
18255            .await?;
18256    let perms: Vec<rustango::tenancy::permissions::RolePermission> =
18257        rustango::tenancy::permissions::RolePermission::objects()
18258            .fetch(tenant.pool())
18259            .await?;
18260    let granted: std::collections::HashSet<(i64, String)> = perms
18261        .iter()
18262        .map(|p| (p.role_id, p.codename.clone()))
18263        .collect();
18264
18265    let role_headers: Vec<serde_json::Value> = roles
18266        .iter()
18267        .map(|r| {
18268            serde_json::json!({
18269                "id": r.id.get().copied().unwrap_or_default(),
18270                "name": r.name,
18271            })
18272        })
18273        .collect();
18274
18275    // sections → resource rows → one cell per role (granted action codes).
18276    let sections: Vec<serde_json::Value> = super::resources::grouped()
18277        .into_iter()
18278        .map(|(section, resources)| {
18279            let rows: Vec<serde_json::Value> = resources
18280                .iter()
18281                .map(|res| {
18282                    let cells: Vec<serde_json::Value> = roles
18283                        .iter()
18284                        .map(|r| {
18285                            let rid = r.id.get().copied().unwrap_or_default();
18286                            let actions = super::resources::granted_actions(res, rid, &granted);
18287                            serde_json::json!({
18288                                "actions": actions,
18289                                "any": !actions.is_empty(),
18290                            })
18291                        })
18292                        .collect();
18293                    serde_json::json!({
18294                        "label": res.label,
18295                        "key": res.key,
18296                        "cells": cells,
18297                    })
18298                })
18299                .collect();
18300            serde_json::json!({
18301                "label": section.label(),
18302                "rows": rows,
18303            })
18304        })
18305        .collect();
18306
18307    let mut ctx = Context::new();
18308    add_chrome(&mut ctx, &tenant, "permissions", session_user.as_ref()).await;
18309    add_admin_theme(&mut ctx, tenant.pool()).await;
18310    ctx.insert("roles", &role_headers);
18311    ctx.insert("sections", &sections);
18312    ctx.insert("role_count", &role_headers.len());
18313    render_with_csrf(
18314        &state,
18315        &headers,
18316        "rcms_admin/permissions_overview.html",
18317        &mut ctx,
18318    )
18319}
18320
18321/// GET /cms-admin/roles/new — create form.
18322pub async fn roles_new_form(
18323    State(state): State<super::AdminState>,
18324    tenant: Tenant,
18325    headers: HeaderMap,
18326    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
18327) -> Result<Response, AdminError> {
18328    // Identity administration is superuser-only (#672).
18329    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
18330        return Ok(redirect);
18331    }
18332    let mut ctx = Context::new();
18333    add_chrome(&mut ctx, &tenant, "roles", session_user.as_ref()).await;
18334    add_admin_theme(&mut ctx, tenant.pool()).await;
18335    ctx.insert("mode", "new");
18336    ctx.insert(
18337        "role",
18338        &serde_json::json!({ "id": serde_json::Value::Null, "name": "", "description": "", "permissions": [] }),
18339    );
18340    ctx.insert("matrix", &build_permission_matrix(&[]));
18341    ctx.insert("legacy_codenames", &Vec::<String>::new());
18342    render_with_csrf(&state, &headers, "rcms_admin/role_form.html", &mut ctx)
18343}
18344
18345/// GET /cms-admin/roles/{id}/edit — edit form with permission
18346/// codenames pre-populated.
18347pub async fn roles_edit_form(
18348    State(state): State<super::AdminState>,
18349    tenant: Tenant,
18350    headers: HeaderMap,
18351    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
18352    Path(id): Path<i64>,
18353) -> Result<Response, AdminError> {
18354    // Identity administration is superuser-only (#672).
18355    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
18356        return Ok(redirect);
18357    }
18358    let role = rustango::tenancy::permissions::Role::objects()
18359        .where_(rustango::tenancy::permissions::Role::id.eq(id))
18360        .first(tenant.pool())
18361        .await?
18362        .ok_or(AdminError::NotFound(id))?;
18363    let perms: Vec<rustango::tenancy::permissions::RolePermission> =
18364        rustango::tenancy::permissions::RolePermission::objects()
18365            .where_(rustango::tenancy::permissions::RolePermission::role_id.eq(id))
18366            .order_by(&[("codename", false)])
18367            .fetch(tenant.pool())
18368            .await?;
18369    let codenames: Vec<String> = perms.iter().map(|p| p.codename.clone()).collect();
18370    let (_matched, legacy) = split_matrix_codenames(&codenames);
18371    let mut ctx = Context::new();
18372    add_chrome(&mut ctx, &tenant, "roles", session_user.as_ref()).await;
18373    add_admin_theme(&mut ctx, tenant.pool()).await;
18374    ctx.insert("mode", "edit");
18375    ctx.insert(
18376        "role",
18377        &serde_json::json!({
18378            "id": role.id.get().copied(),
18379            "name": role.name,
18380            "description": role.description,
18381            "permissions": codenames,
18382        }),
18383    );
18384    ctx.insert("matrix", &build_permission_matrix(&codenames));
18385    ctx.insert("legacy_codenames", &legacy);
18386    render_with_csrf(&state, &headers, "rcms_admin/role_form.html", &mut ctx)
18387}
18388
18389/// Build the matrix structure consumed by `role_form.html`.
18390/// Returns one JSON object per [`super::resources::ResourceSection`]
18391/// with its rows pre-populated against the granted codename set so
18392/// the template can render checkboxes pre-checked.
18393///
18394/// The matrix is keyed by *resource key* (e.g. `pages`,
18395/// `library_item:author`) rather than codename so the same template
18396/// works regardless of which library types / custom admin pages a
18397/// downstream crate registers.
18398fn build_permission_matrix(granted: &[String]) -> serde_json::Value {
18399    use super::resources::{codename, grouped};
18400    use crate::permissions::Action;
18401
18402    let granted_set: std::collections::HashSet<&str> = granted.iter().map(String::as_str).collect();
18403
18404    let mut sections = Vec::new();
18405    for (section, rows) in grouped() {
18406        let rows_json: Vec<serde_json::Value> = rows
18407            .iter()
18408            .map(|r| {
18409                let applicable: Vec<&str> = r.actions.iter().map(|a| a.as_str()).collect();
18410                let granted_actions: Vec<&str> = [
18411                    Action::Access,
18412                    Action::AccessAdmin,
18413                    Action::View,
18414                    Action::Add,
18415                    Action::Edit,
18416                    Action::Publish,
18417                    Action::Delete,
18418                ]
18419                .iter()
18420                .copied()
18421                .filter(|action| {
18422                    r.actions.contains(action)
18423                        && granted_set.contains(codename(r, *action).as_str())
18424                })
18425                .map(|a| a.as_str())
18426                .collect();
18427                serde_json::json!({
18428                    "key": r.key,
18429                    "label": r.label,
18430                    "applicable": applicable,
18431                    "granted": granted_actions,
18432                })
18433            })
18434            .collect();
18435        sections.push(serde_json::json!({
18436            "section_label": section.label(),
18437            "rows": rows_json,
18438        }));
18439    }
18440    serde_json::Value::Array(sections)
18441}
18442
18443/// Split the supplied codename list into:
18444/// 1. The codenames represented in the matrix (`matched`) — these
18445///    get fully re-computed from the form submission.
18446/// 2. Everything else (`legacy`) — preserved across saves so
18447///    out-of-matrix grants (third-party codenames, ad-hoc strings
18448///    from before the matrix existed) survive a role edit.
18449fn split_matrix_codenames(granted: &[String]) -> (Vec<String>, Vec<String>) {
18450    use super::resources::{all_resources, codename};
18451    use crate::permissions::Action;
18452
18453    let known: std::collections::HashSet<String> = all_resources()
18454        .iter()
18455        .flat_map(|r| {
18456            r.actions
18457                .iter()
18458                .copied()
18459                .filter(|a| {
18460                    // Mirror the matrix — only actions in `r.actions`
18461                    // can be toggled, so only those codenames are
18462                    // "matrix-owned".
18463                    matches!(
18464                        a,
18465                        Action::View
18466                            | Action::Add
18467                            | Action::Edit
18468                            | Action::Publish
18469                            | Action::Delete
18470                            | Action::Access
18471                            | Action::AccessAdmin
18472                    )
18473                })
18474                .map(|a| codename(r, a))
18475                .collect::<Vec<_>>()
18476        })
18477        .collect();
18478    let (matched, legacy): (Vec<String>, Vec<String>) =
18479        granted.iter().cloned().partition(|c| known.contains(c));
18480    (matched, legacy)
18481}
18482
18483/// Parse the matrix POST shape (`perm[<key>][<action>]=1`) into a
18484/// codename list. Unknown keys / actions are silently dropped — the
18485/// matrix is authoritative for the resources it represents.
18486fn parse_matrix_form(form: &std::collections::HashMap<String, String>) -> Vec<String> {
18487    use super::resources::{all_resources, codename};
18488    use crate::permissions::Action;
18489
18490    let resources = all_resources();
18491    let resource_by_key: std::collections::HashMap<&str, &super::resources::AdminResource> =
18492        resources.iter().map(|r| (r.key.as_str(), r)).collect();
18493
18494    let mut out = Vec::new();
18495    for (raw_key, value) in form {
18496        // Form serializes `name="perm[<key>][<action>]"`. The bracket
18497        // shape stays intact in `serde_urlencoded` because it doesn't
18498        // try to descend nested keys — we parse manually.
18499        let Some(rest) = raw_key.strip_prefix("perm[") else {
18500            continue;
18501        };
18502        let Some((key, rest)) = rest.split_once("][") else {
18503            continue;
18504        };
18505        let Some(action_str) = rest.strip_suffix(']') else {
18506            continue;
18507        };
18508        // Checkbox semantics: present-and-truthy means granted;
18509        // absent means not granted. Browsers always send `1` for
18510        // checked boxes here.
18511        if value.is_empty() || value == "0" || value.eq_ignore_ascii_case("off") {
18512            continue;
18513        }
18514        let Some(resource) = resource_by_key.get(key) else {
18515            continue;
18516        };
18517        let action = match action_str {
18518            "view" => Action::View,
18519            "add" => Action::Add,
18520            "edit" => Action::Edit,
18521            "publish" => Action::Publish,
18522            "delete" => Action::Delete,
18523            "access" => Action::Access,
18524            "access_admin" => Action::AccessAdmin,
18525            _ => continue,
18526        };
18527        if !resource.actions.contains(&action) {
18528            continue;
18529        }
18530        out.push(codename(resource, action));
18531    }
18532    out.sort();
18533    out.dedup();
18534    out
18535}
18536
18537/// Shared helper: replace the codename set for a role with the
18538/// supplied list. Idempotent — added/removed deltas only.
18539async fn sync_role_codenames(
18540    pool: &rustango::sql::Pool,
18541    role_id: i64,
18542    new_codenames: &[String],
18543) -> Result<(), AdminError> {
18544    let existing: Vec<rustango::tenancy::permissions::RolePermission> =
18545        rustango::tenancy::permissions::RolePermission::objects()
18546            .where_(rustango::tenancy::permissions::RolePermission::role_id.eq(role_id))
18547            .fetch(pool)
18548            .await?;
18549    let want: std::collections::BTreeSet<&str> = new_codenames.iter().map(String::as_str).collect();
18550    let have: std::collections::BTreeSet<&str> =
18551        existing.iter().map(|p| p.codename.as_str()).collect();
18552    // Drop the codenames that are no longer wanted.
18553    for p in &existing {
18554        if !want.contains(p.codename.as_str()) {
18555            p.clone().delete(pool).await?;
18556        }
18557    }
18558    // Insert the codenames that aren't already there.
18559    for codename in new_codenames {
18560        if !have.contains(codename.as_str()) {
18561            let mut row = rustango::tenancy::permissions::RolePermission {
18562                id: rustango::sql::Auto::Unset,
18563                role_id,
18564                codename: codename.clone(),
18565            };
18566            row.insert(pool).await?;
18567        }
18568    }
18569    Ok(())
18570}
18571
18572/// POST /cms-admin/roles/new — create a role + sync its codenames.
18573/// Body shape (matrix): `name=`, `description=`, plus one
18574/// `perm[<resource>][<action>]=1` per granted cell.
18575pub async fn roles_create_submit(
18576    State(_state): State<super::AdminState>,
18577    tenant: Tenant,
18578    headers: HeaderMap,
18579    request: crate::security_log::LoginRequest,
18580    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
18581    Form(form): Form<std::collections::HashMap<String, String>>,
18582) -> Result<Response, AdminError> {
18583    // Identity administration is superuser-only (#672).
18584    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
18585        return Ok(redirect);
18586    }
18587    let name = form.get("name").map(|s| s.trim()).unwrap_or("").to_owned();
18588    if name.is_empty() {
18589        return Err(AdminError::Validation("Role name is required.".to_owned()));
18590    }
18591    let description = form
18592        .get("description")
18593        .map(|s| s.trim())
18594        .unwrap_or("")
18595        .to_owned();
18596    let mut row = rustango::tenancy::permissions::Role {
18597        id: rustango::sql::Auto::Unset,
18598        name: name.clone(),
18599        description,
18600        data: serde_json::Value::Object(serde_json::Map::new()),
18601    };
18602    row.insert(tenant.pool()).await?;
18603    let role_id = row.id.get().copied().unwrap_or_default();
18604    let codenames = parse_matrix_form(&form);
18605    sync_role_codenames(tenant.pool(), role_id, &codenames).await?;
18606    let detail = crate::security_log::describe_role_change(&name, &[], &codenames)
18607        .unwrap_or_else(|| format!("role “{name}”: no permissions"));
18608    record_access_change(&tenant, session_user.as_ref(), &request, None, format!("created {detail}"))
18609        .await;
18610    redirect_named_with_message_args(
18611        "rcms-admin:roles",
18612        MsgLevel::Success,
18613        "Role “{name}” created.",
18614        &[("name", name.as_str())],
18615        &headers,
18616    )
18617}
18618
18619/// POST /cms-admin/roles/{id}/edit — update name/description +
18620/// sync the codename set. Out-of-matrix legacy codenames are
18621/// preserved across saves.
18622pub async fn roles_edit_submit(
18623    State(_state): State<super::AdminState>,
18624    tenant: Tenant,
18625    headers: HeaderMap,
18626    request: crate::security_log::LoginRequest,
18627    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
18628    Path(id): Path<i64>,
18629    Form(form): Form<std::collections::HashMap<String, String>>,
18630) -> Result<Response, AdminError> {
18631    // Identity administration is superuser-only (#672).
18632    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
18633        return Ok(redirect);
18634    }
18635    let mut role = rustango::tenancy::permissions::Role::objects()
18636        .where_(rustango::tenancy::permissions::Role::id.eq(id))
18637        .first(tenant.pool())
18638        .await?
18639        .ok_or(AdminError::NotFound(id))?;
18640    let name = form.get("name").map(|s| s.trim()).unwrap_or("").to_owned();
18641    if name.is_empty() {
18642        return Err(AdminError::Validation("Role name is required.".to_owned()));
18643    }
18644    let description = form
18645        .get("description")
18646        .map(|s| s.trim())
18647        .unwrap_or("")
18648        .to_owned();
18649    role.name = name.clone();
18650    role.description = description;
18651    role.save(tenant.pool()).await?;
18652    // Carry over codenames that live outside the matrix surface so
18653    // legacy / third-party codenames aren't silently dropped when
18654    // an admin saves the matrix-only form.
18655    let existing: Vec<rustango::tenancy::permissions::RolePermission> =
18656        rustango::tenancy::permissions::RolePermission::objects()
18657            .where_(rustango::tenancy::permissions::RolePermission::role_id.eq(id))
18658            .fetch(tenant.pool())
18659            .await?;
18660    let existing_codenames: Vec<String> = existing.into_iter().map(|p| p.codename).collect();
18661    let (_old_matrix, legacy) = split_matrix_codenames(&existing_codenames);
18662    let mut codenames = parse_matrix_form(&form);
18663    codenames.extend(legacy);
18664    codenames.sort();
18665    codenames.dedup();
18666    sync_role_codenames(tenant.pool(), id, &codenames).await?;
18667    if let Some(detail) =
18668        crate::security_log::describe_role_change(&name, &existing_codenames, &codenames)
18669    {
18670        record_access_change(&tenant, session_user.as_ref(), &request, None, detail).await;
18671    }
18672    redirect_named_with_message_args(
18673        "rcms-admin:roles",
18674        MsgLevel::Success,
18675        "Role “{name}” saved.",
18676        &[("name", name.as_str())],
18677        &headers,
18678    )
18679}
18680
18681/// POST /cms-admin/roles/{id}/delete — delete the role + its
18682/// codenames + every UserRole row referencing it.
18683pub async fn roles_delete_submit(
18684    State(_state): State<super::AdminState>,
18685    tenant: Tenant,
18686    headers: HeaderMap,
18687    request: crate::security_log::LoginRequest,
18688    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
18689    Path(id): Path<i64>,
18690) -> Result<Response, AdminError> {
18691    // Identity administration is superuser-only (#672).
18692    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
18693        return Ok(redirect);
18694    }
18695    let role = rustango::tenancy::permissions::Role::objects()
18696        .where_(rustango::tenancy::permissions::Role::id.eq(id))
18697        .first(tenant.pool())
18698        .await?
18699        .ok_or(AdminError::NotFound(id))?;
18700    let name = role.name.clone();
18701    // Delete dependent rows manually — the schema FK isn't ON DELETE CASCADE.
18702    for p in rustango::tenancy::permissions::RolePermission::objects()
18703        .where_(rustango::tenancy::permissions::RolePermission::role_id.eq(id))
18704        .fetch(tenant.pool())
18705        .await?
18706    {
18707        p.delete(tenant.pool()).await?;
18708    }
18709    for ur in rustango::tenancy::permissions::UserRole::objects()
18710        .where_(rustango::tenancy::permissions::UserRole::role_id.eq(id))
18711        .fetch(tenant.pool())
18712        .await?
18713    {
18714        ur.delete(tenant.pool()).await?;
18715    }
18716    role.delete(tenant.pool()).await?;
18717    record_access_change(
18718        &tenant,
18719        session_user.as_ref(),
18720        &request,
18721        None,
18722        format!("deleted role “{name}”"),
18723    )
18724    .await;
18725    redirect_named_with_message_args(
18726        "rcms-admin:roles",
18727        MsgLevel::Success,
18728        "Role “{name}” deleted.",
18729        &[("name", name.as_str())],
18730        &headers,
18731    )
18732}
18733
18734/// GET /cms-admin/users/new — create form.
18735pub async fn users_new_form(
18736    State(state): State<super::AdminState>,
18737    tenant: Tenant,
18738    headers: HeaderMap,
18739    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
18740) -> Result<Response, AdminError> {
18741    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
18742        return Ok(redirect);
18743    }
18744    let mut ctx = Context::new();
18745    add_chrome(&mut ctx, &tenant, "users", session_user.as_ref()).await;
18746    add_admin_theme(&mut ctx, tenant.pool()).await;
18747    ctx.insert("mode", "new");
18748    ctx.insert(
18749        "user",
18750        &serde_json::json!({
18751            "id": serde_json::Value::Null,
18752            "username": "",
18753            "is_superuser": false,
18754            "active": true,
18755        }),
18756    );
18757    // Roles can be given right away, not only after a second visit.
18758    let role_choices: Vec<serde_json::Value> = rustango::tenancy::permissions::Role::objects()
18759        .order_by(&[("name", false)])
18760        .fetch(tenant.pool())
18761        .await?
18762        .iter()
18763        .map(|r| {
18764            serde_json::json!({
18765                "id": r.id.get().copied().unwrap_or_default(),
18766                "name": r.name,
18767                "description": r.description,
18768                "assigned": false,
18769            })
18770        })
18771        .collect();
18772    ctx.insert("role_choices", &role_choices);
18773    render_with_csrf(&state, &headers, "rcms_admin/user_form.html", &mut ctx)
18774}
18775
18776/// GET /cms-admin/users/{id}/edit — edit form. Password field stays
18777/// empty by default; leave blank to keep the existing password.
18778/// Includes a role-checkbox group so editors can grant / revoke
18779/// role memberships inline.
18780pub async fn users_edit_form(
18781    State(state): State<super::AdminState>,
18782    tenant: Tenant,
18783    headers: HeaderMap,
18784    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
18785    Path(id): Path<i64>,
18786) -> Result<Response, AdminError> {
18787    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
18788        return Ok(redirect);
18789    }
18790    render_user_edit_page(&state, &tenant, &headers, session_user.as_ref(), id, None).await
18791}
18792
18793async fn render_user_edit_page(
18794    state: &super::AdminState,
18795    tenant: &Tenant,
18796    headers: &HeaderMap,
18797    session_user: Option<&rustango::tenancy::auth::User>,
18798    id: i64,
18799    mcp_one_time: Option<serde_json::Value>,
18800) -> Result<Response, AdminError> {
18801    let user = rustango::tenancy::auth::User::objects()
18802        .where_(rustango::tenancy::auth::User::id.eq(id))
18803        .first(tenant.pool())
18804        .await?
18805        .ok_or(AdminError::NotFound(id))?;
18806    let roles: Vec<rustango::tenancy::permissions::Role> =
18807        rustango::tenancy::permissions::Role::objects()
18808            .order_by(&[("name", false)])
18809            .fetch(tenant.pool())
18810            .await?;
18811    let memberships: Vec<rustango::tenancy::permissions::UserRole> =
18812        rustango::tenancy::permissions::UserRole::objects()
18813            .where_(rustango::tenancy::permissions::UserRole::user_id.eq(id))
18814            .fetch(tenant.pool())
18815            .await?;
18816    let assigned: std::collections::BTreeSet<i64> = memberships.iter().map(|m| m.role_id).collect();
18817
18818    let role_choices: Vec<serde_json::Value> = roles
18819        .iter()
18820        .map(|r| {
18821            let rid = r.id.get().copied().unwrap_or_default();
18822            serde_json::json!({
18823                "id": rid,
18824                "name": r.name,
18825                "description": r.description,
18826                "assigned": assigned.contains(&rid),
18827            })
18828        })
18829        .collect();
18830
18831    // #13 V2 — per-user timezone stored in `User.data.timezone`.
18832    // No framework column change required; the existing JSON bag
18833    // holds the IANA name. Empty / missing = browser-detected
18834    // fallback (the no-flash JS already handles that case).
18835    let user_timezone = user
18836        .data
18837        .get("timezone")
18838        .and_then(serde_json::Value::as_str)
18839        .unwrap_or("")
18840        .to_owned();
18841    let user_email = user_email(&user);
18842
18843    let mut ctx = Context::new();
18844    add_chrome(&mut ctx, tenant, "users", session_user).await;
18845    add_admin_theme(&mut ctx, tenant.pool()).await;
18846    ctx.insert("mode", "edit");
18847    ctx.insert(
18848        "user",
18849        &serde_json::json!({
18850            "id": user.id.get().copied(),
18851            "username": user.username,
18852            "email": user_email,
18853            "is_superuser": user.is_superuser,
18854            "active": user.active,
18855            "timezone": user_timezone,
18856            "password_changed_at": user.password_changed_at,
18857            "created_at": user.created_at,
18858        }),
18859    );
18860    ctx.insert("role_choices", &role_choices);
18861    // #587 — the target user's MCP keys, for admin-managed minting
18862    // (the "register an agent user, give it a key" flow).
18863    let (keys, skills) = mcp_keys_ctx(tenant.pool(), id).await;
18864    ctx.insert("mcp_keys", &keys);
18865    ctx.insert("mcp_skills", &skills);
18866    if let Some(one_time) = &mcp_one_time {
18867        ctx.insert("mcp_one_time", one_time);
18868    }
18869    render_with_csrf(state, headers, "rcms_admin/user_form.html", &mut ctx)
18870}
18871
18872// ------------------------------------------------------------- MCP keys (#587)
18873
18874/// Parse a keys-create form: `label` (optional) + repeated `skill`
18875/// entries (optional scope — empty = the owner's full entitlement).
18876fn parse_mcp_key_form(pairs: &[(String, String)]) -> (String, Vec<String>) {
18877    let label = pairs
18878        .iter()
18879        .find(|(k, _)| k == "label")
18880        .map(|(_, v)| v.trim())
18881        .filter(|v| !v.is_empty())
18882        .unwrap_or("MCP key")
18883        .to_owned();
18884    let skills: Vec<String> = pairs
18885        .iter()
18886        .filter(|(k, v)| k == "skill" && !v.trim().is_empty())
18887        .map(|(_, v)| v.trim().to_owned())
18888        .collect();
18889    (label, skills)
18890}
18891
18892/// Best-effort audit trail for key lifecycle events — explicit source
18893/// because the CMS admin doesn't install `audit::with_source`.
18894async fn audit_mcp_key(
18895    pool: &rustango::sql::Pool,
18896    actor_id: i64,
18897    what: &str,
18898    detail: serde_json::Value,
18899) {
18900    let entry = rustango::audit::PendingEntry {
18901        entity_table: "rustango_agents",
18902        entity_pk: detail
18903            .get("key_id")
18904            .and_then(serde_json::Value::as_i64)
18905            .map(|i| i.to_string())
18906            .unwrap_or_default(),
18907        operation: rustango::audit::AuditOp::Action,
18908        source: rustango::audit::AuditSource::User {
18909            id: actor_id.to_string(),
18910        },
18911        changes: serde_json::json!({ "event": what, "detail": detail }),
18912    };
18913    if let Err(e) = rustango::audit::emit_one(pool, &entry).await {
18914        tracing::warn!(error = %e, "mcp key audit emit failed");
18915    }
18916}
18917
18918/// Mint a user key for `owner_id`, mapping scope-validation failures to a
18919/// user-facing message. Returns the show-once payload for the dialog.
18920async fn mint_mcp_key(
18921    pool: &rustango::sql::Pool,
18922    actor_id: i64,
18923    owner_id: i64,
18924    label: &str,
18925    skills: &[String],
18926) -> Result<serde_json::Value, String> {
18927    match rustango::tenancy::create_user_key_pool(pool, owner_id, label, skills).await {
18928        Ok(issued) => {
18929            let key_id = issued.agent.id.get().copied().unwrap_or_default();
18930            audit_mcp_key(
18931                pool,
18932                actor_id,
18933                "created",
18934                serde_json::json!({ "key_id": key_id, "owner_id": owner_id, "label": label, "scope": skills }),
18935            )
18936            .await;
18937            Ok(serde_json::json!({ "token": issued.token, "label": label }))
18938        }
18939        Err(e) => Err(e.to_string()),
18940    }
18941}
18942
18943/// POST /cms-admin/me/mcp-keys — mint a key for the signed-in user.
18944/// Renders the account page directly with the show-once token (no PRG —
18945/// the token must never ride a redirect or a flash cookie).
18946pub async fn account_mcp_key_create(
18947    State(state): State<super::AdminState>,
18948    tenant: Tenant,
18949    headers: HeaderMap,
18950    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
18951    Form(pairs): Form<Vec<(String, String)>>,
18952) -> Result<Response, AdminError> {
18953    let Some(uid) = session_user.as_ref().and_then(|u| u.id.get().copied()) else {
18954        return Ok(unauthorized_no_session());
18955    };
18956    let (label, skills) = parse_mcp_key_form(&pairs);
18957    match mint_mcp_key(tenant.pool(), uid, uid, &label, &skills).await {
18958        Ok(one_time) => {
18959            render_account_page(
18960                &state,
18961                &tenant,
18962                &headers,
18963                session_user.as_ref(),
18964                Some(one_time),
18965            )
18966            .await
18967        }
18968        Err(msg) => redirect_named_with_message_args(
18969            "rcms-admin:account",
18970            MsgLevel::Error,
18971            "Couldn't create the key: {error}",
18972            &[("error", msg.as_str())],
18973            &headers,
18974        ),
18975    }
18976}
18977
18978/// POST /cms-admin/me/mcp-keys/{id}/revoke — revoke one of the signed-in
18979/// user's keys (ownership-verified in the framework call).
18980pub async fn account_mcp_key_revoke(
18981    State(_state): State<super::AdminState>,
18982    tenant: Tenant,
18983    headers: HeaderMap,
18984    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
18985    Path(key_id): Path<i64>,
18986) -> Result<Response, AdminError> {
18987    let Some(uid) = session_user.as_ref().and_then(|u| u.id.get().copied()) else {
18988        return Ok(unauthorized_no_session());
18989    };
18990    match rustango::tenancy::revoke_user_key_pool(tenant.pool(), uid, key_id).await {
18991        Ok(()) => {
18992            audit_mcp_key(
18993                tenant.pool(),
18994                uid,
18995                "revoked",
18996                serde_json::json!({ "key_id": key_id, "owner_id": uid }),
18997            )
18998            .await;
18999            redirect_named_with_message_args(
19000                "rcms-admin:account",
19001                MsgLevel::Success,
19002                "MCP key revoked.",
19003                &[],
19004                &headers,
19005            )
19006        }
19007        Err(e) => {
19008            let msg = e.to_string();
19009            redirect_named_with_message_args(
19010                "rcms-admin:account",
19011                MsgLevel::Error,
19012                "Couldn't revoke the key: {error}",
19013                &[("error", msg.as_str())],
19014                &headers,
19015            )
19016        }
19017    }
19018}
19019
19020/// POST /cms-admin/users/{id}/mcp-keys — an admin mints a key for another
19021/// user (the "register an agent user, give it a key" flow). Safe by
19022/// construction: the key's capabilities are bounded by the TARGET user's
19023/// entitlement at every token resolution, so this can't escalate beyond
19024/// what that user could already do.
19025pub async fn users_mcp_key_create(
19026    State(state): State<super::AdminState>,
19027    tenant: Tenant,
19028    headers: HeaderMap,
19029    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
19030    Path(user_id): Path<i64>,
19031    Form(pairs): Form<Vec<(String, String)>>,
19032) -> Result<Response, AdminError> {
19033    // #646 — user-management is superuser-only. Without this the two
19034    // mcp-key handlers gated on "a session exists" only, so a non-superuser
19035    // staff account could mint a key bounded by ANY target user's (e.g. a
19036    // superuser's) entitlement — a privilege escalation the other seven
19037    // user-admin handlers already block. Mirror them.
19038    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
19039        return Ok(redirect);
19040    }
19041    let Some(actor_id) = session_user.as_ref().and_then(|u| u.id.get().copied()) else {
19042        return Ok(unauthorized_no_session());
19043    };
19044    let (label, skills) = parse_mcp_key_form(&pairs);
19045    match mint_mcp_key(tenant.pool(), actor_id, user_id, &label, &skills).await {
19046        Ok(one_time) => {
19047            render_user_edit_page(
19048                &state,
19049                &tenant,
19050                &headers,
19051                session_user.as_ref(),
19052                user_id,
19053                Some(one_time),
19054            )
19055            .await
19056        }
19057        Err(msg) => redirect_named_with_params_and_message_args(
19058            "rcms-admin:users:edit",
19059            &[("id", user_id.to_string())],
19060            MsgLevel::Error,
19061            "Couldn't create the key: {error}",
19062            &[("error", msg.as_str())],
19063            &headers,
19064        ),
19065    }
19066}
19067
19068/// POST /cms-admin/users/{id}/mcp-keys/{key_id}/revoke — admin revoke of
19069/// another user's key (ownership pinned to the target user).
19070pub async fn users_mcp_key_revoke(
19071    State(_state): State<super::AdminState>,
19072    tenant: Tenant,
19073    headers: HeaderMap,
19074    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
19075    Path((user_id, key_id)): Path<(i64, i64)>,
19076) -> Result<Response, AdminError> {
19077    // #646 — user-management is superuser-only. Without this the two
19078    // mcp-key handlers gated on "a session exists" only, so a non-superuser
19079    // staff account could mint a key bounded by ANY target user's (e.g. a
19080    // superuser's) entitlement — a privilege escalation the other seven
19081    // user-admin handlers already block. Mirror them.
19082    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
19083        return Ok(redirect);
19084    }
19085    let Some(actor_id) = session_user.as_ref().and_then(|u| u.id.get().copied()) else {
19086        return Ok(unauthorized_no_session());
19087    };
19088    match rustango::tenancy::revoke_user_key_pool(tenant.pool(), user_id, key_id).await {
19089        Ok(()) => {
19090            audit_mcp_key(
19091                tenant.pool(),
19092                actor_id,
19093                "revoked",
19094                serde_json::json!({ "key_id": key_id, "owner_id": user_id }),
19095            )
19096            .await;
19097            redirect_named_with_params_and_message_args(
19098                "rcms-admin:users:edit",
19099                &[("id", user_id.to_string())],
19100                MsgLevel::Success,
19101                "MCP key revoked.",
19102                &[],
19103                &headers,
19104            )
19105        }
19106        Err(e) => {
19107            let msg = e.to_string();
19108            redirect_named_with_params_and_message_args(
19109                "rcms-admin:users:edit",
19110                &[("id", user_id.to_string())],
19111                MsgLevel::Error,
19112                "Couldn't revoke the key: {error}",
19113                &[("error", msg.as_str())],
19114                &headers,
19115            )
19116        }
19117    }
19118}
19119
19120/// Form payload for create + edit. Password is optional on edit
19121/// (empty = "don't change"); required on create (rejected with a
19122/// 400 if missing).
19123#[derive(Deserialize)]
19124pub struct UserForm {
19125    pub username: String,
19126    #[serde(default)]
19127    pub email: Option<String>,
19128    #[serde(default)]
19129    pub password: Option<String>,
19130    #[serde(default)]
19131    pub is_superuser: Option<String>,
19132    #[serde(default)]
19133    pub active: Option<String>,
19134}
19135
19136/// Light email validation (presence of a single `@` with text
19137/// on both sides). Empty is allowed (email is optional). Returns the
19138/// trimmed value to store, or an error message.
19139fn validate_optional_email(raw: Option<&str>) -> Result<String, String> {
19140    let e = raw.map(str::trim).unwrap_or("");
19141    if e.is_empty() {
19142        return Ok(String::new());
19143    }
19144    let ok = e.split('@').count() == 2
19145        && e.split('@').all(|p| !p.is_empty())
19146        && !e.contains(char::is_whitespace);
19147    if ok {
19148        Ok(e.to_owned())
19149    } else {
19150        Err(format!("“{e}” is not a valid email address."))
19151    }
19152}
19153
19154/// POST /cms-admin/users/new — create a new user. Password is
19155/// required; we hash via the framework's argon2id helper.
19156pub async fn users_create_submit(
19157    State(_state): State<super::AdminState>,
19158    tenant: Tenant,
19159    headers: HeaderMap,
19160    request: crate::security_log::LoginRequest,
19161    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
19162    Form(pairs): Form<Vec<(String, String)>>,
19163) -> Result<Response, AdminError> {
19164    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
19165        return Ok(redirect);
19166    }
19167    use rustango::sql::Auto;
19168    // Pairs, not the typed struct: the roles are a multi-value field
19169    // (see `users_edit_submit`), granted at creation too.
19170    let single = |k: &str| pairs.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
19171    let form = UserForm {
19172        username: single("username").unwrap_or_default(),
19173        email: single("email"),
19174        password: single("password"),
19175        is_superuser: single("is_superuser"),
19176        active: single("active"),
19177    };
19178    let role_ids: Vec<i64> = pairs
19179        .iter()
19180        .filter(|(k, _)| k == "role_id")
19181        .filter_map(|(_, v)| v.parse::<i64>().ok())
19182        .collect();
19183    let username = form.username.trim().to_owned();
19184    let password = form
19185        .password
19186        .as_deref()
19187        .map(str::trim)
19188        .filter(|s| !s.is_empty())
19189        .map(str::to_owned);
19190    if username.is_empty() || password.is_none() {
19191        return Err(AdminError::Validation(
19192            "Username and initial password are both required.".to_owned(),
19193        ));
19194    }
19195    let hash = crate::passwords::hash(password.as_deref().unwrap_or_default()).await
19196        .map_err(|e| AdminError::Validation(format!("password hash failed: {e}")))?;
19197    let email = validate_optional_email(form.email.as_deref()).map_err(AdminError::Validation)?;
19198    // The framework's first-class `email` column is the SSO link target (the
19199    // admin-sso login matches the IdP's verified email against it). Set it here;
19200    // NULL when no email was given (that account simply can't sign in via SSO).
19201    let email_col = (!email.is_empty()).then(|| email.clone());
19202
19203    // #435 — also mirror into the User.data bag (legacy readers: users list +
19204    // edit form still read `data.email`).
19205    let mut data = serde_json::Map::new();
19206    if !email.is_empty() {
19207        data.insert("email".to_owned(), serde_json::Value::String(email));
19208    }
19209    let mut row = rustango::tenancy::auth::User {
19210        id: Auto::Unset,
19211        username: username.clone(),
19212        password_hash: hash,
19213        email: email_col,
19214        is_superuser: form.is_superuser.is_some(),
19215        active: form.active.is_some(),
19216        created_at: chrono::Utc::now(),
19217        data: serde_json::Value::Object(data),
19218        password_changed_at: Some(chrono::Utc::now()),
19219        sessions_revoked_at: None,
19220    };
19221    row.insert(tenant.pool()).await?;
19222    if let Some(new_id) = row.id.get().copied() {
19223        sync_user_roles(tenant.pool(), new_id, &role_ids).await?;
19224    }
19225    let access = user_access(tenant.pool(), &row).await?;
19226    record_access_change(
19227        &tenant,
19228        session_user.as_ref(),
19229        &request,
19230        Some(&row),
19231        crate::security_log::describe_new_user(&access),
19232    )
19233    .await;
19234    redirect_named_with_message_args(
19235        "rcms-admin:users",
19236        MsgLevel::Success,
19237        "User “{username}” created.",
19238        &[("username", username.as_str())],
19239        &headers,
19240    )
19241}
19242
19243/// POST /cms-admin/users/{id}/edit — update flags + optionally
19244/// rotate the password (empty password field = no rotation) +
19245/// sync role memberships. Body parsed as `Vec<(String, String)>`
19246/// instead of the typed struct because role_id is a multi-value
19247/// form field — checkbox groups in HTML submit one entry per
19248/// checked box, and serde_urlencoded folds duplicates onto the
19249/// last write.
19250pub async fn users_edit_submit(
19251    State(_state): State<super::AdminState>,
19252    tenant: Tenant,
19253    headers: HeaderMap,
19254    request: crate::security_log::LoginRequest,
19255    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
19256    Path(id): Path<i64>,
19257    Form(form): Form<Vec<(String, String)>>,
19258) -> Result<Response, AdminError> {
19259    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
19260        return Ok(redirect);
19261    }
19262    // Pull each field out of the multi-pair vec. `find` honors the
19263    // first occurrence — fine for single-value fields.
19264    let single = |key: &str| -> Option<String> {
19265        form.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone())
19266    };
19267    let username_raw = single("username").unwrap_or_default();
19268    let username = username_raw.trim().to_owned();
19269    if username.is_empty() {
19270        return Err(AdminError::Validation(
19271            "Username cannot be empty.".to_owned(),
19272        ));
19273    }
19274    let password = single("password");
19275    let is_superuser = form.iter().any(|(k, _)| k == "is_superuser");
19276    let active = form.iter().any(|(k, _)| k == "active");
19277    let timezone_raw = single("timezone").unwrap_or_default();
19278    let timezone = timezone_raw.trim().to_owned();
19279    // #435 — optional email, validated + stored in User.data.
19280    let email =
19281        validate_optional_email(single("email").as_deref()).map_err(AdminError::Validation)?;
19282    let role_ids: Vec<i64> = form
19283        .iter()
19284        .filter(|(k, _)| k == "role_id")
19285        .filter_map(|(_, v)| v.parse::<i64>().ok())
19286        .collect();
19287
19288    let mut user = rustango::tenancy::auth::User::objects()
19289        .where_(rustango::tenancy::auth::User::id.eq(id))
19290        .first(tenant.pool())
19291        .await?
19292        .ok_or(AdminError::NotFound(id))?;
19293    let before = user_access(tenant.pool(), &user).await?;
19294    user.username = username.clone();
19295    user.is_superuser = is_superuser;
19296    user.active = active;
19297    // #13 V2 — persist the chosen IANA timezone (or unset key
19298    // entirely when blank) on the User.data JSON bag.
19299    {
19300        let map = user.data.as_object_mut().ok_or_else(|| {
19301            AdminError::Validation(
19302                "User.data is not a JSON object — refusing to overwrite.".to_owned(),
19303            )
19304        })?;
19305        if timezone.is_empty() {
19306            map.remove("timezone");
19307        } else {
19308            map.insert(
19309                "timezone".to_owned(),
19310                serde_json::Value::String(timezone.clone()),
19311            );
19312        }
19313        if email.is_empty() {
19314            map.remove("email");
19315        } else {
19316            map.insert("email".to_owned(), serde_json::Value::String(email.clone()));
19317        }
19318    }
19319    // Keep the first-class `email` column (the admin-sso link target) in sync
19320    // with the edited address — NULL clears the SSO link for this user.
19321    user.email = (!email.is_empty()).then(|| email.clone());
19322
19323    let rotated = password.as_deref().map(str::trim).filter(|s| !s.is_empty());
19324    if let Some(new_pw) = rotated {
19325        let hash = crate::passwords::hash(new_pw).await
19326            .map_err(|e| AdminError::Validation(format!("password hash failed: {e}")))?;
19327        user.password_hash = hash;
19328        user.password_changed_at = Some(chrono::Utc::now());
19329    }
19330    user.save(tenant.pool()).await?;
19331    sync_user_roles(tenant.pool(), id, &role_ids).await?;
19332    let after = user_access(tenant.pool(), &user).await?;
19333    if let Some(detail) = crate::security_log::describe_user_change(&before, &after) {
19334        record_access_change(&tenant, session_user.as_ref(), &request, Some(&user), detail).await;
19335    }
19336    if rotated.is_some() {
19337        redirect_named_with_message_args(
19338            "rcms-admin:users",
19339            MsgLevel::Success,
19340            "User “{username}” saved (password rotated).",
19341            &[("username", username.as_str())],
19342            &headers,
19343        )
19344    } else {
19345        redirect_named_with_message_args(
19346            "rcms-admin:users",
19347            MsgLevel::Success,
19348            "User “{username}” saved.",
19349            &[("username", username.as_str())],
19350            &headers,
19351        )
19352    }
19353}
19354
19355/// Shared helper — replace a user's role-membership set with the
19356/// supplied list. Idempotent; computes adds + drops via set diff.
19357async fn sync_user_roles(
19358    pool: &rustango::sql::Pool,
19359    user_id: i64,
19360    new_role_ids: &[i64],
19361) -> Result<(), AdminError> {
19362    let existing: Vec<rustango::tenancy::permissions::UserRole> =
19363        rustango::tenancy::permissions::UserRole::objects()
19364            .where_(rustango::tenancy::permissions::UserRole::user_id.eq(user_id))
19365            .fetch(pool)
19366            .await?;
19367    let want: std::collections::BTreeSet<i64> = new_role_ids.iter().copied().collect();
19368    let have: std::collections::BTreeSet<i64> = existing.iter().map(|m| m.role_id).collect();
19369    for m in &existing {
19370        if !want.contains(&m.role_id) {
19371            m.clone().delete(pool).await?;
19372        }
19373    }
19374    for role_id in new_role_ids {
19375        if !have.contains(role_id) {
19376            let mut row = rustango::tenancy::permissions::UserRole {
19377                id: rustango::sql::Auto::Unset,
19378                user_id,
19379                role_id: *role_id,
19380            };
19381            row.insert(pool).await?;
19382        }
19383    }
19384    Ok(())
19385}
19386
19387/// `user`'s flags and role names, as the security log compares them.
19388async fn user_access(
19389    pool: &rustango::sql::Pool,
19390    user: &rustango::tenancy::auth::User,
19391) -> Result<crate::security_log::Access, AdminError> {
19392    use rustango::tenancy::permissions::{Role, UserRole};
19393    let role_ids: Vec<i64> = match user.id.get().copied() {
19394        Some(uid) => UserRole::objects()
19395            .where_(UserRole::user_id.eq(uid))
19396            .fetch(pool)
19397            .await?
19398            .into_iter()
19399            .map(|m| m.role_id)
19400            .collect(),
19401        None => Vec::new(),
19402    };
19403    let roles = if role_ids.is_empty() {
19404        Vec::new()
19405    } else {
19406        Role::objects()
19407            .where_(Role::id.is_in(role_ids))
19408            .fetch(pool)
19409            .await?
19410            .into_iter()
19411            .map(|r| r.name)
19412            .collect()
19413    };
19414    Ok(crate::security_log::Access {
19415        superuser: user.is_superuser,
19416        active: user.active,
19417        roles,
19418    })
19419}
19420
19421/// Log a change to who may do what, made by `actor` to `target` (a
19422/// user, or `None` for a role).
19423async fn record_access_change(
19424    tenant: &Tenant,
19425    actor: Option<&rustango::tenancy::auth::User>,
19426    request: &crate::security_log::LoginRequest,
19427    target: Option<&rustango::tenancy::auth::User>,
19428    detail: String,
19429) {
19430    let mut entry = SecurityEntry::new(
19431        crate::security_log::EVENT_PERMISSIONS_CHANGED,
19432        "admin",
19433        &request.meta,
19434    )
19435    .change(actor.map_or("", |u| u.username.as_str()), detail);
19436    if let Some(user) = target {
19437        entry = entry.user(user.id.get().copied(), &user.username);
19438    }
19439    crate::security_log::record(tenant.pool(), &tenant.org.slug, entry).await;
19440}
19441
19442/// POST /cms-admin/users/{id}/deactivate — flip the `active` bit
19443/// off. Idempotent. Reversed via the edit form's checkbox.
19444pub async fn users_deactivate_submit(
19445    State(_state): State<super::AdminState>,
19446    tenant: Tenant,
19447    headers: HeaderMap,
19448    request: crate::security_log::LoginRequest,
19449    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
19450    Path(id): Path<i64>,
19451) -> Result<Response, AdminError> {
19452    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
19453        return Ok(redirect);
19454    }
19455    let mut user = rustango::tenancy::auth::User::objects()
19456        .where_(rustango::tenancy::auth::User::id.eq(id))
19457        .first(tenant.pool())
19458        .await?
19459        .ok_or(AdminError::NotFound(id))?;
19460    let was_active = user.active;
19461    user.active = false;
19462    user.save(tenant.pool()).await?;
19463    if was_active {
19464        record_access_change(
19465            &tenant,
19466            session_user.as_ref(),
19467            &request,
19468            Some(&user),
19469            "active: on → off".to_owned(),
19470        )
19471        .await;
19472    }
19473    redirect_named_with_message_args(
19474        "rcms-admin:users",
19475        MsgLevel::Success,
19476        "User “{username}” deactivated.",
19477        &[("username", user.username.as_str())],
19478        &headers,
19479    )
19480}
19481
19482/// POST /cms-admin/users/bulk — enable or disable the selected users
19483/// (bulk actions). `user_id` repeats once per checked row;
19484/// `action` is the clicked button (`enable` | `disable`). Disabling
19485/// your own account is skipped so an admin can't lock themselves out.
19486pub async fn users_bulk_submit(
19487    State(_state): State<super::AdminState>,
19488    tenant: Tenant,
19489    headers: HeaderMap,
19490    request: crate::security_log::LoginRequest,
19491    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
19492    Form(pairs): Form<Vec<(String, String)>>,
19493) -> Result<Response, AdminError> {
19494    if let Some(redirect) = require_superuser_for_user_admin(session_user.as_ref()) {
19495        return Ok(redirect);
19496    }
19497    let mut ids: Vec<i64> = Vec::new();
19498    let mut action = String::new();
19499    for (k, v) in &pairs {
19500        match k.as_str() {
19501            "user_id" => {
19502                if let Ok(id) = v.parse::<i64>() {
19503                    ids.push(id);
19504                }
19505            }
19506            "action" => action = v.clone(),
19507            _ => {}
19508        }
19509    }
19510    let target_active = match action.as_str() {
19511        "enable" => true,
19512        "disable" => false,
19513        _ => {
19514            return redirect_named_with_message(
19515                "rcms-admin:users",
19516                MsgLevel::Error,
19517                "Unknown bulk action.",
19518                &headers,
19519            );
19520        }
19521    };
19522    if ids.is_empty() {
19523        return redirect_named_with_message(
19524            "rcms-admin:users",
19525            MsgLevel::Info,
19526            "No users selected.",
19527            &headers,
19528        );
19529    }
19530    let me = session_user.as_ref().and_then(|u| u.id.get().copied());
19531    let mut changed = 0usize;
19532    let mut skipped_self = false;
19533    // Never disable the acting admin — that's a self-lockout.
19534    if !target_active && me.is_some_and(|m| ids.contains(&m)) {
19535        skipped_self = true;
19536        ids.retain(|id| Some(*id) != me);
19537    }
19538    // The selected users in one read per chunk (#631); each change is
19539    // still saved and logged on its own.
19540    let mut by_id = std::collections::HashMap::new();
19541    for chunk in ids.chunks(500) {
19542        use rustango::tenancy::auth::User;
19543        for u in User::objects().where_(User::id.is_in(chunk.to_vec())).fetch(tenant.pool()).await? {
19544            if let Some(id) = u.id.get().copied() {
19545                by_id.insert(id, u);
19546            }
19547        }
19548    }
19549    // In the posted order, so the audit rows follow the selection.
19550    let users: Vec<_> = ids.iter().filter_map(|id| by_id.remove(id)).collect();
19551    for mut user in users {
19552        {
19553            if user.active != target_active {
19554                user.active = target_active;
19555                user.save(tenant.pool()).await?;
19556                changed += 1;
19557                let detail = if target_active { "active: off → on" } else { "active: on → off" };
19558                record_access_change(
19559                    &tenant,
19560                    session_user.as_ref(),
19561                    &request,
19562                    Some(&user),
19563                    detail.to_owned(),
19564                )
19565                .await;
19566            }
19567        }
19568    }
19569    let verb = if target_active { "Enabled" } else { "Disabled" };
19570    let mut msg = format!("{verb} {changed} user(s).");
19571    if skipped_self {
19572        msg.push_str(" (Skipped your own account.)");
19573    }
19574    redirect_named_with_message("rcms-admin:users", MsgLevel::Success, &msg, &headers)
19575}
19576
19577// =====================================================================
19578// Settings tab
19579// =====================================================================
19580
19581pub async fn settings_page(
19582    State(state): State<super::AdminState>,
19583    tenant: Tenant,
19584    headers: HeaderMap,
19585    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
19586) -> Result<Response, AdminError> {
19587    // Pictures uploaded before Branding used the media library move into
19588    // it, so the form below can show and change them.
19589    crate::branding::migrate_uploads(tenant.pool(), &tenant.org.slug).await;
19590    let locales: Vec<Locale> = Locale::objects()
19591        .order_by(&[("sort_order", false), ("code", false)])
19592        .fetch(tenant.pool())
19593        .await?;
19594    let media_count: Vec<Media> = Media::objects().fetch(tenant.pool()).await?;
19595    // #58 — themes available to the picker. We surface every row in
19596    // `cms_theme` plus its 4 marquee colors for a swatch preview.
19597    let themes: Vec<crate::theme::Theme> = crate::theme::Theme::objects()
19598        .order_by(&[("name", false)])
19599        .fetch(tenant.pool())
19600        .await?;
19601    let theme_rows: Vec<serde_json::Value> = themes
19602        .iter()
19603        .map(|t| {
19604            serde_json::json!({
19605                "id": t.id.get().copied(),
19606                "name": t.name,
19607                "slug": t.slug,
19608                "is_admin_default": t.is_admin_default,
19609                "is_default": t.is_default,
19610                "color_bg": t.color_bg,
19611                "color_surface": t.color_surface,
19612                "color_text_primary": t.color_text_primary,
19613                "color_link": t.color_link,
19614            })
19615        })
19616        .collect();
19617    let mut ctx = Context::new();
19618    add_chrome(&mut ctx, &tenant, "settings", session_user.as_ref()).await;
19619    add_admin_theme(&mut ctx, tenant.pool()).await;
19620    ctx.insert("locales", &locales);
19621    ctx.insert("media_count", &media_count.len());
19622    ctx.insert("org_slug", &tenant.org.slug);
19623    ctx.insert("org_display_name", &tenant.org.display_name);
19624    ctx.insert("themes", &theme_rows);
19625
19626    // Branding: the site name and two pictures from the media library.
19627    let branding = crate::branding::get(tenant.pool()).await;
19628    let picked = |picture: crate::branding::Picture| {
19629        branding.get(picture.key()).and_then(|v| v.as_str()).unwrap_or("").to_owned()
19630    };
19631    let chooser = |picture: crate::branding::Picture, label: &str, help: &str| {
19632        crate::widget::Widget::new(crate::widget::WidgetKind::MediaPicker, picture.key(), super::i18n::tr(&headers, label, &[]))
19633            .with_value(picked(picture))
19634            .with_help(super::i18n::tr(&headers, help, &[]))
19635    };
19636    ctx.insert(
19637        "branding_pictures",
19638        &[
19639            chooser(crate::branding::Picture::Logo, "Logo", "Shown beside the site name in the admin and on the site."),
19640            chooser(crate::branding::Picture::Favicon, "Site icon", "The small picture browsers show in the tab. A square picture works best."),
19641        ],
19642    );
19643    ctx.insert(
19644        "branding_site_name",
19645        branding.get("site_name").and_then(|v| v.as_str()).unwrap_or(""),
19646    );
19647
19648    render_with_csrf(&state, &headers, "rcms_admin/settings.html", &mut ctx)
19649}
19650
19651/// POST /cms-admin/settings/branding — the site name and the logo and
19652/// icon, picked from the media library (media ids). An empty field clears
19653/// it. Stored in the `branding` site setting (see `crate::branding`).
19654pub async fn settings_branding_submit(
19655    State(_state): State<super::AdminState>,
19656    tenant: Tenant,
19657    headers: HeaderMap,
19658    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
19659    axum::Form(form): axum::Form<std::collections::HashMap<String, String>>,
19660) -> Result<Response, AdminError> {
19661    let mut value = crate::branding::get(tenant.pool()).await.as_object().cloned().unwrap_or_default();
19662    let site_name: String = form.get("site_name").map(|n| n.trim().chars().take(120).collect()).unwrap_or_default();
19663    if site_name.is_empty() {
19664        value.remove("site_name");
19665    } else {
19666        value.insert("site_name".to_owned(), serde_json::json!(site_name));
19667    }
19668    for picture in [crate::branding::Picture::Logo, crate::branding::Picture::Favicon] {
19669        let Some(raw) = form.get(picture.key()) else { continue };
19670        let id = raw.trim();
19671        // A picked picture replaces an older upload; an empty field clears both.
19672        value.remove(&format!("{}_storage_key", picture.key()));
19673        if id.is_empty() {
19674            value.remove(picture.key());
19675        } else if id.parse::<i64>().is_ok() {
19676            value.insert(picture.key().to_owned(), serde_json::json!(id));
19677        }
19678    }
19679    crate::site_setting::upsert(tenant.pool(), crate::branding::SCOPE, serde_json::Value::Object(value)).await?;
19680
19681    redirect_named_with_message(
19682        "rcms-admin:settings",
19683        MsgLevel::Success,
19684        "Branding saved.",
19685        &headers,
19686    )
19687}
19688
19689/// GET /__cms-branding/logo — streams the per-tenant logo bytes.
19690/// Anonymous-OK: this is admin chrome but the favicon especially
19691/// needs to be reachable before login.
19692pub async fn settings_branding_serve_logo(headers: HeaderMap, tenant: Tenant) -> Response {
19693    serve_branding_asset(&headers, &tenant, crate::branding::Picture::Logo).await
19694}
19695
19696/// GET /__cms-branding/favicon — streams the per-tenant favicon.
19697pub async fn settings_branding_serve_favicon(headers: HeaderMap, tenant: Tenant) -> Response {
19698    serve_branding_asset(&headers, &tenant, crate::branding::Picture::Favicon).await
19699}
19700
19701async fn serve_branding_asset(headers: &HeaderMap, tenant: &Tenant, picture: crate::branding::Picture) -> Response {
19702    let branding = crate::branding::get(tenant.pool()).await;
19703    let Some((mime, bytes)) = crate::branding::load(tenant.pool(), &tenant.org.slug, &branding, picture).await else {
19704        return (axum::http::StatusCode::NOT_FOUND, "no branding picture").into_response();
19705    };
19706    // #199 fix — the URL is stable (`/__cms-branding/logo|favicon`) and
19707    // the storage key can stay the same across a re-upload, so the old
19708    // `public, max-age=3600` (no validator) left browsers showing the
19709    // OLD logo/favicon for up to an hour after a change (the reported
19710    // "upload didn't work"). Revalidate via a content ETag instead.
19711    revalidated_asset(headers, mime, bytes)
19712}
19713
19714/// Response for a small, mutable asset served from a STABLE URL
19715/// (branding logo/favicon, user avatar): a content-hash ETag plus
19716/// `Cache-Control: no-cache` (cache, but always revalidate) so a
19717/// re-upload is picked up immediately — no stale-for-an-hour window —
19718/// while unchanged bytes still `304` cheaply (`If-None-Match` honored).
19719fn revalidated_asset(headers: &HeaderMap, mime: String, bytes: Vec<u8>) -> Response {
19720    use sha2::{Digest, Sha256};
19721    let digest = Sha256::digest(&bytes);
19722    let mut etag = String::with_capacity(34);
19723    etag.push('"');
19724    for b in digest.iter().take(16) {
19725        use std::fmt::Write as _;
19726        let _ = write!(etag, "{b:02x}");
19727    }
19728    etag.push('"');
19729    let matches_etag = headers
19730        .get(axum::http::header::IF_NONE_MATCH)
19731        .and_then(|v| v.to_str().ok())
19732        .is_some_and(|inm| inm.split(',').any(|t| t.trim() == etag));
19733    if matches_etag {
19734        return (
19735            axum::http::StatusCode::NOT_MODIFIED,
19736            [
19737                (axum::http::header::ETAG, etag),
19738                (axum::http::header::CACHE_CONTROL, "no-cache".to_owned()),
19739            ],
19740        )
19741            .into_response();
19742    }
19743    (
19744        [
19745            (axum::http::header::CONTENT_TYPE, mime),
19746            (axum::http::header::CACHE_CONTROL, "no-cache".to_owned()),
19747            (axum::http::header::ETAG, etag),
19748        ],
19749        bytes,
19750    )
19751        .into_response()
19752}
19753
19754/// POST /cms-admin/settings/theme — flip either `is_admin_default`
19755/// or `is_default` to a new theme. Form fields:
19756///
19757/// - `surface`: either `admin` or `public` — picks which flag to toggle.
19758/// - `theme_id`: the row to set the flag on.
19759///
19760/// The flag is exclusive per surface (one row at a time carries it),
19761/// so we explicitly clear it from every other row in the same pass.
19762#[derive(Debug, Deserialize)]
19763pub struct ThemeSwitchForm {
19764    pub surface: String,
19765    pub theme_id: i64,
19766}
19767
19768pub async fn settings_theme_switch(
19769    State(_state): State<super::AdminState>,
19770    tenant: Tenant,
19771    headers: HeaderMap,
19772    Form(form): Form<ThemeSwitchForm>,
19773) -> Result<Response, AdminError> {
19774    // #174 — only `surface=admin` is reachable through the UI now.
19775    // The `public` value is still accepted at the API level so host
19776    // crates that drive public-page theming externally keep working,
19777    // but no editor surface posts it anymore.
19778    if form.surface != "admin" && form.surface != "public" {
19779        return Err(AdminError::Validation(format!(
19780            "Unknown surface `{}` — expected `admin` or `public`.",
19781            form.surface
19782        )));
19783    }
19784    let target = crate::theme::Theme::objects()
19785        .where_(crate::theme::Theme::id.eq(form.theme_id))
19786        .first(tenant.pool())
19787        .await?
19788        .ok_or(AdminError::NotFound(form.theme_id))?;
19789
19790    // Clear the exclusive flag everywhere else, then set it on the
19791    // picked row. Sequential ORM writes — atomicity isn't critical
19792    // here (worst case a transient request sees zero rows flagged
19793    // and falls through to the static default).
19794    let all_themes: Vec<crate::theme::Theme> =
19795        crate::theme::Theme::objects().fetch(tenant.pool()).await?;
19796    for mut t in all_themes {
19797        let target_id = target.id.get().copied().unwrap_or_default();
19798        let this_id = t.id.get().copied().unwrap_or_default();
19799        if form.surface == "admin" {
19800            t.is_admin_default = this_id == target_id;
19801        } else {
19802            t.is_default = this_id == target_id;
19803        }
19804        t.save(tenant.pool()).await?;
19805    }
19806    // #274 — when the picker submits via fetch() (XHR), return JSON with
19807    // the freshly-rendered CSS + identifying bits so the client can swap
19808    // the `<style data-rcms-theme>` block in place. Detection: either an
19809    // explicit `Accept: application/json` (preferred — modern), or the
19810    // legacy `X-Requested-With: XMLHttpRequest` (kept so older host
19811    // crates that wrap the picker can still light it up). Plain form
19812    // submissions keep the redirect-with-flash behavior so the picker
19813    // degrades gracefully with JS off.
19814    if wants_json_response(&headers) && form.surface == "admin" {
19815        let target_id = target.id.get().copied().unwrap_or_default();
19816        let brand_colors: Vec<crate::theme::BrandColor> = crate::theme::BrandColor::objects()
19817            .where_(crate::theme::BrandColor::theme_id.eq(target_id))
19818            .order_by(&[("sort_order", false)])
19819            .fetch(tenant.pool())
19820            .await
19821            .unwrap_or_default();
19822        let css = crate::theme::emit_css(&target, &brand_colors);
19823        return Ok(Json(serde_json::json!({
19824            "ok": true,
19825            "id": target_id,
19826            "slug": target.slug,
19827            "name": target.name,
19828            "default_mode": target.default_mode,
19829            "css": css,
19830            "message": format!("Admin theme switched to “{}”.", target.name),
19831        }))
19832        .into_response());
19833    }
19834    // #174 — admin picker redirects back to Preferences (its new
19835    // home); the legacy `public` surface still redirects to Settings
19836    // so host integrations that POST manually keep their UX.
19837    let redirect_target = if form.surface == "admin" {
19838        "rcms-admin:account"
19839    } else {
19840        "rcms-admin:settings"
19841    };
19842    let theme_flash = if form.surface == "admin" {
19843        "Admin theme switched to “{name}”."
19844    } else {
19845        "Public theme switched to “{name}”."
19846    };
19847    redirect_named_with_message_args(
19848        redirect_target,
19849        MsgLevel::Success,
19850        theme_flash,
19851        &[("name", target.name.as_str())],
19852        &headers,
19853    )
19854}
19855
19856/// True when the request prefers a JSON response — either set
19857/// `Accept: application/json` (modern fetch with `Accept` header) or
19858/// the legacy `X-Requested-With: XMLHttpRequest` marker. Used by the
19859/// theme picker so it can opt into a live-swap JSON payload
19860/// without losing the no-JS redirect fallback.
19861fn wants_json_response(headers: &HeaderMap) -> bool {
19862    let accept = headers
19863        .get(header::ACCEPT)
19864        .and_then(|v| v.to_str().ok())
19865        .unwrap_or("");
19866    if accept.contains("application/json") {
19867        return true;
19868    }
19869    headers
19870        .get("x-requested-with")
19871        .and_then(|v| v.to_str().ok())
19872        .is_some_and(|v| v.eq_ignore_ascii_case("XMLHttpRequest"))
19873}
19874
19875// =====================================================================
19876// Redirects tab — editor-managed 301/302 maps. Backed by
19877// crate::redirect::Redirect; the public router consults this table
19878// when a slug lookup returns None (see crate::router).
19879// =====================================================================
19880
19881#[derive(Debug, Deserialize)]
19882pub struct RedirectForm {
19883    pub from_path: String,
19884    pub to_path: String,
19885    /// Checkbox — present when ticked, absent when not. `Some(_)` →
19886    /// 301 Moved Permanently. Default checked in the form template.
19887    #[serde(default)]
19888    pub is_permanent: Option<String>,
19889    #[serde(default)]
19890    pub note: Option<String>,
19891    /// Checkbox: serve even when a published page exists at
19892    /// `from_path`.
19893    #[serde(default)]
19894    pub overrides_live: Option<String>,
19895    /// Chooser hidden inputs; empty string when cleared.
19896    #[serde(default)]
19897    pub from_page_id: Option<String>,
19898    #[serde(default)]
19899    pub to_page_id: Option<String>,
19900}
19901
19902impl RedirectForm {
19903    fn parsed_permanent(&self) -> bool {
19904        self.is_permanent.is_some()
19905    }
19906    fn parsed_overrides_live(&self) -> bool {
19907        self.overrides_live.is_some()
19908    }
19909    fn parsed_page_id(raw: &Option<String>) -> Option<i64> {
19910        raw.as_deref()
19911            .and_then(|s| s.trim().parse::<i64>().ok())
19912            .filter(|id| *id > 0)
19913    }
19914    fn parsed_from_page_id(&self) -> Option<i64> {
19915        Self::parsed_page_id(&self.from_page_id)
19916    }
19917    fn parsed_to_page_id(&self) -> Option<i64> {
19918        Self::parsed_page_id(&self.to_page_id)
19919    }
19920}
19921
19922/// Resolve the effective from/to paths for a redirect form:
19923/// a picked source page snapshots its CURRENT `url_path` into
19924/// `from_path`; a picked destination page snapshots into `to_path`
19925/// (display/fallback — the serve path re-resolves it live). Returns
19926/// `(from_path, to_path)`; typed values pass through when no page is
19927/// picked.
19928async fn redirect_form_paths(
19929    pool: &rustango::sql::Pool,
19930    form: &RedirectForm,
19931) -> Result<(String, String), AdminError> {
19932    let mut from = form.from_path.trim().to_owned();
19933    let mut to = form.to_path.trim().to_owned();
19934    if let Some(pid) = form.parsed_from_page_id() {
19935        if let Some(p) = Page::objects().where_(Page::id.eq(pid)).first(pool).await? {
19936            from = p.url_path;
19937        }
19938    }
19939    if let Some(pid) = form.parsed_to_page_id() {
19940        if let Some(p) = Page::objects().where_(Page::id.eq(pid)).first(pool).await? {
19941            to = p.url_path;
19942        }
19943    }
19944    Ok((from, to))
19945}
19946
19947/// Save-time shadow check: a non-override rule whose
19948/// `from_path` matches a PUBLISHED page will never serve (live pages
19949/// win). Returns `true` when shadowed so the submit handlers can
19950/// flash a warning instead of a plain success.
19951async fn redirect_is_shadowed(tenant: &Tenant, from_path: &str, overrides_live: bool) -> bool {
19952    if overrides_live || crate::redirect::is_wildcard(from_path) {
19953        // Wildcards are meant to span subtrees (which may include live
19954        // pages); "shadow" only applies to exact non-override rules.
19955        return false;
19956    }
19957    matches!(
19958        crate::resolver::resolve_path(tenant, from_path).await,
19959        Ok(Some(_))
19960    )
19961}
19962
19963/// Reject a `from_path` with more than one `*`; a single glob
19964/// (typically `path/*` or `*/path`) is the supported shape. Also reject a
19965/// rule whose destination matches its own from-path.
19966fn redirect_pattern_error(from_path: &str, to_path: &str) -> Option<&'static str> {
19967    if from_path.matches('*').count() > 1 {
19968        Some("The from-path may contain at most one “*” wildcard (e.g. /old/* or */feed).")
19969    } else if crate::redirect::redirect_loops(from_path, to_path) {
19970        Some("That redirect points back at its own from-path, so visitors would loop.")
19971    } else {
19972        None
19973    }
19974}
19975
19976/// Query for the redirect list: free-text search, status filter chip,
19977/// sortable column + direction, and page number.
19978#[derive(Debug, Deserialize, Default)]
19979pub struct RedirectListQuery {
19980    #[serde(default)]
19981    pub q: Option<String>,
19982    /// `all` | `active` | `disabled` | `stale`.
19983    #[serde(default)]
19984    pub filter: Option<String>,
19985    /// `from` | `last_used` | `created` | `hits` | `staleness`.
19986    #[serde(default)]
19987    pub sort: Option<String>,
19988    /// `asc` | `desc`.
19989    #[serde(default)]
19990    pub dir: Option<String>,
19991    #[serde(default)]
19992    pub page: Option<i64>,
19993}
19994
19995const REDIRECTS_PER_PAGE: usize = 50;
19996
19997pub async fn redirect_list(
19998    State(state): State<super::AdminState>,
19999    tenant: Tenant,
20000    headers: HeaderMap,
20001    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
20002    Query(q): Query<RedirectListQuery>,
20003) -> Result<Response, AdminError> {
20004    // The redirect table is small (editor-managed), so search / sort /
20005    // paginate happen in-memory over one fetch — same result as
20006    // SQL LIMIT/OFFSET without threading dialect-specific ordering.
20007    let mut all: Vec<crate::redirect::Redirect> = crate::redirect::Redirect::objects()
20008        .fetch(tenant.pool())
20009        .await?;
20010    let now = chrono::Utc::now();
20011
20012    let needle = q.q.as_deref().unwrap_or("").trim().to_lowercase();
20013    if !needle.is_empty() {
20014        all.retain(|r| {
20015            r.from_path.to_lowercase().contains(&needle)
20016                || r.to_path.to_lowercase().contains(&needle)
20017                || r.note.to_lowercase().contains(&needle)
20018        });
20019    }
20020
20021    // Chip counts reflect the search-filtered set (before the status filter).
20022    let count_all = all.len();
20023    let count_active = all.iter().filter(|r| r.is_active).count();
20024    let count_disabled = all.iter().filter(|r| !r.is_active).count();
20025    let count_stale = all
20026        .iter()
20027        .filter(|r| matches!(crate::redirect::staleness(r, now), "stale" | "unused"))
20028        .count();
20029
20030    let filter = q.filter.as_deref().unwrap_or("all");
20031    all.retain(|r| match filter {
20032        "active" => r.is_active,
20033        "disabled" => !r.is_active,
20034        "stale" => matches!(crate::redirect::staleness(r, now), "stale" | "unused"),
20035        _ => true,
20036    });
20037
20038    let sort = q.sort.as_deref().unwrap_or("from");
20039    let desc = q.dir.as_deref() == Some("desc");
20040    all.sort_by(|a, b| {
20041        let o = match sort {
20042            "last_used" => a.last_hit_at.cmp(&b.last_hit_at),
20043            "created" => a.created_at.get().cmp(&b.created_at.get()),
20044            "hits" => a.hit_count.cmp(&b.hit_count),
20045            "staleness" => {
20046                let rank = |r: &crate::redirect::Redirect| match crate::redirect::staleness(r, now)
20047                {
20048                    "disabled" => 0u8,
20049                    "unused" => 1,
20050                    "stale" => 2,
20051                    _ => 3,
20052                };
20053                rank(a).cmp(&rank(b))
20054            }
20055            _ => a.from_path.cmp(&b.from_path),
20056        };
20057        if desc {
20058            o.reverse()
20059        } else {
20060            o
20061        }
20062    });
20063
20064    let total = all.len();
20065    let total_pages = total.div_ceil(REDIRECTS_PER_PAGE).max(1);
20066    let page = q.page.unwrap_or(1).clamp(1, total_pages as i64) as usize;
20067    let start = (page - 1) * REDIRECTS_PER_PAGE;
20068    let items: Vec<crate::redirect::Redirect> = all
20069        .into_iter()
20070        .skip(start)
20071        .take(REDIRECTS_PER_PAGE)
20072        .collect();
20073
20074    let mut ctx = Context::new();
20075    add_chrome(&mut ctx, &tenant, "redirects", session_user.as_ref()).await;
20076    add_admin_theme(&mut ctx, tenant.pool()).await;
20077    ctx.insert("items", &items);
20078    ctx.insert("q", &needle);
20079    ctx.insert("filter", filter);
20080    ctx.insert("sort", sort);
20081    ctx.insert("dir", if desc { "desc" } else { "asc" });
20082    ctx.insert("current_page", &page);
20083    ctx.insert("total_pages", &total_pages);
20084    ctx.insert("total", &total);
20085    ctx.insert("count_all", &count_all);
20086    ctx.insert("count_active", &count_active);
20087    ctx.insert("count_disabled", &count_disabled);
20088    ctx.insert("count_stale", &count_stale);
20089    render_with_csrf(&state, &headers, "rcms_admin/redirect_list.html", &mut ctx)
20090}
20091
20092pub async fn redirect_new_form(
20093    State(state): State<super::AdminState>,
20094    tenant: Tenant,
20095    headers: HeaderMap,
20096    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
20097) -> Result<Response, AdminError> {
20098    let mut ctx = Context::new();
20099    add_chrome(&mut ctx, &tenant, "redirects", session_user.as_ref()).await;
20100    add_admin_theme(&mut ctx, tenant.pool()).await;
20101    ctx.insert("mode", "new");
20102    ctx.insert(
20103        "redirect",
20104        &serde_json::json!({
20105            "from_path": "",
20106            "to_path": "",
20107            "is_permanent": true,
20108            "note": "",
20109            "hit_count": 0,
20110            "overrides_live": false,
20111            "from_page_id": null,
20112            "to_page_id": null,
20113        }),
20114    );
20115    render_with_csrf(&state, &headers, "rcms_admin/redirect_form.html", &mut ctx)
20116}
20117
20118pub async fn redirect_new_submit(
20119    State(_state): State<super::AdminState>,
20120    tenant: Tenant,
20121    headers: HeaderMap,
20122    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
20123    Form(form): Form<RedirectForm>,
20124) -> Result<Response, AdminError> {
20125    use rustango::sql::Auto;
20126    let (from, to) = redirect_form_paths(tenant.pool(), &form).await?;
20127    if from.is_empty() || to.is_empty() {
20128        return redirect_named_with_message(
20129            "rcms-admin:redirects:list",
20130            MsgLevel::Error,
20131            "From-path and to-path are both required.",
20132            &headers,
20133        );
20134    }
20135    if let Some(msg) = redirect_pattern_error(&from, &to) {
20136        return redirect_named_with_message(
20137            "rcms-admin:redirects:list",
20138            MsgLevel::Error,
20139            msg,
20140            &headers,
20141        );
20142    }
20143    let overrides_live = form.parsed_overrides_live();
20144    let is_permanent = form.parsed_permanent();
20145    let from_page_id = form.parsed_from_page_id();
20146    let to_page_id = form.parsed_to_page_id();
20147    let mut row = crate::redirect::Redirect {
20148        id: Auto::Unset,
20149        from_path: from,
20150        to_path: to,
20151        is_permanent,
20152        note: form.note.unwrap_or_default().trim().to_owned(),
20153        hit_count: 0,
20154        overrides_live,
20155        from_page_id,
20156        to_page_id,
20157        is_active: true,
20158        disabled_reason: String::new(),
20159        last_hit_at: None,
20160        created_at: Auto::Unset,
20161        updated_at: Auto::Unset,
20162    };
20163    row.insert(tenant.pool()).await?;
20164    redirect_save_response(&tenant, &row, overrides_live, true, &headers).await
20165}
20166
20167/// Shared post-save flash for redirect create/edit: a strong warning
20168/// for a wildcard override (it can shadow many live pages), a warning
20169/// for an exact non-override rule shadowed by a live page, else
20170/// success. `is_new` picks the "Added…" vs "Saved…" wording so every
20171/// message stays a single fully-localizable sentence.
20172async fn redirect_save_response(
20173    tenant: &Tenant,
20174    row: &crate::redirect::Redirect,
20175    overrides_live: bool,
20176    is_new: bool,
20177    headers: &HeaderMap,
20178) -> Result<Response, AdminError> {
20179    let args = &[
20180        ("from", row.from_path.as_str()),
20181        ("to", row.to_path.as_str()),
20182    ];
20183    if overrides_live && crate::redirect::is_wildcard(&row.from_path) {
20184        let key = if is_new {
20185            "Added redirect {from} → {to} — heads up: a wildcard override can shadow many live pages under this pattern. Double-check the pattern."
20186        } else {
20187            "Saved redirect {from} → {to} — heads up: a wildcard override can shadow many live pages under this pattern. Double-check the pattern."
20188        };
20189        return redirect_named_with_message_args(
20190            "rcms-admin:redirects:list",
20191            MsgLevel::Warning,
20192            key,
20193            args,
20194            headers,
20195        );
20196    }
20197    if redirect_is_shadowed(tenant, &row.from_path, overrides_live).await {
20198        let key = if is_new {
20199            "Added redirect {from} → {to} — but a published page exists at {from}, so it won't serve until that page is unpublished (or tick “Apply even when a published page exists”)."
20200        } else {
20201            "Saved redirect {from} → {to} — but a published page exists at {from}, so it won't serve until that page is unpublished (or tick “Apply even when a published page exists”)."
20202        };
20203        return redirect_named_with_message_args(
20204            "rcms-admin:redirects:list",
20205            MsgLevel::Warning,
20206            key,
20207            args,
20208            headers,
20209        );
20210    }
20211    let key = if is_new {
20212        "Added redirect {from} → {to}."
20213    } else {
20214        "Saved redirect {from} → {to}."
20215    };
20216    redirect_named_with_message_args(
20217        "rcms-admin:redirects:list",
20218        MsgLevel::Success,
20219        key,
20220        args,
20221        headers,
20222    )
20223}
20224
20225// ----- #186 — snippet CSV import (bulk migration) ---
20226
20227/// One row from the snippet CSV / TSV. Mirrors the cms_snippet shape:
20228/// required slug + title, optional body_markdown + folder_path + a
20229/// flat `data` map (any extra column → data.<column_name>).
20230#[derive(Debug)]
20231struct SnippetImportRow {
20232    slug: String,
20233    title: String,
20234    body_markdown: String,
20235    folder_path: String,
20236    data: serde_json::Map<String, serde_json::Value>,
20237}
20238
20239fn parse_snippet_csv(text: &str) -> Vec<SnippetImportRow> {
20240    // Header is required (we need to know what column is what).
20241    // Auto-detect TSV when tabs are present.
20242    let delimiter = if text.contains('\t') { '\t' } else { ',' };
20243    let mut lines = text.lines();
20244    let header = match lines.next() {
20245        Some(h) => h,
20246        None => return Vec::new(),
20247    };
20248    let cols: Vec<String> = header
20249        .split(delimiter)
20250        .map(|s| s.trim().to_ascii_lowercase())
20251        .collect();
20252    // Need at least slug + title.
20253    let slug_idx = cols.iter().position(|c| c == "slug" || c == "key");
20254    let title_idx = cols.iter().position(|c| c == "title" || c == "name");
20255    let (Some(slug_idx), Some(title_idx)) = (slug_idx, title_idx) else {
20256        return Vec::new();
20257    };
20258    let body_idx = cols
20259        .iter()
20260        .position(|c| c == "body_markdown" || c == "body" || c == "content");
20261    let folder_idx = cols
20262        .iter()
20263        .position(|c| c == "folder_path" || c == "folder" || c == "path");
20264    let mut out = Vec::new();
20265    for raw in lines {
20266        let trimmed = raw.trim();
20267        if trimmed.is_empty() {
20268            continue;
20269        }
20270        let parts: Vec<&str> = trimmed.split(delimiter).map(str::trim).collect();
20271        let slug = parts.get(slug_idx).copied().unwrap_or("");
20272        let title = parts.get(title_idx).copied().unwrap_or("");
20273        if slug.is_empty() || title.is_empty() {
20274            continue;
20275        }
20276        let body_markdown = body_idx
20277            .and_then(|i| parts.get(i))
20278            .copied()
20279            .unwrap_or("")
20280            .to_owned();
20281        let folder_path = folder_idx
20282            .and_then(|i| parts.get(i))
20283            .copied()
20284            .unwrap_or("")
20285            .to_owned();
20286        // Every other column lands in `data`.
20287        let mut data = serde_json::Map::new();
20288        for (i, col) in cols.iter().enumerate() {
20289            if Some(i) == Some(slug_idx)
20290                || Some(i) == Some(title_idx)
20291                || Some(i) == body_idx
20292                || Some(i) == folder_idx
20293            {
20294                continue;
20295            }
20296            if col.is_empty() {
20297                continue;
20298            }
20299            let v = parts.get(i).copied().unwrap_or("");
20300            if !v.is_empty() {
20301                data.insert(col.clone(), serde_json::Value::String(v.to_owned()));
20302            }
20303        }
20304        out.push(SnippetImportRow {
20305            slug: slug.to_owned(),
20306            title: title.to_owned(),
20307            body_markdown,
20308            folder_path: crate::snippet::normalize_folder(&folder_path),
20309            data,
20310        });
20311    }
20312    out
20313}
20314
20315/// GET /cms-admin/library/{type_name}/import — show upload form.
20316pub async fn snippet_import_form(
20317    State(state): State<super::AdminState>,
20318    tenant: Tenant,
20319    headers: HeaderMap,
20320    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
20321    Path(type_name): Path<String>,
20322) -> Result<Response, AdminError> {
20323    let mut ctx = Context::new();
20324    add_chrome(&mut ctx, &tenant, "library", session_user.as_ref()).await;
20325    add_admin_theme(&mut ctx, tenant.pool()).await;
20326    ctx.insert("type_name", &type_name);
20327    render_with_csrf(&state, &headers, "rcms_admin/snippet_import.html", &mut ctx)
20328}
20329
20330/// POST /cms-admin/library/{type_name}/import — bulk import snippets
20331/// for one library type from CSV / TSV.
20332pub async fn snippet_import_submit(
20333    State(_state): State<super::AdminState>,
20334    tenant: Tenant,
20335    headers: HeaderMap,
20336    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
20337    Path(type_name): Path<String>,
20338    mut multipart: axum::extract::Multipart,
20339) -> Result<Response, AdminError> {
20340    use rustango::sql::Auto;
20341    let mut bytes: Vec<u8> = Vec::new();
20342    let mut filename = String::new();
20343    while let Some(field) = multipart
20344        .next_field()
20345        .await
20346        .map_err(|e| AdminError::Upload(format!("multipart parse: {e}")))?
20347    {
20348        if field.name().unwrap_or("") == "file" {
20349            if let Some(name) = field.file_name() {
20350                filename = name.to_owned();
20351            }
20352            bytes = field
20353                .bytes()
20354                .await
20355                .map_err(|e| AdminError::Upload(format!("read bytes: {e}")))?
20356                .to_vec();
20357        } else {
20358            let _ = field.bytes().await;
20359        }
20360    }
20361    if bytes.is_empty() {
20362        return redirect_named_with_message(
20363            "rcms-admin:library:list",
20364            MsgLevel::Error,
20365            "No file uploaded.",
20366            &headers,
20367        );
20368    }
20369    let text = String::from_utf8_lossy(&bytes);
20370    let rows = parse_snippet_csv(&text);
20371    let total = rows.len();
20372    if total == 0 {
20373        return redirect_named_with_message(
20374            "rcms-admin:library:list",
20375            MsgLevel::Error,
20376            "Imported 0 snippets — CSV must have a header row with `slug` + `title` columns.",
20377            &headers,
20378        );
20379    }
20380    let mut inserted = 0usize;
20381    let mut skipped = 0usize;
20382    let _ = filename; // captured for the note below
20383    for row in rows {
20384        let mut snippet = crate::snippet::Snippet {
20385            id: Auto::Unset,
20386            type_name: type_name.clone(),
20387            folder_path: row.folder_path,
20388            slug: row.slug,
20389            title: row.title,
20390            body_markdown: row.body_markdown,
20391            data: serde_json::Value::Object(row.data),
20392            created_at: Auto::Unset,
20393            updated_at: Auto::Unset,
20394        };
20395        match snippet.insert(tenant.pool()).await {
20396            Ok(_) => inserted += 1,
20397            Err(_) => skipped += 1,
20398        }
20399    }
20400    let inserted_str = inserted.to_string();
20401    let total_str = total.to_string();
20402    let skipped_str = skipped.to_string();
20403    redirect_named_with_message_args(
20404        "rcms-admin:library:list",
20405        MsgLevel::Success,
20406        "Imported {inserted}/{total} snippets ({skipped} skipped — likely duplicate slugs).",
20407        &[
20408            ("inserted", inserted_str.as_str()),
20409            ("total", total_str.as_str()),
20410            ("skipped", skipped_str.as_str()),
20411        ],
20412        &headers,
20413    )
20414}
20415
20416/// GET /cms-admin/redirects/import — show the upload form.
20417pub async fn redirect_import_form(
20418    State(state): State<super::AdminState>,
20419    tenant: Tenant,
20420    headers: HeaderMap,
20421    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
20422) -> Result<Response, AdminError> {
20423    let mut ctx = Context::new();
20424    add_chrome(&mut ctx, &tenant, "redirects", session_user.as_ref()).await;
20425    add_admin_theme(&mut ctx, tenant.pool()).await;
20426    render_with_csrf(
20427        &state,
20428        &headers,
20429        "rcms_admin/redirect_import.html",
20430        &mut ctx,
20431    )
20432}
20433
20434/// Parsed shape of one row from the CSV / TSV upload. Either two
20435/// or three fields per row: `old_path`, `new_path`, optional
20436/// `is_permanent` (`true` / `false`, or `301` / `302`).
20437#[derive(Debug)]
20438struct RedirectImportRow {
20439    from_path: String,
20440    to_path: String,
20441    is_permanent: bool,
20442}
20443
20444fn parse_redirect_csv(text: &str) -> Vec<RedirectImportRow> {
20445    // Best-effort CSV / TSV. Doesn't handle quoted commas inside
20446    // values (RFC-4180 strict) — redirects are URL paths, no
20447    // commas in them. TSV detection: if any line contains a tab,
20448    // use tab as the delimiter; otherwise comma.
20449    let delimiter = if text.contains('\t') { '\t' } else { ',' };
20450    let mut out = Vec::new();
20451    for (lineno, raw) in text.lines().enumerate() {
20452        let trimmed = raw.trim();
20453        if trimmed.is_empty() {
20454            continue;
20455        }
20456        let parts: Vec<&str> = trimmed.split(delimiter).map(str::trim).collect();
20457        // Header row: if the first row's first two cells are exactly
20458        // `from_path` / `to_path` (case-insensitive), skip.
20459        if lineno == 0 {
20460            let h0 = parts.first().copied().unwrap_or("").to_ascii_lowercase();
20461            if h0 == "from_path" || h0 == "from" || h0 == "old" || h0 == "source" {
20462                continue;
20463            }
20464        }
20465        if parts.len() < 2 {
20466            continue;
20467        }
20468        let from = parts[0];
20469        let to = parts[1];
20470        if from.is_empty() || to.is_empty() {
20471            continue;
20472        }
20473        let is_permanent = parts
20474            .get(2)
20475            .map(|s| {
20476                let v = s.to_ascii_lowercase();
20477                !matches!(v.as_str(), "false" | "0" | "302" | "no")
20478            })
20479            .unwrap_or(true);
20480        out.push(RedirectImportRow {
20481            from_path: from.to_owned(),
20482            to_path: to.to_owned(),
20483            is_permanent,
20484        });
20485    }
20486    out
20487}
20488
20489/// Serialize redirects to CSV: a header row + `from_path,to_path,
20490/// is_permanent`, with `is_permanent` rendered as `301`/`302` so the
20491/// importer ([`parse_redirect_csv`]) round-trips an export.
20492fn redirects_csv(items: &[crate::redirect::Redirect]) -> String {
20493    let mut out = String::from("from_path,to_path,is_permanent\n");
20494    for r in items {
20495        out.push_str(&csv_escape(&r.from_path));
20496        out.push(',');
20497        out.push_str(&csv_escape(&r.to_path));
20498        out.push(',');
20499        out.push_str(if r.is_permanent { "301" } else { "302" });
20500        out.push('\n');
20501    }
20502    out
20503}
20504
20505/// GET /cms-admin/redirects/export.csv — download all redirects as a
20506/// CSV the importer can round-trip.
20507pub async fn redirect_export_csv(
20508    State(_state): State<super::AdminState>,
20509    tenant: Tenant,
20510    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
20511) -> Result<Response, AdminError> {
20512    let items: Vec<crate::redirect::Redirect> = crate::redirect::Redirect::objects()
20513        .order_by(&[("from_path", false)])
20514        .fetch(tenant.pool())
20515        .await?;
20516    let body = redirects_csv(&items);
20517    let filename = format!("redirects-{}.csv", chrono::Utc::now().format("%Y%m%d"));
20518    let mut response = ([(header::CONTENT_TYPE, "text/csv; charset=utf-8")], body).into_response();
20519    if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{filename}\"")) {
20520        response
20521            .headers_mut()
20522            .insert(header::CONTENT_DISPOSITION, v);
20523    }
20524    Ok(response)
20525}
20526
20527#[cfg(test)]
20528mod user_email_column_tests {
20529    use super::user_email;
20530
20531    fn user(email: Option<&str>, data: serde_json::Value) -> rustango::tenancy::auth::User {
20532        rustango::tenancy::auth::User {
20533            id: rustango::sql::Auto::Set(1),
20534            username: "u".into(),
20535            password_hash: String::new(),
20536            email: email.map(ToOwned::to_owned),
20537            is_superuser: false,
20538            active: true,
20539            created_at: chrono::Utc::now(),
20540            data,
20541            password_changed_at: None,
20542            sessions_revoked_at: None,
20543        }
20544    }
20545
20546    #[test]
20547    fn column_first_then_legacy_data_bag() {
20548        // A member signed up on the site: the column only.
20549        assert_eq!(user_email(&user(Some("a@x.example"), serde_json::json!({}))), "a@x.example");
20550        // An admin-made user from before: the data bag only.
20551        assert_eq!(user_email(&user(None, serde_json::json!({"email": "b@x.example"}))), "b@x.example");
20552        assert_eq!(
20553            user_email(&user(Some("a@x.example"), serde_json::json!({"email": "old@x.example"}))),
20554            "a@x.example"
20555        );
20556        assert_eq!(user_email(&user(Some("  "), serde_json::json!({}))), "");
20557    }
20558}
20559
20560#[cfg(test)]
20561mod translation_canonical_html_tests {
20562    use super::translation_canonical_html;
20563
20564    #[test]
20565    fn rich_text_is_sanitized_html_other_kinds_empty() {
20566        let html = translation_canonical_html("richtext", "<p>A jar</p><script>x()</script>");
20567        assert_eq!(html, "<p>A jar</p>");
20568        assert_eq!(translation_canonical_html("richtext", "  "), "");
20569        assert_eq!(translation_canonical_html("textarea", "<p>A jar</p>"), "");
20570        assert_eq!(translation_canonical_html("text", "Moon jar"), "");
20571    }
20572}
20573
20574#[cfg(test)]
20575mod user_email_tests {
20576    use super::validate_optional_email;
20577
20578    #[test]
20579    fn accepts_valid_and_empty() {
20580        assert_eq!(validate_optional_email(Some("a@b.com")).unwrap(), "a@b.com");
20581        assert_eq!(
20582            validate_optional_email(Some("  a@b.com ")).unwrap(),
20583            "a@b.com"
20584        ); // trimmed
20585        assert_eq!(validate_optional_email(None).unwrap(), ""); // optional
20586        assert_eq!(validate_optional_email(Some("   ")).unwrap(), ""); // blank → empty
20587    }
20588
20589    #[test]
20590    fn rejects_malformed() {
20591        assert!(validate_optional_email(Some("nope")).is_err()); // no @
20592        assert!(validate_optional_email(Some("a@b@c")).is_err()); // two @
20593        assert!(validate_optional_email(Some("@b.com")).is_err()); // empty local
20594        assert!(validate_optional_email(Some("a@")).is_err()); // empty domain
20595        assert!(validate_optional_email(Some("a b@c.com")).is_err()); // whitespace
20596    }
20597}
20598
20599#[cfg(test)]
20600mod copy_to_locale_tests {
20601    use super::copy_translatable_fields;
20602
20603    #[test]
20604    fn selects_nonempty_canonical_fields() {
20605        let out = copy_translatable_fields("Home", "", "  Welcome  ");
20606        // `seo_title` empty → skipped; whitespace-only would be too.
20607        assert_eq!(
20608            out,
20609            vec![
20610                ("title", "Home".to_owned()),
20611                ("seo_description", "  Welcome  ".to_owned()),
20612            ]
20613        );
20614    }
20615
20616    #[test]
20617    fn all_empty_yields_nothing_to_seed() {
20618        assert!(copy_translatable_fields("", "   ", "").is_empty());
20619    }
20620}
20621
20622#[cfg(test)]
20623mod redirect_csv_tests {
20624    use super::*;
20625    use rustango::sql::Auto;
20626
20627    fn row(from: &str, to: &str, permanent: bool) -> crate::redirect::Redirect {
20628        crate::redirect::Redirect {
20629            id: Auto::Unset,
20630            from_path: from.to_owned(),
20631            to_path: to.to_owned(),
20632            is_permanent: permanent,
20633            note: String::new(),
20634            hit_count: 0,
20635            overrides_live: false,
20636            from_page_id: None,
20637            to_page_id: None,
20638            is_active: true,
20639            disabled_reason: String::new(),
20640            last_hit_at: None,
20641            created_at: Auto::Unset,
20642            updated_at: Auto::Unset,
20643        }
20644    }
20645
20646    #[test]
20647    fn redirects_csv_header_and_301_302_mapping() {
20648        let csv = redirects_csv(&[row("/old", "/new", true), row("/tmp", "/dst", false)]);
20649        let mut lines = csv.lines();
20650        assert_eq!(lines.next(), Some("from_path,to_path,is_permanent"));
20651        assert_eq!(lines.next(), Some("/old,/new,301"));
20652        assert_eq!(lines.next(), Some("/tmp,/dst,302"));
20653        assert_eq!(lines.next(), None);
20654    }
20655
20656    #[test]
20657    fn redirects_csv_empty_is_header_only() {
20658        assert_eq!(redirects_csv(&[]), "from_path,to_path,is_permanent\n");
20659    }
20660}
20661
20662/// POST /cms-admin/redirects/import — accepts a multipart upload of
20663/// CSV / TSV; bulk-inserts redirects.
20664pub async fn redirect_import_submit(
20665    State(_state): State<super::AdminState>,
20666    tenant: Tenant,
20667    headers: HeaderMap,
20668    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
20669    mut multipart: axum::extract::Multipart,
20670) -> Result<Response, AdminError> {
20671    use rustango::sql::Auto;
20672    let mut bytes: Vec<u8> = Vec::new();
20673    let mut filename = String::new();
20674    while let Some(field) = multipart
20675        .next_field()
20676        .await
20677        .map_err(|e| AdminError::Upload(format!("multipart parse: {e}")))?
20678    {
20679        if field.name().unwrap_or("") == "file" {
20680            if let Some(name) = field.file_name() {
20681                filename = name.to_owned();
20682            }
20683            bytes = field
20684                .bytes()
20685                .await
20686                .map_err(|e| AdminError::Upload(format!("read bytes: {e}")))?
20687                .to_vec();
20688        } else {
20689            let _ = field.bytes().await;
20690        }
20691    }
20692    if bytes.is_empty() {
20693        return redirect_named_with_message(
20694            "rcms-admin:redirects:list",
20695            MsgLevel::Error,
20696            "No file uploaded.",
20697            &headers,
20698        );
20699    }
20700    let text = String::from_utf8_lossy(&bytes);
20701    let rows = parse_redirect_csv(&text);
20702    let total = rows.len();
20703    let mut inserted = 0usize;
20704    let mut skipped = 0usize;
20705    for row in rows {
20706        if redirect_pattern_error(&row.from_path, &row.to_path).is_some() {
20707            skipped += 1;
20708            continue;
20709        }
20710        let mut redirect = crate::redirect::Redirect {
20711            id: Auto::Unset,
20712            from_path: row.from_path,
20713            to_path: row.to_path,
20714            is_permanent: row.is_permanent,
20715            note: format!("Imported from {filename}"),
20716            hit_count: 0,
20717            overrides_live: false,
20718            from_page_id: None,
20719            to_page_id: None,
20720            is_active: true,
20721            disabled_reason: String::new(),
20722            last_hit_at: None,
20723            created_at: Auto::Unset,
20724            updated_at: Auto::Unset,
20725        };
20726        match redirect.insert(tenant.pool()).await {
20727            Ok(_) => inserted += 1,
20728            Err(_) => skipped += 1,
20729        }
20730    }
20731    let inserted_str = inserted.to_string();
20732    let total_str = total.to_string();
20733    let skipped_str = skipped.to_string();
20734    redirect_named_with_message_args(
20735        "rcms-admin:redirects:list",
20736        MsgLevel::Success,
20737        "Imported {inserted}/{total} redirects ({skipped} skipped — likely duplicates).",
20738        &[
20739            ("inserted", inserted_str.as_str()),
20740            ("total", total_str.as_str()),
20741            ("skipped", skipped_str.as_str()),
20742        ],
20743        &headers,
20744    )
20745}
20746
20747pub async fn redirect_edit_form(
20748    State(state): State<super::AdminState>,
20749    tenant: Tenant,
20750    headers: HeaderMap,
20751    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
20752    Path(id): Path<i64>,
20753) -> Result<Response, AdminError> {
20754    let row = crate::redirect::Redirect::objects()
20755        .where_(crate::redirect::Redirect::id.eq(id))
20756        .first(tenant.pool())
20757        .await?
20758        .ok_or(AdminError::NotFound(id))?;
20759    let mut ctx = Context::new();
20760    add_chrome(&mut ctx, &tenant, "redirects", session_user.as_ref()).await;
20761    add_admin_theme(&mut ctx, tenant.pool()).await;
20762    ctx.insert("mode", "edit");
20763    ctx.insert("redirect", &row);
20764    render_with_csrf(&state, &headers, "rcms_admin/redirect_form.html", &mut ctx)
20765}
20766
20767pub async fn redirect_edit_submit(
20768    State(_state): State<super::AdminState>,
20769    tenant: Tenant,
20770    headers: HeaderMap,
20771    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
20772    Path(id): Path<i64>,
20773    Form(form): Form<RedirectForm>,
20774) -> Result<Response, AdminError> {
20775    let mut row = crate::redirect::Redirect::objects()
20776        .where_(crate::redirect::Redirect::id.eq(id))
20777        .first(tenant.pool())
20778        .await?
20779        .ok_or(AdminError::NotFound(id))?;
20780    let (from, to) = redirect_form_paths(tenant.pool(), &form).await?;
20781    if from.is_empty() || to.is_empty() {
20782        return redirect_named_with_message(
20783            "rcms-admin:redirects:list",
20784            MsgLevel::Error,
20785            "From-path and to-path are both required.",
20786            &headers,
20787        );
20788    }
20789    if let Some(msg) = redirect_pattern_error(&from, &to) {
20790        return redirect_named_with_message(
20791            "rcms-admin:redirects:list",
20792            MsgLevel::Error,
20793            msg,
20794            &headers,
20795        );
20796    }
20797    row.from_path = from;
20798    row.to_path = to;
20799    row.is_permanent = form.parsed_permanent();
20800    row.overrides_live = form.parsed_overrides_live();
20801    row.from_page_id = form.parsed_from_page_id();
20802    row.to_page_id = form.parsed_to_page_id();
20803    row.note = form.note.unwrap_or_default().trim().to_owned();
20804    row.save(tenant.pool()).await?;
20805    let overrides_live = row.overrides_live;
20806    redirect_save_response(&tenant, &row, overrides_live, false, &headers).await
20807}
20808
20809/// POST /cms-admin/redirects/{id}/enable — re-enable a rule that was
20810/// auto-disabled when a linked page was deleted/unpublished.
20811pub async fn redirect_enable_submit(
20812    State(_state): State<super::AdminState>,
20813    tenant: Tenant,
20814    headers: HeaderMap,
20815    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
20816    Path(id): Path<i64>,
20817) -> Result<Response, AdminError> {
20818    let mut row = crate::redirect::Redirect::objects()
20819        .where_(crate::redirect::Redirect::id.eq(id))
20820        .first(tenant.pool())
20821        .await?
20822        .ok_or(AdminError::NotFound(id))?;
20823    row.is_active = true;
20824    row.disabled_reason = String::new();
20825    row.save(tenant.pool()).await?;
20826    redirect_named_with_message_args(
20827        "rcms-admin:redirects:list",
20828        MsgLevel::Success,
20829        "Re-enabled redirect {from} → {to}.",
20830        &[
20831            ("from", row.from_path.as_str()),
20832            ("to", row.to_path.as_str()),
20833        ],
20834        &headers,
20835    )
20836}
20837
20838pub async fn redirect_delete_submit(
20839    State(_state): State<super::AdminState>,
20840    tenant: Tenant,
20841    headers: HeaderMap,
20842    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
20843    Path(id): Path<i64>,
20844) -> Result<Response, AdminError> {
20845    let row = crate::redirect::Redirect::objects()
20846        .where_(crate::redirect::Redirect::id.eq(id))
20847        .first(tenant.pool())
20848        .await?
20849        .ok_or(AdminError::NotFound(id))?;
20850    let label = format!("{} → {}", row.from_path, row.to_path);
20851    row.delete(tenant.pool()).await?;
20852    redirect_named_with_message_args(
20853        "rcms-admin:redirects:list",
20854        MsgLevel::Success,
20855        "Deleted redirect {label}.",
20856        &[("label", label.as_str())],
20857        &headers,
20858    )
20859}
20860
20861// =====================================================================
20862// Helpers (existing)
20863// =====================================================================
20864
20865// ---------- helpers ----------
20866
20867/// `PageType` rows whose handler reports `is_creatable() = true`.
20868/// Falls back to the row's `is_creatable` column when no handler is
20869/// registered (stale row from a removed type).
20870pub(crate) fn creatable_types(all: &[PageType]) -> Vec<PageType> {
20871    all.iter()
20872        .filter(|t| {
20873            find_handler(&t.type_name)
20874                .map(|h| h.is_creatable())
20875                .unwrap_or(t.is_creatable)
20876        })
20877        .cloned()
20878        .collect()
20879}
20880
20881/// `PageType` rows allowed at the ROOT of the tree (no parent).
20882///
20883/// A type that names `allowed_parent_types` is declaring it may only live
20884/// under those parents, so it cannot be a root. Without this the root picker
20885/// offered every creatable type and the save path accepted it, letting you
20886/// create e.g. an `ArticlePage` (parent-restricted to `HomePage`) at the root
20887/// — a tree the type rules forbid. The child case has always been
20888/// gated by [`allowed_children_for`]; this is the missing mirror.
20889pub(crate) fn allowed_root_types(all: &[PageType]) -> Vec<PageType> {
20890    creatable_types(all)
20891        .into_iter()
20892        .filter(|t| t.allowed_parents().is_empty())
20893        .collect()
20894}
20895
20896/// `PageType` rows allowed as direct children of `parent`. Consults
20897/// the parent's handler's `allowed_child_types` AND each candidate's
20898/// `allowed_parent_types`. Skip the check if either whitelist is
20899/// empty.
20900pub(crate) fn allowed_children_for(parent: &Page, all: &[PageType]) -> Vec<PageType> {
20901    let parent_row = all
20902        .iter()
20903        .find(|t| t.id.get().copied() == Some(parent.page_type_id));
20904    let parent_type_name = parent_row.map(|t| t.type_name.clone()).unwrap_or_default();
20905    // Rules come from the rows, so admin-made types count too (#843).
20906    let parent_allowed_children = parent_row.map(PageType::allowed_children).unwrap_or_default();
20907
20908    creatable_types(all)
20909        .into_iter()
20910        .filter(|cand| {
20911            // Parent-side gate: empty list = no restriction.
20912            if !parent_allowed_children.is_empty()
20913                && !parent_allowed_children.iter().any(|t| t == &cand.type_name)
20914            {
20915                return false;
20916            }
20917            // Child-side gate.
20918            let allowed_parents = cand.allowed_parents();
20919            allowed_parents.is_empty() || allowed_parents.iter().any(|p| *p == parent_type_name)
20920        })
20921        .collect()
20922}
20923
20924/// Empty values for a fresh create form — Tera doesn't auto-default
20925/// missing keys, so we pre-populate the field map.
20926fn empty_page_form_values() -> serde_json::Value {
20927    serde_json::json!({
20928        "title": "",
20929        "slug": "",
20930        "page_type_id": 0,
20931        "status": "draft",
20932        "seo_title": "",
20933        "seo_description": "",
20934        "robots_index": true,
20935        "sitemap_priority": 0.5,
20936        "show_in_menus": true,
20937        "go_live_at": serde_json::Value::Null,
20938        "expire_at": serde_json::Value::Null,
20939        "og_title": "",
20940        "og_description": "",
20941        "og_image_media_id": serde_json::Value::Null,
20942        "twitter_card": "summary_large_image",
20943    })
20944}
20945
20946// =====================================================================
20947// Password reset
20948// =====================================================================
20949//
20950// The four screens — request form (GET), request submit (POST),
20951// confirm form (GET, signed-token URL), confirm submit (POST). Mounted
20952// by `admin::public_router` so anonymous visitors can reach them.
20953//
20954// Token model: signed-URL only (no DB table). The signing secret lives
20955// in `AdminState::signing_secret`, loaded once at boot. `PasswordReset`
20956// (rustango::auth_flows) handles issue + verify.
20957//
20958// Email model: `ConsoleMailer` for v1 — the reset URL prints to stdout
20959// + `tracing::info!`. Production deployments swap in `SmtpMailer` by
20960// editing `send_reset_email` below.
20961//
20962// Account-existence non-leak: every reset-request returns the same
20963// "if that account exists, check your email" page regardless of
20964// whether a user was found.
20965
20966/// POST `/cms-admin/logout` — clear every session cookie the host
20967/// might have minted (bare-admin `rustango_admin_session`, tenant
20968/// `rustango_tenant_session`, operator `rustango_op_session`),
20969/// redirect to `/login`. Self-contained so the button works
20970/// regardless of which framework auth flow signed the user in —
20971/// avoids depending on the right cookie name being known here.
20972pub async fn cms_logout_submit(
20973    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
20974    tenant: Result<Tenant, rustango::extractors::TenantRejection>,
20975    request: crate::security_log::LoginRequest,
20976) -> Response {
20977    if let (Some(user), Ok(tenant)) = (session_user, tenant) {
20978        let entry = SecurityEntry::new(crate::security_log::EVENT_LOGOUT, "admin", &request.meta)
20979            .user(user.id.get().copied(), &user.username);
20980        crate::security_log::record(tenant.pool(), &tenant.org.slug, entry).await;
20981    }
20982    let mut resp = Redirect::to("/login").into_response();
20983    // Reset all three cookies (`Max-Age=0` clears, the empty value
20984    // is a fallback for browsers that only honor expiry-by-value).
20985    // SameSite=Lax + HttpOnly match the framework's mint shape.
20986    let cookies = [
20987        "rustango_admin_session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0",
20988        "rustango_tenant_session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0",
20989        "rustango_op_session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0",
20990    ];
20991    for c in cookies {
20992        if let Ok(v) = HeaderValue::from_str(c) {
20993            resp.headers_mut().append(header::SET_COOKIE, v);
20994        }
20995    }
20996    resp
20997}
20998
20999/// GET `/login` — render the CMS-branded login form. Shadows the
21000/// framework's default `/login` GET (which is wired to its own
21001/// embedded Tera + `login.html`). POST `/login` continues to be
21002/// handled by the framework's auth code — its handler validates
21003/// `username`+`password` against `rustango_users` and sets the
21004/// tenant session cookie.
21005/// GET `/cms-admin/no-access` — destination for the `cms_admin.access`
21006/// gate. Reachable while signed in; doesn't require any
21007/// permission. The middleware adds an exception for this path so
21008/// the redirect doesn't loop.
21009pub async fn no_access_page(
21010    State(state): State<super::AdminState>,
21011    headers: HeaderMap,
21012    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
21013    tenant: Tenant,
21014) -> Result<Response, AdminError> {
21015    let mut ctx = Context::new();
21016    add_auth_chrome(&mut ctx, &tenant).await;
21017    render_with_csrf(&state, &headers, "rcms_admin/no_access.html", &mut ctx)
21018}
21019
21020/// GET `/cms-admin/me` — per-user appearance / text-size / accessibility
21021/// preferences. Replaces the sidebar-footer toggles. The
21022/// preferences themselves persist in `localStorage` via the existing
21023/// no-flash boot script + the toggle JS in `_base.html`; this view
21024/// is purely the surface that hosts the same toggle widgets in a
21025/// dedicated page.
21026/// POST /cms-admin/dismissibles/{key} — record dismissal of the
21027/// banner identified by `key` for the current user. Returns 204 No Content on success.
21028pub async fn dismissible_submit(
21029    State(_state): State<super::AdminState>,
21030    tenant: Tenant,
21031    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
21032    Path(key): Path<String>,
21033) -> Result<Response, AdminError> {
21034    let Some(viewer) = session_user.as_ref() else {
21035        return Ok(unauthorized_no_session());
21036    };
21037    let viewer_id = viewer.id.get().copied().unwrap_or_default();
21038    crate::dismissible::dismiss(tenant.pool(), viewer_id, &key).await?;
21039    Ok((axum::http::StatusCode::NO_CONTENT, "").into_response())
21040}
21041
21042/// GET /cms-admin/dashboard — editor home / at-a-glance screen.
21043/// Surfaces count widgets, recent edits,
21044/// items locked by the current user, and pages scheduled to publish
21045/// next.
21046pub async fn dashboard(
21047    State(state): State<super::AdminState>,
21048    tenant: Tenant,
21049    headers: HeaderMap,
21050    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
21051) -> Result<Response, AdminError> {
21052    let pool = tenant.pool();
21053    let viewer_id = session_user.as_ref().and_then(|u| u.id.get().copied());
21054
21055    // ---- counts ----
21056    // Counted in SQL, grouped by status (#763): the dashboard used to load
21057    // every page to count them. `expired` pages have no tile.
21058    let mut count_drafts = 0usize;
21059    let mut count_published = 0usize;
21060    let mut count_scheduled = 0usize;
21061    let mut count_archived = 0usize;
21062    if let Ok(q) = Page::objects()
21063        .values(&["status"])
21064        .annotate("n", rustango::core::aggregates::count_all().into())
21065        .compile()
21066    {
21067        for r in rustango::sql::fetch_aggregate_dict(pool, &q).await.unwrap_or_default() {
21068            let n = usize::try_from(sql_i64(r.get("n")).unwrap_or(0)).unwrap_or(0);
21069            let status = match r.get("status") {
21070                Some(rustango::core::SqlValue::String(s)) => crate::page::PageStatus::parse(s),
21071                _ => None,
21072            };
21073            match status {
21074                Some(crate::page::PageStatus::Draft) => count_drafts = n,
21075                Some(crate::page::PageStatus::Published) => count_published = n,
21076                Some(crate::page::PageStatus::Scheduled) => count_scheduled = n,
21077                Some(crate::page::PageStatus::Archived) => count_archived = n,
21078                Some(crate::page::PageStatus::Expired) | None => {}
21079            }
21080        }
21081    }
21082    let snippet_count = crate::snippet::Snippet::objects().count(pool).await.unwrap_or(0);
21083    let media_images = Media::objects().where_(Media::kind.eq("image".to_owned())).count(pool).await.unwrap_or(0);
21084    let media_docs = Media::objects().where_(Media::kind.ne("image".to_owned())).count(pool).await.unwrap_or(0);
21085
21086    // ---- recent edits (last 10 revisions across all pages) ----
21087    let revs: Vec<crate::revision::Revision> = crate::revision::Revision::objects()
21088        .order_by(&[("created_at", true)]) // desc
21089        .limit(10)
21090        .fetch(pool)
21091        .await
21092        .unwrap_or_default();
21093    // Who made them, by name (one query).
21094    let user_ids: std::collections::BTreeSet<i64> = revs.iter().filter_map(|r| r.created_by).collect();
21095    let usernames: std::collections::HashMap<i64, String> = if user_ids.is_empty() {
21096        std::collections::HashMap::new()
21097    } else {
21098        rustango::tenancy::auth::User::objects()
21099            .where_(rustango::tenancy::auth::User::id.is_in(user_ids.into_iter()))
21100            .fetch(pool)
21101            .await
21102            .unwrap_or_default()
21103            .into_iter()
21104            .filter_map(|u| u.id.get().copied().map(|id| (id, u.username)))
21105            .collect()
21106    };
21107    // Locks and in-progress reviews up front, so the pages every panel
21108    // names come from one lookup of just those ids — not the whole tree.
21109    let locks: Vec<crate::lock::PageLock> = crate::lock::PageLock::objects()
21110        .fetch(pool)
21111        .await
21112        .unwrap_or_default();
21113    let review_states: Vec<crate::workflow::WorkflowState> = crate::workflow::WorkflowState::objects()
21114        .where_(crate::workflow::WorkflowState::status.eq(crate::workflow::WorkflowStatus::InProgress.as_str().to_owned()))
21115        .fetch(pool)
21116        .await
21117        .unwrap_or_default();
21118    let needed: Vec<i64> = revs
21119        .iter()
21120        .map(|r| r.page_id)
21121        .chain(locks.iter().map(|l| l.page_id))
21122        .chain(review_states.iter().map(|st| st.page_id))
21123        .collect::<std::collections::BTreeSet<i64>>()
21124        .into_iter()
21125        .collect();
21126    let mut named_pages: Vec<Page> = Vec::new();
21127    for chunk in needed.chunks(500) {
21128        named_pages.extend(Page::objects().where_(Page::id.is_in(chunk.to_vec())).fetch(pool).await.unwrap_or_default());
21129    }
21130    let page_by_id: std::collections::HashMap<i64, &Page> = named_pages
21131        .iter()
21132        .filter_map(|p| p.id.get().copied().map(|id| (id, p)))
21133        .collect();
21134    let recent_edits: Vec<serde_json::Value> = revs
21135        .iter()
21136        .filter_map(|r| {
21137            let p = page_by_id.get(&r.page_id)?;
21138            Some(serde_json::json!({
21139                "page_id": r.page_id,
21140                "title": p.title,
21141                "url_path": p.url_path,
21142                "sequence": r.sequence,
21143                "created_at": r.created_at.get().copied(),
21144                "created_by": r.created_by.and_then(|id| usernames.get(&id).cloned()),
21145            }))
21146        })
21147        .collect();
21148
21149    // ---- locked by me ----
21150    let now = chrono::Utc::now();
21151    let mine_locked: Vec<serde_json::Value> = locks
21152        .iter()
21153        .filter(|l| !l.is_stale(now))
21154        .filter(|l| Some(l.user_id) == viewer_id)
21155        .filter_map(|l| {
21156            let p = page_by_id.get(&l.page_id)?;
21157            Some(serde_json::json!({
21158                "page_id": l.page_id,
21159                "title": p.title,
21160                "url_path": p.url_path,
21161                "acquired_at": l.acquired_at.get().copied(),
21162            }))
21163        })
21164        .collect();
21165
21166    // ---- waiting for your review ----
21167    // Pages mid-review whose current step belongs to one of the viewer's
21168    // roles (a superuser decides every step). Without this the reviewer
21169    // had no way to know someone was waiting.
21170    let mut review_rows: Vec<serde_json::Value> = Vec::new();
21171    if let Some(viewer) = session_user.as_ref() {
21172        let states = &review_states;
21173        if !states.is_empty() {
21174            let my_roles: std::collections::BTreeSet<i64> = rustango::tenancy::permissions::UserRole::objects()
21175                .where_(rustango::tenancy::permissions::UserRole::user_id.eq(viewer_id.unwrap_or_default()))
21176                .fetch(pool)
21177                .await
21178                .unwrap_or_default()
21179                .into_iter()
21180                .map(|m| m.role_id)
21181                .collect();
21182            let task_ids: Vec<i64> = states.iter().filter_map(|st| st.current_task_id).collect();
21183            let tasks: std::collections::HashMap<i64, crate::workflow::WorkflowTask> = crate::workflow::WorkflowTask::objects()
21184                .where_(crate::workflow::WorkflowTask::id.is_in(task_ids.into_iter()))
21185                .fetch(pool)
21186                .await
21187                .unwrap_or_default()
21188                .into_iter()
21189                .filter_map(|t| t.id.get().copied().map(|id| (id, t)))
21190                .collect();
21191            for st in states {
21192                let Some(task) = st.current_task_id.and_then(|id| tasks.get(&id)) else { continue };
21193                if !viewer.is_superuser && !my_roles.contains(&task.role_id) {
21194                    continue;
21195                }
21196                let Some(p) = page_by_id.get(&st.page_id) else { continue };
21197                review_rows.push(serde_json::json!({
21198                    "page_id": st.page_id,
21199                    "title": p.title,
21200                    "url_path": p.url_path,
21201                    "step": task.name,
21202                    "requested_at": st.requested_at.get().copied(),
21203                }));
21204            }
21205        }
21206    }
21207
21208    // ---- scheduled next ----
21209    // The next five, straight from SQL.
21210    let scheduled: Vec<Page> = Page::objects()
21211        .where_(Page::status.eq(crate::page::PageStatus::Scheduled.as_str().to_owned()))
21212        .where_(Page::go_live_at.gt(now))
21213        .order_by(&[("go_live_at", false), ("id", false)])
21214        .limit(5)
21215        .fetch(pool)
21216        .await
21217        .unwrap_or_default();
21218    let scheduled_rows: Vec<serde_json::Value> = scheduled
21219        .into_iter()
21220        .map(|p| {
21221            serde_json::json!({
21222                "page_id": p.id.get().copied().unwrap_or_default(),
21223                "title": p.title,
21224                "url_path": p.url_path,
21225                "go_live_at": p.go_live_at,
21226            })
21227        })
21228        .collect();
21229
21230    // ---- plugin widgets ----
21231    let plugin_widgets: Vec<serde_json::Value> =
21232        crate::hooks::render_dashboard_widgets(crate::hooks::HookCtx::new(pool, &tenant.org.slug, viewer_id))
21233            .await
21234            .into_iter()
21235            .map(|(w, html)| {
21236                serde_json::json!({
21237                    "key": w.key,
21238                    "label": w.label,
21239                    "icon": w.icon,
21240                    "html": html,
21241                })
21242            })
21243            .collect();
21244
21245    let mut ctx = Context::new();
21246    add_chrome(&mut ctx, &tenant, "dashboard", session_user.as_ref()).await;
21247    add_admin_theme(&mut ctx, tenant.pool()).await;
21248    ctx.insert("review_rows", &review_rows);
21249    ctx.insert("count_drafts", &count_drafts);
21250    ctx.insert("count_published", &count_published);
21251    ctx.insert("count_scheduled", &count_scheduled);
21252    ctx.insert("count_archived", &count_archived);
21253    ctx.insert("count_snippets", &snippet_count);
21254    ctx.insert("count_images", &media_images);
21255    ctx.insert("count_documents", &media_docs);
21256    ctx.insert("recent_edits", &recent_edits);
21257    ctx.insert("mine_locked", &mine_locked);
21258    ctx.insert("scheduled_rows", &scheduled_rows);
21259    ctx.insert("plugin_widgets", &plugin_widgets);
21260    render_with_csrf(&state, &headers, "rcms_admin/dashboard.html", &mut ctx)
21261}
21262
21263/// GET /cms-admin/styleguide — component gallery. Lists every registered block + every widget kind so
21264/// editors + reviewers can see the available palette at a glance.
21265pub async fn styleguide(
21266    State(state): State<super::AdminState>,
21267    tenant: Tenant,
21268    headers: HeaderMap,
21269    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
21270) -> Result<Response, AdminError> {
21271    let mut ctx = Context::new();
21272    add_chrome(&mut ctx, &tenant, "styleguide", session_user.as_ref()).await;
21273    add_admin_theme(&mut ctx, tenant.pool()).await;
21274
21275    // Registered blocks — one row per registration. Author-curated
21276    // sample data lives in the template (the trait surface doesn't
21277    // require blocks to ship examples).
21278    let blocks: Vec<serde_json::Value> = crate::block::registered_blocks()
21279        .map(|b| {
21280            serde_json::json!({
21281                "type_name": b.type_name(),
21282                "verbose_name": b.verbose_name(),
21283                "icon": b.icon(),
21284                "group": b.group(),
21285                "field_count": b.fields().len(),
21286            })
21287        })
21288        .collect();
21289    ctx.insert("blocks", &blocks);
21290
21291    // Registered page types — second registry editors care about.
21292    let page_types: Vec<serde_json::Value> = crate::page_type::registered_handlers()
21293        .map(|h| {
21294            serde_json::json!({
21295                "type_name": h.type_name(),
21296                "verbose_name": h.verbose_name(),
21297                "icon": h.icon(),
21298                "description": h.description(),
21299            })
21300        })
21301        .collect();
21302    ctx.insert("page_types", &page_types);
21303
21304    // Library types.
21305    let library_types: Vec<serde_json::Value> = crate::library::registered_handlers()
21306        .map(|h| {
21307            serde_json::json!({
21308                "type_name": h.type_name(),
21309                "verbose_name": h.verbose_name(),
21310            })
21311        })
21312        .collect();
21313    ctx.insert("library_types", &library_types);
21314
21315    render_with_csrf(&state, &headers, "rcms_admin/styleguide.html", &mut ctx)
21316}
21317
21318pub async fn account_preferences(
21319    State(state): State<super::AdminState>,
21320    tenant: Tenant,
21321    headers: HeaderMap,
21322    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
21323) -> Result<Response, AdminError> {
21324    render_account_page(&state, &tenant, &headers, session_user.as_ref(), None).await
21325}
21326
21327/// Serialize a user's MCP keys (+ per-key skill scope) and the tenant's
21328/// skill catalog for the key-management cards.
21329async fn mcp_keys_ctx(
21330    pool: &rustango::sql::Pool,
21331    owner_id: i64,
21332) -> (Vec<serde_json::Value>, Vec<serde_json::Value>) {
21333    use rustango::tenancy::{AgentGrant, AgentSkill};
21334
21335    let keys = rustango::tenancy::list_user_keys_pool(pool, owner_id)
21336        .await
21337        .unwrap_or_default();
21338    let skills: Vec<AgentSkill> = rustango::tenancy::list_skills_pool(pool)
21339        .await
21340        .unwrap_or_default();
21341    let skill_name = |sid: i64| -> Option<String> {
21342        skills
21343            .iter()
21344            .find(|s| s.id.get().copied() == Some(sid))
21345            .map(|s| s.codename.clone())
21346    };
21347    // Every key's grants in one query (#630), not one per key.
21348    let key_ids: Vec<i64> = keys.iter().filter_map(|k| k.id.get().copied()).collect();
21349    let mut grants_by_key: std::collections::HashMap<i64, Vec<i64>> = std::collections::HashMap::new();
21350    if !key_ids.is_empty() {
21351        let grants: Vec<AgentGrant> = AgentGrant::objects()
21352            .where_(AgentGrant::agent_id.is_in(key_ids))
21353            .fetch(pool)
21354            .await
21355            .unwrap_or_default();
21356        for g in grants {
21357            grants_by_key.entry(g.agent_id).or_default().push(g.skill_id);
21358        }
21359    }
21360    let mut rows = Vec::with_capacity(keys.len());
21361    for key in &keys {
21362        let key_id = key.id.get().copied().unwrap_or_default();
21363        let scope: Vec<String> = grants_by_key
21364            .get(&key_id)
21365            .into_iter()
21366            .flatten()
21367            .filter_map(|sid| skill_name(*sid))
21368            .collect();
21369        rows.push(serde_json::json!({
21370            "id": key_id,
21371            "label": key.data.get("label").and_then(|v| v.as_str()).unwrap_or(&key.name),
21372            "prefix": key.secret_prefix,
21373            "active": key.active,
21374            "created_at": key.created_at.get().map(|t| t.format("%Y-%m-%d %H:%M").to_string()),
21375            "scope": scope,
21376        }));
21377    }
21378    let skill_rows: Vec<serde_json::Value> = skills
21379        .iter()
21380        .map(|s| {
21381            serde_json::json!({
21382                "codename": s.codename,
21383                "name": s.name,
21384                "description": s.description,
21385            })
21386        })
21387        .collect();
21388    (rows, skill_rows)
21389}
21390
21391async fn render_account_page(
21392    state: &super::AdminState,
21393    tenant: &Tenant,
21394    headers: &HeaderMap,
21395    session_user: Option<&rustango::tenancy::auth::User>,
21396    mcp_one_time: Option<serde_json::Value>,
21397) -> Result<Response, AdminError> {
21398    // #202 — surface the current + pending email + mailer presence so
21399    // the Profile card can render the change-email form variant.
21400    let (current_email, pending_email, mailer_wired) = {
21401        let mailer = state.mailer.is_some();
21402        let user_data = session_user
21403            .map(|u| u.data.clone())
21404            .unwrap_or_else(|| serde_json::json!({}));
21405        let cur = session_user.map(user_email).unwrap_or_default();
21406        let pending = user_data
21407            .get("pending_email")
21408            .and_then(|v| v.as_str())
21409            .unwrap_or("")
21410            .to_owned();
21411        (cur, pending, mailer)
21412    };
21413    let mut ctx = Context::new();
21414    add_chrome(&mut ctx, tenant, "", session_user).await;
21415    add_admin_theme(&mut ctx, tenant.pool()).await;
21416    // #174 — admin theme picker lives in Preferences (was on
21417    // Settings). Surface every cms_theme row + its 4 marquee
21418    // colors for a swatch preview.
21419    let themes: Vec<crate::theme::Theme> = crate::theme::Theme::objects()
21420        .order_by(&[("name", false)])
21421        .fetch(tenant.pool())
21422        .await
21423        .unwrap_or_default();
21424    let theme_rows: Vec<serde_json::Value> = themes
21425        .iter()
21426        .map(|t| {
21427            serde_json::json!({
21428                "id": t.id.get().copied(),
21429                "name": t.name,
21430                "slug": t.slug,
21431                "is_admin_default": t.is_admin_default,
21432                "color_bg": t.color_bg,
21433                "color_surface": t.color_surface,
21434                "color_text_primary": t.color_text_primary,
21435                "color_link": t.color_link,
21436            })
21437        })
21438        .collect();
21439    ctx.insert("themes", &theme_rows);
21440    // #128 — plugin-contributed Account settings panels. Each panel is a pre-rendered HTML fragment hosts
21441    // contribute via `register_account_settings_panel!`.
21442    let account_panels: Vec<serde_json::Value> = crate::hooks::account_settings_panels()
21443        .into_iter()
21444        .map(|p| {
21445            serde_json::json!({
21446                "key": p.key,
21447                "label": p.label,
21448                "icon": p.icon,
21449                "html": p.html,
21450            })
21451        })
21452        .collect();
21453    ctx.insert("account_panels", &account_panels);
21454
21455    // #197 — per-user notification preferences. We pass every kind
21456    // through with its current toggle state so the template renders
21457    // checked/unchecked without a second fetch. Missing rows default
21458    // to true (opt-out semantics).
21459    let pref_map = session_user
21460        .and_then(|u| u.id.get().copied())
21461        .map(|uid| crate::notification_pref::map_for_user(tenant.pool(), uid))
21462        .map(|fut| async move { fut.await.unwrap_or_default() });
21463    let pref_lookup: std::collections::HashMap<String, bool> = match pref_map {
21464        Some(f) => f.await,
21465        None => std::collections::HashMap::new(),
21466    };
21467    let notification_rows: Vec<serde_json::Value> = crate::notification_pref::ALL_KINDS
21468        .iter()
21469        .map(|(label, kind, hint)| {
21470            let enabled = pref_lookup.get(*kind).copied().unwrap_or(true);
21471            serde_json::json!({
21472                "label": label,
21473                "kind": kind,
21474                "hint": hint,
21475                "enabled": enabled,
21476            })
21477        })
21478        .collect();
21479    ctx.insert("notification_prefs", &notification_rows);
21480
21481    ctx.insert("account_email", &current_email);
21482    ctx.insert("account_pending_email", &pending_email);
21483    ctx.insert("account_mailer_wired", &mailer_wired);
21484    ctx.insert(
21485        "show_templates",
21486        &session_user.is_some_and(|u| crate::template_inspector::wanted(u)),
21487    );
21488
21489    // #587 — MCP keys card: the viewer's keys + the skill catalog for
21490    // the optional-scope picker; `mcp_one_time` carries a just-minted
21491    // token for the show-once dialog.
21492    if let Some(uid) = session_user.and_then(|u| u.id.get().copied()) {
21493        let (keys, skills) = mcp_keys_ctx(tenant.pool(), uid).await;
21494        ctx.insert("mcp_keys", &keys);
21495        ctx.insert("mcp_skills", &skills);
21496    }
21497    if let Some(one_time) = &mcp_one_time {
21498        ctx.insert("mcp_one_time", one_time);
21499    }
21500
21501    render_with_csrf(
21502        state,
21503        headers,
21504        "rcms_admin/account_preferences.html",
21505        &mut ctx,
21506    )
21507}
21508
21509/// POST /cms-admin/me/notifications — save the on/off toggles for
21510/// every notification kind. The form posts a checkbox per kind;
21511/// absent inputs mean "off". Iterates every known kind so the user
21512/// can disable categories from a single submit.
21513pub async fn account_notifications_submit(
21514    State(_state): State<super::AdminState>,
21515    tenant: Tenant,
21516    headers: HeaderMap,
21517    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
21518    Form(form): Form<std::collections::HashMap<String, String>>,
21519) -> Result<Response, AdminError> {
21520    let Some(viewer) = session_user.as_ref() else {
21521        return Ok(unauthorized_no_session());
21522    };
21523    let Some(uid) = viewer.id.get().copied() else {
21524        return Ok((axum::http::StatusCode::UNAUTHORIZED, "no user id").into_response());
21525    };
21526    for (_label, kind, _hint) in crate::notification_pref::ALL_KINDS {
21527        let key = format!("kind_{kind}");
21528        let enabled = form
21529            .get(&key)
21530            .map(|v| matches!(v.as_str(), "on" | "true" | "1" | "yes"))
21531            .unwrap_or(false);
21532        crate::notification_pref::set_enabled(tenant.pool(), uid, kind, enabled).await?;
21533    }
21534    redirect_named_with_params_and_message(
21535        "rcms-admin:account",
21536        &[],
21537        MsgLevel::Success,
21538        "Notification preferences saved.",
21539        &headers,
21540    )
21541}
21542
21543/// POST /cms-admin/me/profile — display name + avatar upload.
21544/// Multipart submit; absence of either field leaves the existing
21545/// value untouched. Avatar bytes land at
21546/// `./var/avatars/<tenant-slug>/<user_id>.<ext>` (slug-namespaced so
21547/// per-tenant user ids don't collide) and the filename is recorded in
21548/// `rustango_users.data.avatar_path`.
21549pub async fn account_profile_submit(
21550    State(_state): State<super::AdminState>,
21551    tenant: Tenant,
21552    headers: HeaderMap,
21553    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
21554    mut multipart: axum::extract::Multipart,
21555) -> Result<Response, AdminError> {
21556    let Some(viewer) = session_user.as_ref() else {
21557        return Ok(unauthorized_no_session());
21558    };
21559    let Some(uid) = viewer.id.get().copied() else {
21560        return Ok((axum::http::StatusCode::UNAUTHORIZED, "no user id").into_response());
21561    };
21562
21563    let mut new_display_name: Option<String> = None;
21564    let mut new_avatar_path: Option<String> = None;
21565    // Namespace avatars by tenant slug. Per-tenant DBs each start user
21566    // ids at 1, so a flat `./var/avatars/{uid}.{ext}` collided across
21567    // tenants (tenant B's user #1 overwriting / exposing tenant A's).
21568    let avatar_dir = std::path::PathBuf::from("./var/avatars").join(&tenant.org.slug);
21569
21570    while let Some(field) = multipart
21571        .next_field()
21572        .await
21573        .map_err(|e| AdminError::Upload(format!("multipart parse: {e}")))?
21574    {
21575        let field_name = field.name().unwrap_or("").to_owned();
21576        match field_name.as_str() {
21577            "display_name" => {
21578                new_display_name = Some(
21579                    field
21580                        .text()
21581                        .await
21582                        .map_err(|e| AdminError::Upload(format!("read display_name: {e}")))?
21583                        .trim()
21584                        .to_owned(),
21585                );
21586            }
21587            "avatar" => {
21588                let original = field.file_name().map(|s| s.to_owned());
21589                let bytes = field
21590                    .bytes()
21591                    .await
21592                    .map_err(|e| AdminError::Upload(format!("read avatar: {e}")))?;
21593                if bytes.is_empty() {
21594                    continue;
21595                }
21596                // Raster pictures only: an SVG can carry script, and the
21597                // avatar is served from the admin's own origin.
21598                let ext = original
21599                    .as_deref()
21600                    .and_then(|n| n.rsplit_once('.'))
21601                    .map(|(_, ext)| ext.to_ascii_lowercase())
21602                    .unwrap_or_default();
21603                if !matches!(ext.as_str(), "png" | "jpg" | "jpeg" | "webp" | "gif") {
21604                    return Ok(redirect_named_with_message(
21605                        "rcms-admin:account",
21606                        MsgLevel::Error,
21607                        "The avatar must be a PNG, JPEG, WebP or GIF picture.",
21608                        &headers,
21609                    )?);
21610                }
21611                std::fs::create_dir_all(&avatar_dir)
21612                    .map_err(|e| AdminError::Upload(format!("create avatar dir: {e}")))?;
21613                let storage_name = format!("{uid}.{ext}");
21614                let path = avatar_dir.join(&storage_name);
21615                std::fs::write(&path, &bytes)
21616                    .map_err(|e| AdminError::Upload(format!("write avatar: {e}")))?;
21617                new_avatar_path = Some(storage_name);
21618            }
21619            _ => {
21620                let _ = field.bytes().await;
21621            }
21622        }
21623    }
21624
21625    // Reload the user row + merge changes into `.data`. Using the
21626    // pool fetch (rather than mutating the extracted `viewer`) keeps
21627    // the save isolated from any session-cache invariants.
21628    let mut user_rows: Vec<rustango::tenancy::auth::User> =
21629        rustango::tenancy::auth::User::objects()
21630            .where_(rustango::tenancy::auth::User::id.eq(uid))
21631            .fetch(tenant.pool())
21632            .await?;
21633    let Some(mut user) = user_rows.pop() else {
21634        return Ok((axum::http::StatusCode::NOT_FOUND, "user not found").into_response());
21635    };
21636
21637    let mut data = user.data.as_object().cloned().unwrap_or_default();
21638    if let Some(name) = new_display_name {
21639        if name.is_empty() {
21640            data.remove("display_name");
21641        } else {
21642            data.insert("display_name".to_owned(), serde_json::json!(name));
21643        }
21644    }
21645    if let Some(path) = new_avatar_path {
21646        data.insert("avatar_path".to_owned(), serde_json::json!(path));
21647    }
21648    user.data = serde_json::Value::Object(data);
21649    user.save(tenant.pool()).await?;
21650
21651    redirect_named_with_message(
21652        "rcms-admin:account",
21653        MsgLevel::Success,
21654        "Profile saved.",
21655        &headers,
21656    )
21657}
21658
21659/// Persist an editor's preferred admin UI locale to
21660/// `rustango_users.data.admin_lang`. Shared by the account-prefs form and
21661/// the sidebar switcher so both keep the durable pref in sync with the cookie.
21662async fn persist_user_admin_lang(
21663    pool: &rustango::sql::Pool,
21664    uid: i64,
21665    lang: &str,
21666) -> Result<(), AdminError> {
21667    let mut rows: Vec<rustango::tenancy::auth::User> = rustango::tenancy::auth::User::objects()
21668        .where_(rustango::tenancy::auth::User::id.eq(uid))
21669        .fetch(pool)
21670        .await?;
21671    if let Some(mut user) = rows.pop() {
21672        let mut data = user.data.as_object().cloned().unwrap_or_default();
21673        data.insert("admin_lang".to_owned(), serde_json::json!(lang));
21674        user.data = serde_json::Value::Object(data);
21675        user.save(pool).await?;
21676    }
21677    Ok(())
21678}
21679
21680/// Form body for `POST /cms-admin/me/language`.
21681#[derive(Debug, Deserialize)]
21682pub struct AccountLanguageForm {
21683    pub lang: String,
21684}
21685
21686/// POST /cms-admin/me/language — set the editor's preferred admin UI locale.
21687/// Persists to `rustango_users.data.admin_lang` (durable + cross-device,
21688/// folded into negotiation by `add_user_chrome` → `render_with_csrf`) AND sets
21689/// the sticky `rcms_admin_lang` cookie so the change applies on the next render.
21690/// An unshipped code resets to English.
21691pub async fn account_language_submit(
21692    State(_state): State<super::AdminState>,
21693    tenant: Tenant,
21694    headers: HeaderMap,
21695    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
21696    Form(form): Form<AccountLanguageForm>,
21697) -> Result<Response, AdminError> {
21698    let Some(viewer) = session_user.as_ref() else {
21699        return Ok(unauthorized_no_session());
21700    };
21701    let Some(uid) = viewer.id.get().copied() else {
21702        return Ok((axum::http::StatusCode::UNAUTHORIZED, "no user id").into_response());
21703    };
21704    let lang = if super::i18n::is_ui_locale(&form.lang) {
21705        form.lang.clone()
21706    } else {
21707        "en".to_owned()
21708    };
21709    persist_user_admin_lang(tenant.pool(), uid, &lang).await?;
21710
21711    let mut resp = redirect_named_with_message(
21712        "rcms-admin:account",
21713        MsgLevel::Success,
21714        "Language updated.",
21715        &headers,
21716    )?;
21717    let cookie = format!(
21718        "{}={lang}; Path=/; SameSite=Lax; Max-Age=31536000",
21719        super::i18n::ADMIN_LANG_COOKIE
21720    );
21721    if let Ok(v) = HeaderValue::from_str(&cookie) {
21722        resp.headers_mut().append(header::SET_COOKIE, v);
21723    }
21724    Ok(resp)
21725}
21726
21727/// Form body for `POST /cms-admin/me/show-templates`; the checkbox is
21728/// absent when unticked.
21729#[derive(Debug, Deserialize)]
21730pub struct AccountShowTemplatesForm {
21731    #[serde(default)]
21732    pub show_templates: Option<String>,
21733}
21734
21735/// POST /cms-admin/me/show-templates — turn the template inspector on the
21736/// public site on or off for this admin (`data.show_templates`; see
21737/// `crate::template_inspector`). Superusers only.
21738pub async fn account_show_templates_submit(
21739    tenant: Tenant,
21740    headers: HeaderMap,
21741    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
21742    axum::Form(form): axum::Form<AccountShowTemplatesForm>,
21743) -> Result<Response, AdminError> {
21744    let Some(viewer) = session_user.as_ref() else {
21745        return Ok(unauthorized_no_session());
21746    };
21747    if !viewer.is_superuser {
21748        return Ok((axum::http::StatusCode::FORBIDDEN, "admins only").into_response());
21749    }
21750    let Some(uid) = viewer.id.get().copied() else {
21751        return Ok((axum::http::StatusCode::UNAUTHORIZED, "no user id").into_response());
21752    };
21753    let on = form.show_templates.is_some();
21754    if let Some(mut user) = rustango::tenancy::auth::User::objects()
21755        .where_(rustango::tenancy::auth::User::id.eq(uid))
21756        .first(tenant.pool())
21757        .await?
21758    {
21759        let mut data = user.data.as_object().cloned().unwrap_or_default();
21760        data.insert(crate::template_inspector::PREFERENCE.to_owned(), serde_json::json!(on));
21761        user.data = serde_json::Value::Object(data);
21762        user.save(tenant.pool()).await?;
21763    }
21764    redirect_named_with_message(
21765        "rcms-admin:account",
21766        MsgLevel::Success,
21767        if on { "Templates will show on the site while you browse it." } else { "Templates are hidden on the site." },
21768        &headers,
21769    )
21770}
21771
21772/// Form body for `POST /cms-admin/me/email`.
21773#[derive(Debug, Deserialize)]
21774pub struct AccountEmailForm {
21775    pub new_email: String,
21776}
21777
21778/// POST /cms-admin/me/email — request an email change.
21779///
21780/// When a mailer is wired, the change goes through a confirmation
21781/// flow: a random 32-hex token is stashed on `user.data.pending_email_*`
21782/// and the new address receives a confirm link. Clicking the link
21783/// finalizes the change.
21784///
21785/// When no mailer is wired, the change applies immediately + a banner
21786/// explains no confirmation email was sent.
21787pub async fn account_email_submit(
21788    State(state): State<super::AdminState>,
21789    tenant: Tenant,
21790    headers: HeaderMap,
21791    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
21792    Form(form): Form<AccountEmailForm>,
21793) -> Result<Response, AdminError> {
21794    let Some(viewer) = session_user.as_ref() else {
21795        return Ok(unauthorized_no_session());
21796    };
21797    let Some(uid) = viewer.id.get().copied() else {
21798        return Ok((axum::http::StatusCode::UNAUTHORIZED, "no user id").into_response());
21799    };
21800
21801    let new_email = form.new_email.trim().to_owned();
21802    if new_email.is_empty() || !new_email.contains('@') {
21803        return redirect_named_with_message(
21804            "rcms-admin:account",
21805            MsgLevel::Error,
21806            "Enter a valid email address.",
21807            &headers,
21808        );
21809    }
21810
21811    let mut user = rustango::tenancy::auth::User::objects()
21812        .where_(rustango::tenancy::auth::User::id.eq(uid))
21813        .first(tenant.pool())
21814        .await?
21815        .ok_or(AdminError::NotFound(uid))?;
21816    let mut data = user.data.as_object().cloned().unwrap_or_default();
21817
21818    if state.mailer.is_none() {
21819        // No mailer → write directly + banner.
21820        data.insert("email".to_owned(), serde_json::json!(new_email));
21821        user.email = Some(new_email.clone());
21822        // Clear any in-flight confirmation token from a previous attempt.
21823        data.remove("pending_email");
21824        user.data = serde_json::Value::Object(data);
21825        user.save(tenant.pool()).await?;
21826        return redirect_named_with_message(
21827            "rcms-admin:account",
21828            MsgLevel::Warning,
21829            "Email updated. No confirmation email was sent — the host hasn't wired a mailer.",
21830            &headers,
21831        );
21832    }
21833
21834    // Stash the pending email so the editor sees a banner + the
21835    // confirm handler can replay-guard against a different change
21836    // having kicked off in the meantime. Drop legacy keys from the
21837    // previous hand-rolled token scheme so they don't shadow the
21838    // new flow.
21839    data.insert(
21840        "pending_email".to_owned(),
21841        serde_json::json!(new_email.clone()),
21842    );
21843    data.remove("pending_email_token");
21844    data.remove("pending_email_expires_at");
21845    user.data = serde_json::Value::Object(data);
21846    user.save(tenant.pool()).await?;
21847
21848    // Send the confirmation. Best-effort. The signed URL carries
21849    // user_id + email + TTL — `EmailVerification::verify` on the
21850    // confirm endpoint replaces the hand-rolled (token, expires_at)
21851    // round-trip we used to stash in user.data.
21852    if let Some(mailer) = state.mailer.as_deref() {
21853        let link = rustango::auth_flows::EmailVerification::issue(
21854            &rustango::auth_flows::LinkScope::from(&tenant),
21855            "/cms-admin/me/email/confirm",
21856            uid,
21857            &new_email,
21858            state.signing_secret.as_slice(),
21859            std::time::Duration::from_secs(3600),
21860        );
21861        let subject = "Confirm your CMS email change";
21862        let body = format!(
21863            "Click the link below to confirm your CMS email change to {new_email}.\n\nLink: {link}\n\nThe link expires in one hour. If you didn't request this change, ignore this email.\n",
21864        );
21865        let email = rustango::email::Email::new()
21866            .from((*state.mailer_from).clone())
21867            .to(new_email.clone())
21868            .subject(subject.to_owned())
21869            .body(body);
21870        if let Err(e) = mailer.send(&email).await {
21871            tracing::warn!(
21872                target: "rustango_cms::admin::account",
21873                user_id = uid, error = %e,
21874                "email-change confirmation send failed (pending_email stashed; user can re-request)"
21875            );
21876        }
21877    }
21878
21879    redirect_named_with_message(
21880        "rcms-admin:account",
21881        MsgLevel::Success,
21882        "Confirmation link sent to the new email. Click it within an hour to finalize the change.",
21883        &headers,
21884    )
21885}
21886
21887/// GET /cms-admin/me/email/confirm — verify the signed URL from
21888/// [`account_email_submit`] (`EmailVerification::verify`) and apply
21889/// the pending email change. The URL itself carries user_id + new
21890/// email + TTL signature — we just check the click came from the
21891/// account that started the change and that the change is still
21892/// the one the user wants to apply.
21893pub async fn account_email_confirm(
21894    State(state): State<super::AdminState>,
21895    tenant: Tenant,
21896    headers: HeaderMap,
21897    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
21898    axum::extract::OriginalUri(uri): axum::extract::OriginalUri,
21899) -> Result<Response, AdminError> {
21900    let Some(viewer) = session_user.as_ref() else {
21901        return Ok(unauthorized_no_session());
21902    };
21903    let Some(uid) = viewer.id.get().copied() else {
21904        return Ok((axum::http::StatusCode::UNAUTHORIZED, "no user id").into_response());
21905    };
21906
21907    let path_and_query = uri
21908        .path_and_query()
21909        .map(|p| p.as_str())
21910        .unwrap_or_default()
21911        .to_owned();
21912    let (token_uid, signed_email) = match rustango::auth_flows::EmailVerification::verify(
21913        &rustango::auth_flows::LinkScope::from(&tenant),
21914        &path_and_query,
21915        state.signing_secret.as_slice(),
21916    ) {
21917        Ok(pair) => pair,
21918        Err(_) => {
21919            return redirect_named_with_message(
21920                "rcms-admin:account",
21921                MsgLevel::Error,
21922                "Confirmation link is invalid or has expired. Request a new one.",
21923                &headers,
21924            );
21925        }
21926    };
21927    // Clicking your own confirm link from a different session is a
21928    // common case (verify from inbox on phone, signed in on
21929    // desktop). We require the session user to match the user_id
21930    // baked into the signed URL — anything else is a cross-account
21931    // hijack attempt.
21932    if token_uid != uid {
21933        return redirect_named_with_message(
21934            "rcms-admin:account",
21935            MsgLevel::Error,
21936            "Confirmation link belongs to a different account. Sign in as that account to confirm.",
21937            &headers,
21938        );
21939    }
21940
21941    let mut user = rustango::tenancy::auth::User::objects()
21942        .where_(rustango::tenancy::auth::User::id.eq(uid))
21943        .first(tenant.pool())
21944        .await?
21945        .ok_or(AdminError::NotFound(uid))?;
21946    let mut data = user.data.as_object().cloned().unwrap_or_default();
21947    // Stale-link guard: if the user kicked off a different change
21948    // since this link was minted (or none at all), reject — the
21949    // signed URL is still valid but no longer the one they want.
21950    let pending = data
21951        .get("pending_email")
21952        .and_then(|v| v.as_str())
21953        .unwrap_or("");
21954    if pending != signed_email {
21955        return redirect_named_with_message(
21956            "rcms-admin:account",
21957            MsgLevel::Error,
21958            "This link is for a different email change than the one currently pending. Request a fresh confirmation.",
21959            &headers,
21960        );
21961    }
21962
21963    data.insert("email".to_owned(), serde_json::json!(signed_email));
21964    user.email = Some(signed_email.clone());
21965    data.remove("pending_email");
21966    // Keys the earlier email-change flow stored — dropped on confirm so
21967    // old rows clean themselves up.
21968    data.remove("pending_email_token");
21969    data.remove("pending_email_expires_at");
21970    user.data = serde_json::Value::Object(data);
21971    user.save(tenant.pool()).await?;
21972
21973    redirect_named_with_message(
21974        "rcms-admin:account",
21975        MsgLevel::Success,
21976        "Email confirmed. Notifications go to the new address from now on.",
21977        &headers,
21978    )
21979}
21980
21981/// Form body for `POST /cms-admin/me/password`.
21982#[derive(Deserialize)]
21983pub struct AccountPasswordForm {
21984    pub current_password: String,
21985    pub new_password: String,
21986    pub new_password_confirm: String,
21987}
21988
21989/// POST /cms-admin/me/password — verify current password, hash + write
21990/// the new one.
21991pub async fn account_password_submit(
21992    State(_state): State<super::AdminState>,
21993    tenant: Tenant,
21994    headers: HeaderMap,
21995    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
21996    Form(form): Form<AccountPasswordForm>,
21997) -> Result<Response, AdminError> {
21998    let Some(viewer) = session_user.as_ref() else {
21999        return Ok(unauthorized_no_session());
22000    };
22001    let Some(uid) = viewer.id.get().copied() else {
22002        return Ok((axum::http::StatusCode::UNAUTHORIZED, "no user id").into_response());
22003    };
22004    if form.new_password.len() < 12 {
22005        return redirect_named_with_message(
22006            "rcms-admin:account",
22007            MsgLevel::Error,
22008            "New password must be at least 12 characters.",
22009            &headers,
22010        );
22011    }
22012    if form.new_password != form.new_password_confirm {
22013        return redirect_named_with_message(
22014            "rcms-admin:account",
22015            MsgLevel::Error,
22016            "New password and confirmation don't match.",
22017            &headers,
22018        );
22019    }
22020
22021    let mut user = rustango::tenancy::auth::User::objects()
22022        .where_(rustango::tenancy::auth::User::id.eq(uid))
22023        .first(tenant.pool())
22024        .await?
22025        .ok_or(AdminError::NotFound(uid))?;
22026
22027    let verified =
22028        crate::passwords::verify(&form.current_password, &user.password_hash).await.unwrap_or(false);
22029    if !verified {
22030        return redirect_named_with_message(
22031            "rcms-admin:account",
22032            MsgLevel::Error,
22033            "Current password is incorrect.",
22034            &headers,
22035        );
22036    }
22037    let hash = crate::passwords::hash(&form.new_password).await
22038        .map_err(|e| AdminError::Validation(format!("password hash failed: {e}")))?;
22039    user.password_hash = hash;
22040    user.password_changed_at = Some(chrono::Utc::now());
22041    user.save(tenant.pool()).await?;
22042
22043    redirect_named_with_message(
22044        "rcms-admin:account",
22045        MsgLevel::Success,
22046        "Password changed. Old sessions on other devices will be signed out on next request.",
22047        &headers,
22048    )
22049}
22050
22051/// GET /__cms-avatar/{user_id} — stream the user's avatar bytes.
22052/// Anonymous-OK so the sidebar avatar shows on the dashboard
22053/// pre-login. Image not found → 404.
22054pub async fn account_avatar_serve(
22055    headers: HeaderMap,
22056    tenant: Tenant,
22057    Path(user_id): Path<i64>,
22058) -> Response {
22059    let user_rows: Vec<rustango::tenancy::auth::User> =
22060        match rustango::tenancy::auth::User::objects()
22061            .where_(rustango::tenancy::auth::User::id.eq(user_id))
22062            .fetch(tenant.pool())
22063            .await
22064        {
22065            Ok(v) => v,
22066            Err(_) => {
22067                return (
22068                    axum::http::StatusCode::INTERNAL_SERVER_ERROR,
22069                    "user lookup failed",
22070                )
22071                    .into_response();
22072            }
22073        };
22074    let Some(user) = user_rows.into_iter().next() else {
22075        return (axum::http::StatusCode::NOT_FOUND, "user not found").into_response();
22076    };
22077    let storage_name = match user.data.get("avatar_path").and_then(|v| v.as_str()) {
22078        Some(s) if !s.is_empty() => s.to_owned(),
22079        _ => return (axum::http::StatusCode::NOT_FOUND, "no avatar").into_response(),
22080    };
22081    if storage_name.contains('/') || storage_name.contains("..") {
22082        return (axum::http::StatusCode::BAD_REQUEST, "invalid storage name").into_response();
22083    }
22084    // Tenant-scoped path (matches the upload) — never read another
22085    // tenant's avatar dir.
22086    let path = std::path::PathBuf::from("./var/avatars")
22087        .join(&tenant.org.slug)
22088        .join(&storage_name);
22089    let bytes = match std::fs::read(&path) {
22090        Ok(b) => b,
22091        Err(_) => {
22092            return (axum::http::StatusCode::NOT_FOUND, "avatar bytes missing").into_response()
22093        }
22094    };
22095    let mime = mime_guess::from_path(&storage_name)
22096        .first_or_octet_stream()
22097        .essence_str()
22098        .to_owned();
22099    // Same stable-URL staleness fix as branding: revalidate via a
22100    // content ETag so a changed avatar is picked up immediately.
22101    revalidated_asset(&headers, mime, bytes)
22102}
22103
22104pub async fn cms_login_form(
22105    State(state): State<super::AdminState>,
22106    headers: HeaderMap,
22107    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
22108    tenant: Tenant,
22109    Query(q): Query<std::collections::HashMap<String, String>>,
22110) -> Result<Response, AdminError> {
22111    let mut ctx = Context::new();
22112    // The framework's POST handler expects to receive the form at
22113    // `/login`. Set the action to a relative URL so the same shape
22114    // works under reverse proxies.
22115    ctx.insert("action", &"/login");
22116    // #279 — make sure the CMS-branded login form always carries a
22117    // `next` destination so the framework's POST handler doesn't
22118    // fall back to `/` (the public homepage). Precedence:
22119    //   1. Explicit `?next=` (passed in by `with_login_required`
22120    //      when an anonymous request hit an admin URL).
22121    //   2. Default `/cms-admin/` when the user navigated to /login
22122    //      manually — they almost certainly want the admin, not
22123    //      the public site root.
22124    // The framework's `sanitize_next` rejects open-redirect-shaped
22125    // values (anything not starting with a single `/`, scheme-bearing,
22126    // or pointing back at /login itself), so we don't need to filter
22127    // here; the worst case is the framework strips ours and uses `/`.
22128    let next = q
22129        .get("next")
22130        .map(String::as_str)
22131        .filter(|s| !s.is_empty())
22132        .unwrap_or("/cms-admin/");
22133    ctx.insert("next", next);
22134    // Friendly error from a redirect (e.g. `?error=invalid_credentials`).
22135    if let Some(err) = q.get("error") {
22136        ctx.insert("error", err);
22137    }
22138    // SSO (admin-sso) — one "Sign in with <provider>" button per enabled
22139    // `SsoProvider` row (the DB-backed, admin-managed, multi-provider model
22140    // that replaced the flat `Org.sso_*` columns). The framework serves
22141    // `/login/sso/{slug}` + `/login/sso/{slug}/callback` (mints the same
22142    // rustango_tenant_session cookie password login does), so no auth code
22143    // lives here — just the buttons. Mirrors the framework's own login context.
22144    let sso_providers = rustango::admin::sso_provider::list_enabled(tenant.pool(), "/login").await;
22145    ctx.insert("sso_enabled", &!sso_providers.is_empty());
22146    ctx.insert("sso_providers", &sso_providers);
22147    // Surface the callback's failure reason (it redirects with `?sso_error=...`).
22148    if let Some(err) = q.get("sso_error") {
22149        ctx.insert("sso_error", err);
22150    }
22151    // #199 — show the tenant's uploaded logo/favicon in the login brand badge
22152    // (falls back to the default icon when none is set). Same source as the
22153    // authenticated sidebar; the `/__cms-branding/*` routes are pre-auth.
22154    add_auth_chrome(&mut ctx, &tenant).await;
22155    render_with_csrf(&state, &headers, "login.html", &mut ctx)
22156}
22157
22158/// GET `/cms-admin/password-reset` — show the username form.
22159pub async fn password_reset_request_form(
22160    State(state): State<super::AdminState>,
22161    headers: HeaderMap,
22162    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
22163    tenant: Tenant,
22164) -> Result<Response, AdminError> {
22165    let mut ctx = Context::new();
22166    add_auth_chrome(&mut ctx, &tenant).await;
22167    render_with_csrf(
22168        &state,
22169        &headers,
22170        "rcms_admin/password_reset_request.html",
22171        &mut ctx,
22172    )
22173}
22174
22175/// POST `/cms-admin/password-reset` — issue a token, email the link,
22176/// render the "check your email" page either way (so the form never
22177/// confirms or denies account existence).
22178/// The key a password-reset link is signed with: the process secret
22179/// narrowed to one tenant and one password.
22180///
22181/// Tenants number their users from 1, so a link signed with the process
22182/// secret alone — which names only `user_id` — resets the same id on every
22183/// tenant. Binding the tenant slug makes a link verify only where it was
22184/// issued; binding the current password hash makes it die the moment the
22185/// password changes, so it is single-use without any cache.
22186/// The scope stamped on a reset link: the link only verifies on the tenant
22187/// (slug and org id) it was issued for, alongside the tenant-bound key.
22188fn password_reset_scope(org: &rustango::tenancy::Org) -> rustango::auth_flows::LinkScope {
22189    rustango::auth_flows::LinkScope::from(org)
22190}
22191
22192fn password_reset_key(secret: &[u8], tenant_slug: &str, password_hash: &str) -> Vec<u8> {
22193    let msg = format!("rcms-password-reset\0{tenant_slug}\0{password_hash}");
22194    crate::signing::hmac_sha256_hex(secret, msg.as_bytes()).into_bytes()
22195}
22196
22197/// The relative reset link (`/cms-admin/password-reset/confirm?…`) for
22198/// `user`, valid for an hour. Signed with a key bound to the tenant and
22199/// the user's current password hash, so it stops working once used.
22200fn password_reset_url(
22201    secret: &[u8],
22202    org: &rustango::tenancy::Org,
22203    user: &rustango::tenancy::auth::User,
22204) -> String {
22205    let key = password_reset_key(secret, &org.slug, &user.password_hash);
22206    rustango::auth_flows::PasswordReset::issue(
22207        &password_reset_scope(org),
22208        "/cms-admin/password-reset/confirm",
22209        user.id.get().copied().unwrap_or(0),
22210        &key,
22211        std::time::Duration::from_secs(3600),
22212    )
22213}
22214
22215/// A one-hour password-reset link for the active user `username` of `org`,
22216/// whose tenant database is `pool`, or `None` when there is no such user.
22217///
22218/// For operators: it works for an account with no email on file, which
22219/// the reset form cannot reach. The link is relative — prefix the site's
22220/// origin. It is valid on any admin router of this process, which signs
22221/// with the same [`crate::signing::secret`].
22222///
22223/// # Errors
22224/// Database errors from the user lookup.
22225pub async fn issue_password_reset_link(
22226    pool: &rustango::sql::Pool,
22227    org: &rustango::tenancy::Org,
22228    username: &str,
22229) -> Result<Option<String>, rustango::sql::ExecError> {
22230    let user: Option<rustango::tenancy::auth::User> = rustango::tenancy::auth::User::objects()
22231        .where_(rustango::tenancy::auth::User::username.eq(username.to_owned()))
22232        .where_(rustango::tenancy::auth::User::active.eq(true))
22233        .fetch(pool)
22234        .await?
22235        .into_iter()
22236        .next();
22237    let secret = crate::signing::derived_key(super::PASSWORD_RESET_KEY_PURPOSE);
22238    Ok(user.map(|u| password_reset_url(&secret, org, &u)))
22239}
22240
22241/// The active user a reset link was issued for, in this request's tenant.
22242///
22243/// The `user_id` in the link is read before it is trusted only to find
22244/// whose key to verify against; the link is accepted solely when it
22245/// verifies under that user's tenant- and password-bound key.
22246async fn password_reset_user(
22247    tenant: &Tenant,
22248    secret: &[u8],
22249    signed_url: &str,
22250) -> Option<rustango::tenancy::auth::User> {
22251    let claimed: i64 = signed_url
22252        .split_once('?')?
22253        .1
22254        .split('&')
22255        .find_map(|kv| kv.strip_prefix("user_id="))?
22256        .parse()
22257        .ok()?;
22258    let user = rustango::tenancy::auth::User::objects()
22259        .where_(rustango::tenancy::auth::User::id.eq(claimed))
22260        .where_(rustango::tenancy::auth::User::active.eq(true))
22261        .first(tenant.pool())
22262        .await
22263        .ok()??;
22264    let key = password_reset_key(secret, &tenant.org.slug, &user.password_hash);
22265    match rustango::auth_flows::PasswordReset::verify(
22266        &password_reset_scope(&tenant.org),
22267        signed_url,
22268        &key,
22269    ) {
22270        Ok(uid) if uid == claimed => Some(user),
22271        _ => None,
22272    }
22273}
22274
22275pub async fn password_reset_request_submit(
22276    State(state): State<super::AdminState>,
22277    tenant: Tenant,
22278    headers: HeaderMap,
22279    request: crate::security_log::LoginRequest,
22280    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
22281    Form(form): Form<std::collections::HashMap<String, String>>,
22282) -> Result<Response, AdminError> {
22283    let username = form.get("username").cloned().unwrap_or_default();
22284    if !username.trim().is_empty() {
22285        // Look up the rustango_users row by username. Active users
22286        // only; soft-disabled accounts get the same silent treatment
22287        // as missing ones.
22288        let user: Option<rustango::tenancy::auth::User> = rustango::tenancy::auth::User::objects()
22289            .where_(rustango::tenancy::auth::User::username.eq(username.clone()))
22290            .where_(rustango::tenancy::auth::User::active.eq(true))
22291            .fetch(tenant.pool())
22292            .await
22293            .unwrap_or_default()
22294            .into_iter()
22295            .next();
22296        if let Some(u) = user {
22297            let entry = SecurityEntry::new(
22298                crate::security_log::EVENT_PASSWORD_RESET_REQUESTED,
22299                "admin",
22300                &request.meta,
22301            )
22302            .user(u.id.get().copied(), &u.username);
22303            crate::security_log::record(tenant.pool(), &tenant.org.slug, entry).await;
22304            // The link goes to the user's real address. The response below
22305            // renders "sent" either way, so the form never confirms or
22306            // denies that an account exists.
22307            let token_url =
22308                password_reset_url(state.signing_secret.as_slice(), &tenant.org, &u);
22309            let to_email = Some(user_email(&u)).filter(|e| !e.is_empty());
22310            match (to_email, state.mailer.is_some()) {
22311                (Some(to), _) => {
22312                    send_reset_email(
22313                        state.mailer.as_deref(),
22314                        &state.mailer_from,
22315                        &to,
22316                        &u.username,
22317                        &token_url,
22318                    )
22319                    .await;
22320                }
22321                // No mailer: emails already go to stdout, which the page
22322                // tells the reader to check — so print the link there for
22323                // the operator too, rather than nothing at all.
22324                (None, false) => {
22325                    println!(
22326                        "============= password reset =============\n\
22327                         {} has no email on file. Reset link, valid for an hour \
22328                         (prefix the site's address):\n{token_url}\n\
22329                         ==========================================",
22330                        u.username
22331                    );
22332                    tracing::warn!(
22333                        username = %u.username,
22334                        "password reset for an account with no email: link printed to stdout"
22335                    );
22336                }
22337                (None, true) => {
22338                    tracing::warn!(
22339                        username = %u.username,
22340                        "password reset requested but the account has no email on file; nothing \
22341                         sent. Add an email to the account, or issue a link with \
22342                         rustango_cms::admin::issue_password_reset_link"
22343                    );
22344                }
22345            }
22346        }
22347    }
22348    let mut ctx = Context::new();
22349    add_auth_chrome(&mut ctx, &tenant).await;
22350    // The stdout hint is only true when no mailer is wired.
22351    ctx.insert("console_mail", &state.mailer.is_none());
22352    render_with_csrf(
22353        &state,
22354        &headers,
22355        "rcms_admin/password_reset_sent.html",
22356        &mut ctx,
22357    )
22358}
22359
22360/// GET `/cms-admin/password-reset/confirm` — verify the signed token
22361/// in the URL, render the new-password form when valid. Invalid /
22362/// expired links land on a friendly error inside the same template.
22363pub async fn password_reset_confirm_form(
22364    State(state): State<super::AdminState>,
22365    tenant: Tenant,
22366    headers: HeaderMap,
22367    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
22368    axum::extract::OriginalUri(uri): axum::extract::OriginalUri,
22369) -> Result<Response, AdminError> {
22370    let path_and_query = uri
22371        .path_and_query()
22372        .map(|p| p.as_str())
22373        .unwrap_or_default()
22374        .to_owned();
22375    let mut ctx = Context::new();
22376    add_auth_chrome(&mut ctx, &tenant).await;
22377    match password_reset_user(&tenant, state.signing_secret.as_slice(), &path_and_query).await {
22378        Some(_) => {
22379            // Pass the signed URL through so the POST handler can
22380            // re-verify before writing the new password.
22381            ctx.insert("signed_token", &path_and_query);
22382            render_with_csrf(
22383                &state,
22384                &headers,
22385                "rcms_admin/password_reset_confirm.html",
22386                &mut ctx,
22387            )
22388        }
22389        None => {
22390            ctx.insert(
22391                "error",
22392                &"This reset link is invalid or has expired. Request a fresh one.",
22393            );
22394            render_with_csrf(
22395                &state,
22396                &headers,
22397                "rcms_admin/password_reset_request.html",
22398                &mut ctx,
22399            )
22400        }
22401    }
22402}
22403
22404/// POST `/cms-admin/password-reset/confirm` — verify the token + new
22405/// password fields, hash the password, write to `rustango_users`,
22406/// render the "all set" page.
22407pub async fn password_reset_confirm_submit(
22408    State(state): State<super::AdminState>,
22409    tenant: Tenant,
22410    headers: HeaderMap,
22411    request: crate::security_log::LoginRequest,
22412    rustango::extractors::SessionUser(_session_user): rustango::extractors::SessionUser,
22413    Form(form): Form<std::collections::HashMap<String, String>>,
22414) -> Result<Response, AdminError> {
22415    let token = form.get("token").cloned().unwrap_or_default();
22416    let password = form.get("password").cloned().unwrap_or_default();
22417    let password_confirm = form.get("password_confirm").cloned().unwrap_or_default();
22418
22419    let mut ctx = Context::new();
22420    add_auth_chrome(&mut ctx, &tenant).await;
22421    let render_confirm_with_error = |state: &super::AdminState,
22422                                     headers: &HeaderMap,
22423                                     token: &str,
22424                                     msg: &str|
22425     -> Result<Response, AdminError> {
22426        let mut c = Context::new();
22427        c.insert("signed_token", &token);
22428        c.insert("error", &msg);
22429        render_with_csrf(
22430            state,
22431            headers,
22432            "rcms_admin/password_reset_confirm.html",
22433            &mut c,
22434        )
22435    };
22436
22437    if password.len() < 12 {
22438        return render_confirm_with_error(
22439            &state,
22440            &headers,
22441            &token,
22442            "Password must be at least 12 characters.",
22443        );
22444    }
22445    if password != password_confirm {
22446        return render_confirm_with_error(
22447            &state,
22448            &headers,
22449            &token,
22450            "Password confirmation didn't match.",
22451        );
22452    }
22453
22454    // Tenant- and password-bound (#673): a link from another tenant, or one
22455    // already used to change this password, does not verify.
22456    let Some(mut user) = password_reset_user(&tenant, state.signing_secret.as_slice(), &token).await
22457    else {
22458        ctx.insert(
22459            "error",
22460            &"This reset link is invalid or has expired. Request a fresh one.",
22461        );
22462        return render_with_csrf(
22463            &state,
22464            &headers,
22465            "rcms_admin/password_reset_request.html",
22466            &mut ctx,
22467        );
22468    };
22469    let new_hash = match crate::passwords::hash(&password).await {
22470        Ok(h) => h,
22471        Err(e) => {
22472            tracing::warn!(error = %e, "password hash failed");
22473            return render_confirm_with_error(
22474                &state,
22475                &headers,
22476                &token,
22477                "Could not save the new password. Try again.",
22478            );
22479        }
22480    };
22481    user.password_hash = new_hash;
22482    if user.save(tenant.pool()).await.is_err() {
22483        return render_confirm_with_error(
22484            &state,
22485            &headers,
22486            &token,
22487            "Could not save the new password. Try again.",
22488        );
22489    }
22490    // Proving control of the account's mail lifts a lock a guesser set.
22491    if let Some(site) = rustango::tenancy::TenantSlug::of(&tenant.org) {
22492        crate::security_log::unlock(&site, &user.username).await;
22493    }
22494    let entry = SecurityEntry::new(crate::security_log::EVENT_PASSWORD_RESET, "admin", &request.meta)
22495        .user(user.id.get().copied(), &user.username);
22496    crate::security_log::record(tenant.pool(), &tenant.org.slug, entry).await;
22497
22498    render_with_csrf(
22499        &state,
22500        &headers,
22501        "rcms_admin/password_reset_done.html",
22502        &mut ctx,
22503    )
22504}
22505
22506/// Send the reset email via `ConsoleMailer`. Prints the URL to stdout
22507/// in dev; production deployments swap in `SmtpMailer` here.
22508///
22509/// The `rustango_users` table doesn't carry an email column, so the
22510/// "to" address is synthesized from the username for now. Replace
22511/// with `user.email` once the host extends the user model.
22512/// Deliver the reset link to the user's real address through
22513/// the host-configured mailer (`router_with_mailer`), falling back to
22514/// the console mailer in dev setups with no mailer wired.
22515async fn send_reset_email(
22516    mailer: Option<&dyn rustango::email::Mailer>,
22517    mailer_from: &str,
22518    to_email: &str,
22519    username: &str,
22520    reset_url: &str,
22521) {
22522    let from = if mailer_from.trim().is_empty() {
22523        "noreply@cms.local"
22524    } else {
22525        mailer_from
22526    };
22527    let email = rustango::email::Email::new()
22528        .to(to_email)
22529        .from(from)
22530        .subject("Reset your CMS password")
22531        .body(format!(
22532            "Hi {username},\n\n\
22533             We received a request to reset your CMS password.\n\
22534             Click the link below within the next hour to set a new one:\n\n\
22535             {reset_url}\n\n\
22536             If you didn't request this, you can safely ignore this email.\n"
22537        ));
22538    let result = match mailer {
22539        Some(m) => m.send(&email).await,
22540        None => {
22541            let console = rustango::email::ConsoleMailer;
22542            <rustango::email::ConsoleMailer as rustango::email::Mailer>::send(&console, &email)
22543                .await
22544        }
22545    };
22546    if let Err(e) = result {
22547        tracing::warn!(error = %e, username = %username, "password-reset mail send failed");
22548    }
22549    tracing::info!(username = %username, "issued password-reset link");
22550}
22551
22552#[cfg(test)]
22553mod tests {
22554    //! Role-permission matrix translation tests. Exercise the
22555    //! pure helpers — no DB, no Tera.
22556    use super::*;
22557
22558    fn reset_user(password_hash: &str) -> rustango::tenancy::auth::User {
22559        rustango::tenancy::auth::User {
22560            id: rustango::sql::Auto::Set(7),
22561            username: "admin".to_owned(),
22562            password_hash: password_hash.to_owned(),
22563            email: None,
22564            is_superuser: true,
22565            active: true,
22566            created_at: chrono::Utc::now(),
22567            data: serde_json::json!({}),
22568            password_changed_at: None,
22569            sessions_revoked_at: None,
22570        }
22571    }
22572
22573    /// The link an operator gets (or the console prints for an account
22574    /// with no email) is the one the confirm page accepts — and it dies
22575    /// once the password changes.
22576    #[test]
22577    fn a_reset_link_verifies_until_the_password_changes() {
22578        let secret = b"test-secret";
22579        let blog_org = password_reset_key_tests::org(1, "blog");
22580        let url = password_reset_url(secret, &blog_org, &reset_user("hash-1"));
22581        assert!(url.starts_with("/cms-admin/password-reset/confirm?user_id=7&"), "{url}");
22582        let key = password_reset_key(secret, "blog", "hash-1");
22583        let blog = password_reset_scope(&blog_org);
22584        assert_eq!(rustango::auth_flows::PasswordReset::verify(&blog, &url, &key).ok(), Some(7));
22585        let after_change = password_reset_key(secret, "blog", "hash-2");
22586        assert!(rustango::auth_flows::PasswordReset::verify(&blog, &url, &after_change).is_err());
22587        let other_tenant = password_reset_key(secret, "shop", "hash-1");
22588        let shop = password_reset_scope(&password_reset_key_tests::org(2, "shop"));
22589        assert!(rustango::auth_flows::PasswordReset::verify(&shop, &url, &other_tenant).is_err());
22590        // A new site that reuses the slug does not accept the old link.
22591        let reborn = password_reset_key_tests::org(9, "blog");
22592        let reborn_key = password_reset_key(secret, "blog", "hash-1");
22593        assert!(rustango::auth_flows::PasswordReset::verify(&password_reset_scope(&reborn), &url, &reborn_key).is_err());
22594    }
22595
22596    #[test]
22597    fn parse_matrix_form_translates_brackets_to_codenames() {
22598        let mut form = std::collections::HashMap::new();
22599        form.insert("name".to_owned(), "Editor".to_owned());
22600        form.insert("perm[pages][view]".to_owned(), "1".to_owned());
22601        form.insert("perm[pages][add]".to_owned(), "1".to_owned());
22602        form.insert("perm[pages][edit]".to_owned(), "1".to_owned());
22603        // Unchecked → not present in the form. View-only.
22604        form.insert("perm[history][view]".to_owned(), "1".to_owned());
22605        // Inapplicable cell — `history` doesn't accept `edit`. Must be
22606        // dropped silently.
22607        form.insert("perm[history][edit]".to_owned(), "1".to_owned());
22608        // Off-state checkbox shouldn't produce a grant.
22609        form.insert("perm[redirects][delete]".to_owned(), "0".to_owned());
22610        // Unknown resource key — dropped.
22611        form.insert("perm[bogus][view]".to_owned(), "1".to_owned());
22612        // Malformed key — dropped.
22613        form.insert("perm[pages]".to_owned(), "1".to_owned());
22614
22615        let codenames = parse_matrix_form(&form);
22616        assert!(codenames.contains(&"cms_page.view".to_owned()));
22617        assert!(codenames.contains(&"cms_page.add".to_owned()));
22618        assert!(codenames.contains(&"cms_page.edit".to_owned()));
22619        assert!(codenames.contains(&"cms_history.view".to_owned()));
22620        assert!(!codenames.contains(&"cms_history.edit".to_owned()));
22621        assert!(!codenames.contains(&"cms_redirect.delete".to_owned()));
22622        // No bogus / malformed leakage.
22623        assert!(!codenames.iter().any(|c| c.contains("bogus")));
22624    }
22625
22626    #[test]
22627    fn split_matrix_codenames_isolates_legacy() {
22628        let granted = vec![
22629            "cms_page.view".to_owned(),
22630            "cms_page.edit".to_owned(),
22631            "rustango_roles.view".to_owned(),
22632            "acme_custom.do_thing".to_owned(),
22633            "free_form_string".to_owned(),
22634        ];
22635        let (matched, legacy) = split_matrix_codenames(&granted);
22636        assert!(matched.contains(&"cms_page.view".to_owned()));
22637        assert!(matched.contains(&"cms_page.edit".to_owned()));
22638        assert!(matched.contains(&"rustango_roles.view".to_owned()));
22639        assert!(legacy.contains(&"acme_custom.do_thing".to_owned()));
22640        assert!(legacy.contains(&"free_form_string".to_owned()));
22641    }
22642
22643    #[test]
22644    fn build_permission_matrix_marks_granted_cells() {
22645        let granted = vec![
22646            "cms_page.view".to_owned(),
22647            "cms_page.add".to_owned(),
22648            "cms_media.view".to_owned(),
22649        ];
22650        let matrix = build_permission_matrix(&granted);
22651        let arr = matrix.as_array().expect("matrix is an array of sections");
22652        // Find the Content section → Pages row → granted list.
22653        let pages_row = arr
22654            .iter()
22655            .flat_map(|s| s["rows"].as_array().unwrap().iter())
22656            .find(|r| r["key"] == "pages")
22657            .expect("pages row present");
22658        let granted_actions: Vec<&str> = pages_row["granted"]
22659            .as_array()
22660            .unwrap()
22661            .iter()
22662            .map(|v| v.as_str().unwrap())
22663            .collect();
22664        assert!(granted_actions.contains(&"view"));
22665        assert!(granted_actions.contains(&"add"));
22666        assert!(!granted_actions.contains(&"edit"));
22667        assert!(!granted_actions.contains(&"delete"));
22668    }
22669
22670    #[test]
22671    fn round_trip_form_to_codenames_to_matrix() {
22672        // Submit a matrix; reverse-render it; expect every checked cell
22673        // to come back as `granted`.
22674        let mut form = std::collections::HashMap::new();
22675        form.insert("perm[pages][view]".to_owned(), "1".to_owned());
22676        form.insert("perm[pages][publish]".to_owned(), "1".to_owned());
22677        form.insert("perm[media][view]".to_owned(), "1".to_owned());
22678        let codenames = parse_matrix_form(&form);
22679        let matrix = build_permission_matrix(&codenames);
22680
22681        let pages = matrix
22682            .as_array()
22683            .unwrap()
22684            .iter()
22685            .flat_map(|s| s["rows"].as_array().unwrap().iter())
22686            .find(|r| r["key"] == "pages")
22687            .unwrap();
22688        let granted: Vec<&str> = pages["granted"]
22689            .as_array()
22690            .unwrap()
22691            .iter()
22692            .map(|v| v.as_str().unwrap())
22693            .collect();
22694        assert_eq!(granted, vec!["view", "publish"]);
22695    }
22696
22697    // -------- #117 InlinePanel extractor --------
22698
22699    fn sample_spec() -> crate::page_type::InlinePanelSpec {
22700        crate::page_type::InlinePanelSpec::new(
22701            "team",
22702            "Team",
22703            vec![
22704                crate::page_type::ExtensionField {
22705                    name: "name".to_owned(),
22706                    label: "Name".to_owned(),
22707                    kind: crate::page_type::ExtensionFieldKind::Text,
22708                    value: String::new(),
22709                    help: String::new(),
22710                    max_length: None,
22711                },
22712                crate::page_type::ExtensionField {
22713                    name: "role".to_owned(),
22714                    label: "Role".to_owned(),
22715                    kind: crate::page_type::ExtensionFieldKind::Text,
22716                    value: String::new(),
22717                    help: String::new(),
22718                    max_length: None,
22719                },
22720            ],
22721        )
22722    }
22723
22724    #[test]
22725    fn inline_extractor_groups_by_row_index() {
22726        let spec = sample_spec();
22727        let mut form = std::collections::HashMap::new();
22728        form.insert("inline__team__0__name".to_owned(), "Ada".to_owned());
22729        form.insert("inline__team__0__role".to_owned(), "Engineer".to_owned());
22730        form.insert("inline__team__1__name".to_owned(), "Bob".to_owned());
22731        form.insert("inline__team__1__role".to_owned(), "Designer".to_owned());
22732        let rows = extract_inline_panel_rows(&form, &spec);
22733        assert_eq!(rows.len(), 2);
22734        assert_eq!(rows[0]["name"], "Ada");
22735        assert_eq!(rows[1]["role"], "Designer");
22736    }
22737
22738    #[test]
22739    fn inline_extractor_drops_tombstoned_rows() {
22740        let spec = sample_spec();
22741        let mut form = std::collections::HashMap::new();
22742        form.insert("inline__team__0__name".to_owned(), "Ada".to_owned());
22743        form.insert("inline__team__1__name".to_owned(), "Bob".to_owned());
22744        form.insert("inline__team__1____deleted".to_owned(), "1".to_owned());
22745        let rows = extract_inline_panel_rows(&form, &spec);
22746        assert_eq!(rows.len(), 1);
22747        assert_eq!(rows[0]["name"], "Ada");
22748    }
22749
22750    #[test]
22751    fn inline_extractor_ignores_unknown_field_names() {
22752        let spec = sample_spec();
22753        let mut form = std::collections::HashMap::new();
22754        form.insert("inline__team__0__name".to_owned(), "Ada".to_owned());
22755        form.insert("inline__team__0__bogus".to_owned(), "x".to_owned());
22756        let rows = extract_inline_panel_rows(&form, &spec);
22757        assert_eq!(rows.len(), 1);
22758        assert!(!rows[0].contains_key("bogus"));
22759    }
22760
22761    #[test]
22762    fn inline_extractor_keeps_the_row_id_and_widget_fields() {
22763        let spec = crate::page_type::InlinePanelSpec::with_widgets(
22764            "links",
22765            "Links",
22766            vec![
22767                crate::widget::Widget::new(crate::widget::WidgetKind::Select, "cause_id", "Cause"),
22768                crate::widget::Widget::new(crate::widget::WidgetKind::Boolean, "featured", "Featured"),
22769            ],
22770        );
22771        let mut form = std::collections::HashMap::new();
22772        form.insert("inline__links__0__id".to_owned(), "7".to_owned());
22773        form.insert("inline__links__0__cause_id".to_owned(), "3".to_owned());
22774        form.insert("inline__links__1__id".to_owned(), String::new());
22775        form.insert("inline__links__1__featured".to_owned(), "on".to_owned());
22776        let rows = extract_inline_panel_rows(&form, &spec);
22777        assert_eq!(rows.len(), 2);
22778        assert_eq!(rows[0]["id"], "7");
22779        assert_eq!(rows[0]["cause_id"], "3");
22780        assert_eq!(rows[1]["featured"], "on");
22781        assert!(!rows[1].contains_key("cause_id"), "an unposted field stays absent");
22782    }
22783
22784    #[test]
22785    fn inline_panel_ctx_names_and_fills_each_rows_widgets() {
22786        use crate::widget::{Widget, WidgetKind};
22787        let spec = crate::page_type::InlinePanelSpec::with_widgets(
22788            "links",
22789            "Links",
22790            vec![
22791                Widget::new(WidgetKind::Select, "cause_id", "Cause"),
22792                Widget::new(WidgetKind::Boolean, "featured", "Featured").with_value("true"),
22793            ],
22794        )
22795        .in_tab("Causes")
22796        .allow(false, false, true);
22797        let mut row = serde_json::Map::new();
22798        row.insert("id".into(), serde_json::json!(7));
22799        row.insert("cause_id".into(), serde_json::json!(3));
22800        row.insert("featured".into(), serde_json::json!(false));
22801        row.insert("__title".into(), serde_json::json!("Scholarships"));
22802        let ctx = inline_panel_ctx(&spec, &[row]);
22803
22804        assert_eq!(ctx["tab_slug"], "inline-causes");
22805        assert_eq!(ctx["row_count"], 1);
22806        let cards = ctx["cards"].as_array().expect("cards");
22807        // The blank row the add button clones comes first, with the placeholder
22808        // index and the widgets' own defaults.
22809        assert_eq!(cards[0]["template"], true);
22810        assert_eq!(cards[0]["widgets"][0]["name"], format!("inline__links__{INLINE_ROW_PLACEHOLDER}__cause_id"));
22811        assert_eq!(cards[0]["widgets"][1]["value"], "true");
22812        // A loaded row: its index, id, title and values.
22813        assert_eq!(cards[1]["template"], false);
22814        assert_eq!(cards[1]["id"], "7");
22815        assert_eq!(cards[1]["title"], "Scholarships");
22816        assert_eq!(cards[1]["widgets"][0]["name"], "inline__links__0__cause_id");
22817        assert_eq!(cards[1]["widgets"][0]["value"], "3");
22818        assert_eq!(cards[1]["widgets"][1]["value"], "", "false shows as an unchecked box");
22819        assert_eq!(ctx["spec"]["can_add"], false);
22820    }
22821
22822    /// A media item whose thumbnails were generated must still delete:
22823    /// its renditions reference it, so they go first.
22824    #[cfg(feature = "sqlite")]
22825    #[tokio::test]
22826    async fn media_with_renditions_deletes() {
22827        use rustango::sql::Auto;
22828        let pool = rustango::sql::Pool::connect("sqlite::memory:").await.expect("pool");
22829        for schema in [
22830            <crate::media::MediaCollection as rustango::core::Model>::SCHEMA,
22831            <Media as rustango::core::Model>::SCHEMA,
22832            <crate::rendition::MediaRendition as rustango::core::Model>::SCHEMA,
22833        ] {
22834            let sql = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(pool.dialect(), schema);
22835            for stmt in sql.split(';').map(str::trim).filter(|s| !s.is_empty()) {
22836                rustango::sql::raw_execute_pool(&pool, stmt, Vec::new()).await.expect("ddl");
22837            }
22838        }
22839        rustango::sql::raw_execute_pool(&pool, "PRAGMA foreign_keys = ON", Vec::new()).await.expect("fk on");
22840        let mut media = Media {
22841            id: Auto::Unset,
22842            filename: "a.png".into(),
22843            content_hash: "h".into(),
22844            mime: "image/png".into(),
22845            size: 1,
22846            kind: "image".into(),
22847            width: Some(1),
22848            height: Some(1),
22849            storage_key: "missing-a.png".into(),
22850            title: String::new(),
22851            alt_text: String::new(),
22852            description: String::new(),
22853            uploaded_by: None,
22854            collection_id: None,
22855            focal_point_x: None,
22856            focal_point_y: None,
22857            uploaded_at: Auto::Unset,
22858        };
22859        media.save(&pool).await.expect("media");
22860        let mid = media.id.get().copied().expect("id");
22861        let mut r = crate::rendition::MediaRendition {
22862            id: Auto::Unset,
22863            media_id: mid,
22864            content_hash: "h".into(),
22865            filter_spec: "fill-10x10".into(),
22866            width: 10,
22867            height: 10,
22868            mime: "image/webp".into(),
22869            storage_key: "missing-r.webp".into(),
22870            size: 1,
22871            last_used_at: chrono::Utc::now(),
22872            created_at: Auto::Unset,
22873        };
22874        r.save(&pool).await.expect("rendition");
22875        assert!(media.clone().delete(&pool).await.is_err(), "the bare delete hits the foreign key");
22876        delete_media(&pool, "acme", media).await.expect("deletes with its renditions");
22877        assert_eq!(Media::objects().fetch(&pool).await.expect("q").len(), 0);
22878        assert_eq!(crate::rendition::MediaRendition::objects().fetch(&pool).await.expect("q").len(), 0);
22879    }
22880
22881    #[test]
22882    fn per_row_panels_list_titles_only_and_name_their_endpoint() {
22883        let spec = crate::page_type::InlinePanelSpec::with_widgets(
22884            "links",
22885            "Links",
22886            vec![crate::widget::Widget::new(crate::widget::WidgetKind::Text, "name", "Name")],
22887        )
22888        .in_tab("Causes")
22889        .per_row();
22890        let rows = vec![crate::page_type::InlineRowSummary { id: 7, title: "Scholarships".into() }];
22891        let ctx = inline_panel_lazy_ctx(&spec, &rows, 2);
22892        assert_eq!(ctx["endpoint"], "/cms-admin/pages/2/inline/links");
22893        assert_eq!(ctx["cards"][0]["id"], "7");
22894        assert_eq!(ctx["cards"][0]["title"], "Scholarships");
22895        assert!(ctx["cards"][0].get("widgets").is_none(), "fields load when the card opens");
22896        assert_eq!(ctx["tab_slug"], "inline-causes");
22897        // A page not saved yet has nowhere to attach rows.
22898        assert!(inline_panel_lazy_ctx(&spec, &[], 0)["endpoint"].is_null());
22899    }
22900
22901    #[test]
22902    fn a_new_card_is_not_a_new_page_to_the_route_gate() {
22903        assert!(inline_row_id("new-row").unwrap().is_none());
22904        assert_eq!(inline_row_id("12").unwrap(), Some(12));
22905        assert!(inline_row_id("new").is_err());
22906        let code = |path: &str| super::super::route_perms::required(&axum::http::Method::POST, path).map(|r| r.codename);
22907        assert_eq!(code("/cms-admin/pages/2/inline/links/new-row").as_deref(), Some("cms_page.edit"));
22908        assert_eq!(code("/cms-admin/pages/2/inline/links/7/remove").as_deref(), Some("cms_page.edit"));
22909        assert_eq!(code("/cms-admin/pages/2/inline/links/order").as_deref(), Some("cms_page.edit"));
22910    }
22911
22912    #[test]
22913    fn legacy_fields_render_as_their_declared_kind() {
22914        // Every legacy field used to render as a text box.
22915        let mut spec = sample_spec();
22916        spec.fields[1].kind = crate::page_type::ExtensionFieldKind::Number;
22917        let kinds: Vec<_> = spec.row_widgets().iter().map(|w| w.kind).collect();
22918        assert_eq!(kinds, [crate::widget::WidgetKind::Text, crate::widget::WidgetKind::Number]);
22919    }
22920
22921    #[test]
22922    fn inline_extractor_ignores_unrelated_form_keys() {
22923        let spec = sample_spec();
22924        let mut form = std::collections::HashMap::new();
22925        form.insert("title".to_owned(), "irrelevant".to_owned());
22926        form.insert("inline__other_panel__0__name".to_owned(), "x".to_owned());
22927        let rows = extract_inline_panel_rows(&form, &spec);
22928        assert!(rows.is_empty());
22929    }
22930
22931    /// The page-edit submit handler funnels the raw posted
22932    /// form through an allow-list before re-deserializing as
22933    /// `PageForm`. The bug guarded here was that schedule fields
22934    /// (`go_live_at`, `expire_at`) and `show_in_menus` were missing
22935    /// from that allow-list, so any datetime the editor set on the
22936    /// Promote tab was silently dropped on save — and never made it
22937    /// to the scheduled-pages report. Lock these in so a future
22938    /// trim of the array can't reintroduce the regression.
22939    #[test]
22940    fn page_form_canonical_keys_include_schedule_and_menu_fields() {
22941        assert!(
22942            PAGE_FORM_CANONICAL_KEYS.contains(&"go_live_at"),
22943            "go_live_at must be in canonical keys — see #268"
22944        );
22945        assert!(
22946            PAGE_FORM_CANONICAL_KEYS.contains(&"expire_at"),
22947            "expire_at must be in canonical keys — see #268"
22948        );
22949        assert!(
22950            PAGE_FORM_CANONICAL_KEYS.contains(&"show_in_menus"),
22951            "show_in_menus must be in canonical keys — see #268"
22952        );
22953    }
22954}
22955
22956#[cfg(all(test, feature = "sqlite"))]
22957mod media_picker_tests {
22958    //! `media_picker_payload` filtering / pagination / collection-tree
22959    //! tests over an in-memory sqlite pool (mirrors redirect.rs's
22960    //! `mem_pool` pattern).
22961    use super::{media_picker_payload, MediaPickerQuery};
22962    use crate::media::{Media, MediaCollection};
22963    use rustango::core::Model as _;
22964    use rustango::sql::{Auto, FetcherPool as _, Pool};
22965
22966    async fn mem_pool() -> Pool {
22967        let pool = Pool::connect("sqlite::memory:")
22968            .await
22969            .expect("in-memory sqlite");
22970        for schema in [&Media::SCHEMA, &MediaCollection::SCHEMA] {
22971            let ddl = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(
22972                pool.dialect(),
22973                schema,
22974            );
22975            for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
22976                rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
22977                    .await
22978                    .expect("ddl");
22979            }
22980        }
22981        pool
22982    }
22983
22984    async fn mk_collection(pool: &Pool, name: &str, parent_id: Option<i64>, sort: i32) -> i64 {
22985        MediaCollection {
22986            id: Auto::Unset,
22987            name: name.to_owned(),
22988            parent_id,
22989            sort_order: sort,
22990            created_at: Auto::Unset,
22991        }
22992        .insert(pool)
22993        .await
22994        .expect("collection insert");
22995        MediaCollection::objects()
22996            .fetch(pool)
22997            .await
22998            .expect("fetch")
22999            .into_iter()
23000            .find(|c| c.name == name)
23001            .and_then(|c| c.id.get().copied())
23002            .expect("collection id")
23003    }
23004
23005    async fn mk_media(
23006        pool: &Pool,
23007        title: &str,
23008        filename: &str,
23009        kind: &str,
23010        collection_id: Option<i64>,
23011        alt: &str,
23012    ) {
23013        Media {
23014            id: Auto::Unset,
23015            filename: filename.to_owned(),
23016            content_hash: format!("{:0>64}", title.len()),
23017            mime: if kind == "image" {
23018                "image/png"
23019            } else {
23020                "application/pdf"
23021            }
23022            .to_owned(),
23023            size: 123,
23024            kind: kind.to_owned(),
23025            width: (kind == "image").then_some(100),
23026            height: (kind == "image").then_some(80),
23027            storage_key: format!("k-{filename}"),
23028            title: title.to_owned(),
23029            alt_text: alt.to_owned(),
23030            description: String::new(),
23031            uploaded_by: None,
23032            collection_id,
23033            focal_point_x: None,
23034            focal_point_y: None,
23035            uploaded_at: Auto::Unset,
23036        }
23037        .insert(pool)
23038        .await
23039        .expect("media insert");
23040    }
23041
23042    #[tokio::test]
23043    async fn default_kind_excludes_documents() {
23044        let pool = mem_pool().await;
23045        mk_media(&pool, "Photo", "p.png", "image", None, "").await;
23046        mk_media(&pool, "Spec", "s.pdf", "document", None, "").await;
23047        let body = media_picker_payload(&pool, &MediaPickerQuery::default())
23048            .await
23049            .expect("payload");
23050        let items = body["items"].as_array().expect("items");
23051        assert_eq!(items.len(), 1);
23052        assert_eq!(items[0]["kind"], "image");
23053        // kind=any opts back in.
23054        let q = MediaPickerQuery {
23055            kind: Some("any".to_owned()),
23056            ..Default::default()
23057        };
23058        let body = media_picker_payload(&pool, &q).await.expect("payload");
23059        assert_eq!(body["items"].as_array().expect("items").len(), 2);
23060    }
23061
23062    #[tokio::test]
23063    async fn collection_zero_means_uncategorized_only() {
23064        let pool = mem_pool().await;
23065        let cid = mk_collection(&pool, "Root", None, 0).await;
23066        mk_media(&pool, "In", "in.png", "image", Some(cid), "").await;
23067        mk_media(&pool, "Loose", "loose.png", "image", None, "").await;
23068        let q = MediaPickerQuery {
23069            collection: Some(0),
23070            ..Default::default()
23071        };
23072        let body = media_picker_payload(&pool, &q).await.expect("payload");
23073        let items = body["items"].as_array().expect("items");
23074        assert_eq!(items.len(), 1);
23075        assert_eq!(items[0]["title"], "Loose");
23076        assert_eq!(body["uncategorized_count"], 1);
23077        // Exact collection id narrows to its members.
23078        let q = MediaPickerQuery {
23079            collection: Some(cid),
23080            ..Default::default()
23081        };
23082        let body = media_picker_payload(&pool, &q).await.expect("payload");
23083        assert_eq!(body["items"].as_array().expect("items").len(), 1);
23084        assert_eq!(body["items"][0]["title"], "In");
23085    }
23086
23087    #[tokio::test]
23088    async fn search_matches_alt_text() {
23089        let pool = mem_pool().await;
23090        mk_media(
23091            &pool,
23092            "IMG_0001",
23093            "a.png",
23094            "image",
23095            None,
23096            "sunset glow over harbour",
23097        )
23098        .await;
23099        mk_media(&pool, "IMG_0002", "b.png", "image", None, "office desk").await;
23100        let q = MediaPickerQuery {
23101            q: Some("Sunset".to_owned()),
23102            ..Default::default()
23103        };
23104        let body = media_picker_payload(&pool, &q).await.expect("payload");
23105        let items = body["items"].as_array().expect("items");
23106        assert_eq!(items.len(), 1);
23107        assert_eq!(items[0]["title"], "IMG_0001");
23108    }
23109
23110    #[tokio::test]
23111    async fn pagination_math_and_has_more() {
23112        let pool = mem_pool().await;
23113        for i in 0..5 {
23114            mk_media(
23115                &pool,
23116                &format!("M{i}"),
23117                &format!("m{i}.png"),
23118                "image",
23119                None,
23120                "",
23121            )
23122            .await;
23123        }
23124        let q = MediaPickerQuery {
23125            limit: Some(2),
23126            offset: Some(0),
23127            ..Default::default()
23128        };
23129        let body = media_picker_payload(&pool, &q).await.expect("payload");
23130        assert_eq!(body["items"].as_array().expect("items").len(), 2);
23131        assert_eq!(body["total"], 5);
23132        assert_eq!(body["has_more"], true);
23133        let q = MediaPickerQuery {
23134            limit: Some(2),
23135            offset: Some(4),
23136            ..Default::default()
23137        };
23138        let body = media_picker_payload(&pool, &q).await.expect("payload");
23139        assert_eq!(body["items"].as_array().expect("items").len(), 1);
23140        assert_eq!(body["has_more"], false);
23141        // Offset past the end is clamped, not a panic.
23142        let q = MediaPickerQuery {
23143            limit: Some(2),
23144            offset: Some(99),
23145            ..Default::default()
23146        };
23147        let body = media_picker_payload(&pool, &q).await.expect("payload");
23148        assert_eq!(body["items"].as_array().expect("items").len(), 0);
23149    }
23150
23151    #[tokio::test]
23152    async fn collections_come_back_in_dfs_order_with_depth() {
23153        let pool = mem_pool().await;
23154        let root_a = mk_collection(&pool, "Alpha", None, 0).await;
23155        let _sub = mk_collection(&pool, "Alpha Child", Some(root_a), 0).await;
23156        let _root_b = mk_collection(&pool, "Beta", None, 1).await;
23157        mk_media(&pool, "In A", "a.png", "image", Some(root_a), "").await;
23158        let body = media_picker_payload(&pool, &MediaPickerQuery::default())
23159            .await
23160            .expect("payload");
23161        let cols = body["collections"].as_array().expect("collections");
23162        let names: Vec<&str> = cols.iter().map(|c| c["name"].as_str().unwrap()).collect();
23163        assert_eq!(names, ["Alpha", "Alpha Child", "Beta"]);
23164        assert_eq!(cols[0]["depth"], 0);
23165        assert_eq!(cols[1]["depth"], 1);
23166        assert_eq!(cols[2]["depth"], 0);
23167        assert_eq!(cols[0]["count"], 1);
23168        assert_eq!(cols[2]["count"], 0);
23169    }
23170
23171    #[tokio::test]
23172    async fn ids_lookup_resolves_any_kind() {
23173        // The label-hydration pass resolves exact ids — including
23174        // non-image kinds, which the default filter would drop.
23175        let pool = mem_pool().await;
23176        mk_media(&pool, "Photo", "p.png", "image", None, "").await;
23177        mk_media(&pool, "Spec", "s.pdf", "document", None, "").await;
23178        let all = media_picker_payload(
23179            &pool,
23180            &MediaPickerQuery {
23181                kind: Some("any".to_owned()),
23182                ..Default::default()
23183            },
23184        )
23185        .await
23186        .expect("payload");
23187        let ids: Vec<i64> = all["items"]
23188            .as_array()
23189            .unwrap()
23190            .iter()
23191            .map(|i| i["id"].as_i64().unwrap())
23192            .collect();
23193        let q = MediaPickerQuery {
23194            ids: Some(
23195                ids.iter()
23196                    .map(|i| i.to_string())
23197                    .collect::<Vec<_>>()
23198                    .join(","),
23199            ),
23200            ..Default::default()
23201        };
23202        let body = media_picker_payload(&pool, &q).await.expect("payload");
23203        let items = body["items"].as_array().expect("items");
23204        assert_eq!(
23205            items.len(),
23206            2,
23207            "document resolves too when ids are explicit"
23208        );
23209        // Explicit kind still narrows an ids lookup.
23210        let q = MediaPickerQuery {
23211            ids: Some(
23212                ids.iter()
23213                    .map(|i| i.to_string())
23214                    .collect::<Vec<_>>()
23215                    .join(","),
23216            ),
23217            kind: Some("image".to_owned()),
23218            ..Default::default()
23219        };
23220        let body = media_picker_payload(&pool, &q).await.expect("payload");
23221        assert_eq!(body["items"].as_array().expect("items").len(), 1);
23222    }
23223
23224    #[tokio::test]
23225    async fn image_items_carry_rendition_thumb_urls() {
23226        let pool = mem_pool().await;
23227        mk_media(&pool, "Pic", "p.png", "image", None, "").await;
23228        let body = media_picker_payload(&pool, &MediaPickerQuery::default())
23229            .await
23230            .expect("payload");
23231        let item = &body["items"][0];
23232        let thumb = item["thumb_url"].as_str().expect("thumb_url");
23233        assert!(
23234            thumb.starts_with("/__media__/fill-320x320"),
23235            "spec-first URL: {thumb}"
23236        );
23237        assert!(thumb.contains("v="), "cache-buster present: {thumb}");
23238        let preview = item["preview_url"].as_str().expect("preview_url");
23239        assert!(preview.contains("max-640x480"), "{preview}");
23240    }
23241}
23242
23243#[cfg(all(test, feature = "sqlite"))]
23244mod forms_list_tests {
23245    //! `forms_list_rows` row-model tests over an in-memory sqlite pool.
23246    use super::forms_list_rows;
23247    use crate::forms::submit::FormEntry;
23248    use crate::snippet::Snippet;
23249    use rustango::core::Model as _;
23250    use rustango::sql::{Auto, FetcherPool as _, Pool};
23251
23252    async fn mem_pool() -> Pool {
23253        let pool = Pool::connect("sqlite::memory:")
23254            .await
23255            .expect("in-memory sqlite");
23256        for schema in [&Snippet::SCHEMA, &FormEntry::SCHEMA] {
23257            let ddl = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(
23258                pool.dialect(),
23259                schema,
23260            );
23261            for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
23262                rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
23263                    .await
23264                    .expect("ddl");
23265            }
23266        }
23267        pool
23268    }
23269
23270    async fn mk_form(pool: &Pool, slug: &str, title: &str, fields: usize) -> i64 {
23271        let field_json: Vec<serde_json::Value> = (0..fields)
23272            .map(|i| serde_json::json!({"id": format!("f{i}"), "key": format!("k{i}"), "type": "text", "label": "F"}))
23273            .collect();
23274        Snippet {
23275            id: Auto::Unset,
23276            type_name: "form".to_owned(),
23277            folder_path: String::new(),
23278            slug: slug.to_owned(),
23279            title: title.to_owned(),
23280            body_markdown: String::new(),
23281            data: serde_json::json!({
23282                "settings": {},
23283                "pages": [{"id": "p1", "sections": [{"id": "s1", "rows": [{"id": "r1",
23284                    "columns": [{"id": "c1", "width": 12, "fields": field_json}]}]}]}]
23285            }),
23286            created_at: Auto::Unset,
23287            updated_at: Auto::Unset,
23288        }
23289        .insert(pool)
23290        .await
23291        .expect("form insert");
23292        Snippet::objects()
23293            .fetch(pool)
23294            .await
23295            .expect("fetch")
23296            .into_iter()
23297            .find(|s| s.slug == slug)
23298            .and_then(|s| s.id.get().copied())
23299            .expect("form id")
23300    }
23301
23302    async fn mk_entry(pool: &Pool, form_id: i64) {
23303        FormEntry {
23304            id: Auto::Unset,
23305            form_snippet_id: form_id,
23306            form_version: 1,
23307            source_page_id: 0,
23308            source_url: "/contact".to_owned(),
23309            data_json: serde_json::json!({"k0": "hi"}),
23310            locale: "en".to_owned(),
23311            ip: String::new(),
23312            submitted_at: Auto::Unset,
23313        }
23314        .insert(pool)
23315        .await
23316        .expect("entry insert");
23317    }
23318
23319    #[tokio::test]
23320    async fn rows_carry_field_and_submission_counts() {
23321        let pool = mem_pool().await;
23322        let a = mk_form(&pool, "contact", "Contact", 3).await;
23323        let b = mk_form(&pool, "rsvp", "RSVP", 1).await;
23324        mk_entry(&pool, a).await;
23325        mk_entry(&pool, a).await;
23326        let rows = forms_list_rows(&pool).await.expect("rows");
23327        assert_eq!(rows.len(), 2);
23328        let by_slug = |slug: &str| rows.iter().find(|r| r["slug"] == slug).expect("row");
23329        let ra = by_slug("contact");
23330        assert_eq!(ra["fields"], 3);
23331        assert_eq!(ra["submissions"], 2);
23332        assert!(
23333            ra["last_submission"].as_str().unwrap().len() >= 16,
23334            "has a timestamp"
23335        );
23336        assert_eq!(ra["build_url"], format!("/cms-admin/forms/{a}/build"));
23337        assert_eq!(
23338            ra["submissions_url"],
23339            format!("/cms-admin/forms/{a}/submissions")
23340        );
23341        let rb = by_slug("rsvp");
23342        assert_eq!(rb["fields"], 1);
23343        assert_eq!(rb["submissions"], 0);
23344        assert_eq!(rb["last_submission"], "");
23345        assert_eq!(rb["delete_url"], format!("/cms-admin/library/{b}/delete"));
23346    }
23347
23348    #[tokio::test]
23349    async fn only_form_snippets_appear() {
23350        let pool = mem_pool().await;
23351        mk_form(&pool, "contact", "Contact", 1).await;
23352        Snippet {
23353            id: Auto::Unset,
23354            type_name: "branding".to_owned(),
23355            folder_path: String::new(),
23356            slug: "site-branding".to_owned(),
23357            title: "Branding".to_owned(),
23358            body_markdown: String::new(),
23359            data: serde_json::json!({}),
23360            created_at: Auto::Unset,
23361            updated_at: Auto::Unset,
23362        }
23363        .insert(&pool)
23364        .await
23365        .expect("snippet insert");
23366        let rows = forms_list_rows(&pool).await.expect("rows");
23367        assert_eq!(rows.len(), 1);
23368        assert_eq!(rows[0]["slug"], "contact");
23369    }
23370
23371    #[test]
23372    fn user_admin_is_superuser_only() {
23373        // #642 — user management sets is_superuser / active / roles from
23374        // the form, so the whole surface is restricted to superusers.
23375        // A superuser proceeds; a signed-in non-superuser is bounced to
23376        // no-access; an anonymous caller to login. A regression that drops
23377        // the guard (or lets a non-superuser through) fails here.
23378        assert_eq!(super::user_admin_denial_target(Some(true)), None);
23379        assert_eq!(
23380            super::user_admin_denial_target(Some(false)),
23381            Some("/cms-admin/no-access")
23382        );
23383        assert_eq!(super::user_admin_denial_target(None), Some("/login"));
23384    }
23385
23386    #[test]
23387    fn mcp_key_admin_handlers_enforce_the_superuser_gate() {
23388        // #646 — the two /cms-admin/users/{id}/mcp-keys handlers must carry
23389        // the same superuser gate as every other user-admin handler. They
23390        // once gated on "a session exists" only, so a non-superuser could
23391        // mint a key bounded by a superuser's entitlement. Pin the wiring so
23392        // a future edit can't silently drop it again (the gap that untested
23393        // wiring hid the first time). Runs in the default suite — no DB.
23394        let src = include_str!("handlers.rs");
23395        for name in ["users_mcp_key_create", "users_mcp_key_revoke"] {
23396            let start = src
23397                .find(&format!("pub async fn {name}("))
23398                .unwrap_or_else(|| panic!("handler {name} not found"));
23399            // Bound the scan to this fn's body: up to the next top-level fn.
23400            let rest = &src[start + 1..];
23401            let end = rest.find("\npub async fn ").unwrap_or(rest.len());
23402            assert!(
23403                rest[..end].contains("require_superuser_for_user_admin(session_user.as_ref())"),
23404                "{name} is missing the superuser gate (#646)"
23405            );
23406        }
23407    }
23408}
23409
23410#[cfg(test)]
23411mod password_reset_key_tests {
23412    use super::{password_reset_key, password_reset_scope};
23413    use rustango::auth_flows::PasswordReset;
23414    use rustango::tenancy::Org;
23415    use std::time::Duration;
23416
23417    const SECRET: &[u8] = b"process-wide-signing-secret";
23418    const BASE: &str = "/cms-admin/password-reset/confirm";
23419
23420    /// A registry org with an id, which a tenant scope needs.
23421    pub(super) fn org(id: i64, slug: &str) -> Org {
23422        let mut org = Org::new(slug);
23423        org.id = rustango::sql::Auto::Set(id);
23424        org.backend_kind = "sqlite".to_owned();
23425        org
23426    }
23427
23428    fn link(tenant: &Org, hash: &str) -> String {
23429        PasswordReset::issue(
23430            &password_reset_scope(tenant),
23431            BASE,
23432            1,
23433            &password_reset_key(SECRET, &tenant.slug, hash),
23434            Duration::from_secs(3600),
23435        )
23436    }
23437
23438    #[test]
23439    fn a_link_verifies_for_the_tenant_and_password_it_was_issued_for() {
23440        let acme = org(1, "acme");
23441        let url = link(&acme, "$argon2id$v=19$old");
23442        let key = password_reset_key(SECRET, "acme", "$argon2id$v=19$old");
23443        assert_eq!(PasswordReset::verify(&password_reset_scope(&acme), &url, &key).ok(), Some(1));
23444    }
23445
23446    #[test]
23447    fn a_link_issued_on_one_tenant_does_not_verify_on_another() {
23448        // User ids restart at 1 per tenant: this is the takeover in #673.
23449        let url = link(&org(1, "acme"), "$argon2id$v=19$same");
23450        let other = password_reset_key(SECRET, "globex", "$argon2id$v=19$same");
23451        let globex = org(2, "globex");
23452        assert!(PasswordReset::verify(&password_reset_scope(&globex), &url, &other).is_err());
23453    }
23454
23455    #[test]
23456    fn a_link_does_not_verify_on_a_new_tenant_reusing_the_slug() {
23457        let url = link(&org(1, "acme"), "$argon2id$v=19$same");
23458        let key = password_reset_key(SECRET, "acme", "$argon2id$v=19$same");
23459        let reborn = org(9, "acme");
23460        assert!(PasswordReset::verify(&password_reset_scope(&reborn), &url, &key).is_err());
23461    }
23462
23463    #[test]
23464    fn a_link_stops_verifying_once_the_password_changes() {
23465        let acme = org(1, "acme");
23466        let url = link(&acme, "$argon2id$v=19$before");
23467        let after = password_reset_key(SECRET, "acme", "$argon2id$v=19$after");
23468        assert!(PasswordReset::verify(&password_reset_scope(&acme), &url, &after).is_err());
23469    }
23470}
23471
23472#[cfg(all(test, feature = "sqlite"))]
23473mod publish_gate_tests {
23474    //! A save that puts a page live takes the publish right,
23475    //! judged on the status it lands on after go-live derivation.
23476    use super::{apply_page_edit, PageEditActor, PageEditRefusal};
23477    use crate::page::{Page, PageStatus};
23478    use crate::page_type_model::PageType;
23479    use rustango::core::Column as _;
23480    use rustango::sql::{Auto, Pool};
23481
23482    pub(super) async fn mem_pool() -> Pool {
23483        let pool = Pool::connect("sqlite::memory:").await.expect("in-memory sqlite");
23484        for entry in inventory::iter::<rustango::core::ModelEntry> {
23485            if !entry.schema.managed {
23486                continue;
23487            }
23488            let ddl = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(
23489                pool.dialect(),
23490                entry.schema,
23491            );
23492            for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
23493                rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
23494                    .await
23495                    .expect("ddl");
23496            }
23497        }
23498        pool
23499    }
23500
23501    pub(super) async fn draft(pool: &Pool) -> Page {
23502        let mut pt = PageType {
23503            id: Auto::Unset,
23504            app_label: "cms".to_owned(),
23505            type_name: "TestPage".to_owned(),
23506            verbose_name: "Test page".to_owned(),
23507            default_template: "page.html".to_owned(),
23508            view_mode: "auto".to_owned(),
23509            is_creatable: true,
23510            allowed_parent_types: serde_json::json!([]),
23511            allowed_child_types: serde_json::json!([]),
23512            workflow: String::new(),
23513            created_at: Auto::Unset,
23514            updated_at: Auto::Unset,
23515        };
23516        pt.save(pool).await.expect("page type");
23517        let mut p = draft_template(pt.id.get().copied().expect("type id"));
23518        p.save(pool).await.expect("page");
23519        p
23520    }
23521
23522    pub(super) fn draft_template(type_id: i64) -> Page {
23523        Page {
23524            id: Auto::Unset,
23525            page_type_id: type_id,
23526            title: "Draft".to_owned(),
23527            slug: "draft".to_owned(),
23528            path: "0001/".to_owned(),
23529            url_path: "/draft".to_owned(),
23530            preview_path: String::new(),
23531            template_override: String::new(),
23532            depth: 1,
23533            parent_id: None,
23534            locale_variant_of: None,
23535            alias_of: None,
23536            theme_id: None,
23537            sort_order: 0,
23538            status: PageStatus::Draft.as_str().to_owned(),
23539            published_at: None,
23540            last_published_at: None,
23541            go_live_at: None,
23542            expire_at: None,
23543            seo_title: String::new(),
23544            seo_description: String::new(),
23545            robots_index: true,
23546            sitemap_priority: 0.5,
23547            show_in_menus: true,
23548            og_title: String::new(),
23549            og_description: String::new(),
23550            og_image_media_id: None,
23551            twitter_card: "summary".to_owned(),
23552            notification_pre_published_sent: false,
23553            created_at: Auto::Unset,
23554            updated_at: Auto::Unset,
23555        }
23556    }
23557
23558    async fn save(
23559        pool: &Pool,
23560        page: &Page,
23561        status: &str,
23562        go_live_days: Option<i64>,
23563        superuser: bool,
23564    ) -> Result<String, &'static str> {
23565        let mut form = crate::page_form::prefill(pool, page).await;
23566        form.insert("status".into(), status.to_owned());
23567        match go_live_days {
23568            Some(d) => form.insert(
23569                "go_live_at".into(),
23570                (chrono::Utc::now() + chrono::Duration::days(d))
23571                    .format("%Y-%m-%dT%H:%M")
23572                    .to_string(),
23573            ),
23574            None => form.remove("go_live_at"),
23575        };
23576        // A user with no roles: edit reached the handler, publish is not held.
23577        let actor = PageEditActor { id: 999, username: "editor".to_owned(), is_superuser: superuser };
23578        let invalidator: std::sync::Arc<dyn crate::cache_invalidate::PageCacheInvalidator> =
23579            std::sync::Arc::new(crate::cache_invalidate::Noop);
23580        let id = page.id.get().copied().expect("id");
23581        match apply_page_edit(pool, &rustango::tenancy::TenantSlug::new(1, "t"), &invalidator, None, "", false, id, &form, Some(&actor))
23582            .await
23583            .expect("save")
23584        {
23585            Ok(o) => Ok(o.page.status),
23586            Err(PageEditRefusal::PublishDenied) => Err("publish denied"),
23587            Err(PageEditRefusal::ReviewRequired { .. }) => Err("review required"),
23588            Err(_) => Err("other refusal"),
23589        }
23590    }
23591
23592    async fn stored_status(pool: &Pool, page: &Page) -> String {
23593        Page::objects()
23594            .where_(Page::id.eq(page.id.get().copied().expect("id")))
23595            .first(pool)
23596            .await
23597            .expect("query")
23598            .expect("page")
23599            .status
23600    }
23601
23602    async fn stored_theme(pool: &Pool, page: &Page) -> Option<i64> {
23603        Page::objects()
23604            .where_(Page::id.eq(page.id.get().copied().expect("id")))
23605            .first(pool)
23606            .await
23607            .expect("query")
23608            .expect("page")
23609            .theme_id
23610    }
23611
23612    /// #902 — the editor has no theme input, so its save must keep a theme
23613    /// set some other way; only a posted (empty) `theme_id` changes it.
23614    #[tokio::test]
23615    async fn an_editor_save_keeps_the_page_theme() {
23616        let pool = mem_pool().await;
23617        let mut page = draft(&pool).await;
23618        let mut theme = crate::theme::tests::fixture_theme();
23619        theme.save(&pool).await.expect("theme");
23620        let theme_id = theme.id.get().copied().expect("theme id");
23621        page.theme_id = Some(theme_id);
23622        page.save(&pool).await.expect("set theme");
23623
23624        let invalidator: std::sync::Arc<dyn crate::cache_invalidate::PageCacheInvalidator> =
23625            std::sync::Arc::new(crate::cache_invalidate::Noop);
23626        let id = page.id.get().copied().expect("id");
23627        let mut form = crate::page_form::prefill(&pool, &page).await;
23628        form.remove("theme_id");
23629        assert!(apply_page_edit(&pool, &rustango::tenancy::TenantSlug::new(1, "t"), &invalidator, None, "", false, id, &form, None).await.expect("save").is_ok());
23630        assert_eq!(stored_theme(&pool, &page).await, Some(theme_id), "a form without the field keeps it");
23631
23632        form.insert("theme_id".into(), String::new());
23633        assert!(apply_page_edit(&pool, &rustango::tenancy::TenantSlug::new(1, "t"), &invalidator, None, "", false, id, &form, None).await.expect("save").is_ok());
23634        assert_eq!(stored_theme(&pool, &page).await, None, "posted empty clears it");
23635    }
23636
23637    /// Publish a page-builder body with one text field, `headline`.
23638    pub(super) async fn publish_headline_schema(pool: &Pool, type_id: i64) {
23639        let document = serde_json::json!({
23640            "nodes": [{ "kind": "field", "key": "headline", "label": "Headline", "widget": "text" }]
23641        });
23642        rustango::sql::raw_execute_pool(
23643            pool,
23644            "INSERT INTO cms_page_type_schema (page_type_id, status, version, document) \
23645             VALUES (?, 'published', 1, ?)",
23646            vec![
23647                rustango::core::SqlValue::I64(type_id),
23648                rustango::core::SqlValue::Json(document),
23649            ],
23650        )
23651        .await
23652        .expect("schema");
23653    }
23654
23655    /// #857 — the new-page form carries the type's own fields, not only
23656    /// Title, Slug and Status.
23657    #[tokio::test]
23658    async fn the_new_page_form_shows_the_type_fields() {
23659        let pool = mem_pool().await;
23660        let type_id = draft(&pool).await.page_type_id;
23661        publish_headline_schema(&pool, type_id).await;
23662        let mut tera = tera::Tera::default();
23663        crate::admin::register_templates(&mut tera).expect("templates");
23664        let mut ctx = tera::Context::new();
23665        super::insert_type_fields(&mut ctx, &tera, &pool, None, Vec::new(), 0, type_id, None).await;
23666        let body = ctx
23667            .get("builder_body_html")
23668            .and_then(serde_json::Value::as_str)
23669            .expect("builder body on the new form")
23670            .to_owned();
23671        assert!(body.contains("pb__headline"), "headline input missing: {body}");
23672    }
23673
23674    /// #857 — what the new-page form posts for the type's fields is saved
23675    /// with the page, not dropped until a second save.
23676    #[tokio::test]
23677    async fn creating_a_page_saves_its_type_fields() {
23678        let pool = mem_pool().await;
23679        let page = draft(&pool).await;
23680        publish_headline_schema(&pool, page.page_type_id).await;
23681        let page_type = PageType::objects()
23682            .where_(PageType::id.eq(page.page_type_id))
23683            .first(&pool)
23684            .await
23685            .expect("type query");
23686        let id = page.id.get().copied().expect("id");
23687        let form = std::collections::HashMap::from([("pb__headline".to_owned(), "Hello".to_owned())]);
23688        super::save_type_content(&pool, page_type.as_ref(), page.page_type_id, id, &form)
23689            .await
23690            .expect("save");
23691        let data = crate::page_builder::model::data_for_page(&pool, id)
23692            .await
23693            .expect("builder data query")
23694            .expect("builder data row")
23695            .data;
23696        assert_eq!(data["headline"], "Hello", "{data}");
23697    }
23698
23699    #[tokio::test]
23700    async fn going_live_by_any_route_needs_the_publish_right() {
23701        let pool = mem_pool().await;
23702        let page = draft(&pool).await;
23703        for (status, go_live) in [
23704            ("archived", None),
23705            ("published", None),
23706            // Draft plus a future go-live is parked as scheduled.
23707            ("draft", Some(1)),
23708            // Scheduled with a go-live already past: the sweep publishes it.
23709            ("scheduled", Some(-1)),
23710        ] {
23711            assert_eq!(
23712                save(&pool, &page, status, go_live, false).await,
23713                Err("publish denied"),
23714                "{status} / {go_live:?}"
23715            );
23716            assert_eq!(stored_status(&pool, &page).await, "draft", "nothing written");
23717        }
23718        assert_eq!(
23719            save(&pool, &page, "scheduled", None, false).await,
23720            Ok("draft".to_owned()),
23721            "scheduled without a date is parked as a draft, so it is allowed"
23722        );
23723        assert_eq!(
23724            save(&pool, &page, "draft", Some(1), true).await,
23725            Ok("scheduled".to_owned()),
23726            "the publish right schedules"
23727        );
23728    }
23729
23730    /// A page type with a review workflow goes live only through it: a
23731    /// save straight to Published is refused for everyone but a
23732    /// superuser — the owner's review can't be skipped.
23733    /// Bind `type_id` to a one-step "Owner review" workflow.
23734    pub(super) async fn bind_review(pool: &Pool, type_id: i64, reapproval: bool) -> crate::workflow::Workflow {
23735        let mut wf = crate::workflow::Workflow {
23736            id: Auto::Unset,
23737            name: "Owner review".to_owned(),
23738            description: String::new(),
23739            active: true,
23740            require_reapproval_on_edit: reapproval,
23741            created_at: Auto::Unset,
23742            updated_at: Auto::Unset,
23743        };
23744        wf.save(pool).await.expect("workflow");
23745        rustango::sql::raw_execute_pool(pool, "INSERT INTO rustango_roles (id, name, description) VALUES (1, 'Owner', '')", Vec::new())
23746            .await
23747            .expect("role");
23748        let mut task = crate::workflow::WorkflowTask {
23749            id: Auto::Unset,
23750            workflow_id: wf.id.get().copied().expect("id"),
23751            name: "Owner checks".to_owned(),
23752            role_id: 1,
23753            sort_order: 10,
23754            kind: "group_approval".to_owned(),
23755            webhook_url: String::new(),
23756        };
23757        task.save(pool).await.expect("task");
23758        let mut pt = PageType::objects()
23759            .where_(PageType::id.eq(type_id))
23760            .first(pool)
23761            .await
23762            .expect("q")
23763            .expect("type");
23764        pt.workflow = "Owner review".to_owned();
23765        pt.save(pool).await.expect("bind");
23766        wf
23767    }
23768
23769    #[tokio::test]
23770    async fn a_review_workflow_cannot_be_published_around() {
23771        let pool = mem_pool().await;
23772        let page = draft(&pool).await;
23773        let mut wf = bind_review(&pool, page.page_type_id, false).await;
23774
23775        assert_eq!(save(&pool, &page, "published", None, false).await, Err("review required"));
23776        assert_eq!(save(&pool, &page, "draft", Some(1), false).await, Err("review required"), "nor scheduled");
23777        assert_eq!(stored_status(&pool, &page).await, "draft");
23778        assert_eq!(save(&pool, &page, "draft", None, false).await, Ok("draft".to_owned()), "drafts still save");
23779        assert_eq!(save(&pool, &page, "published", None, true).await, Ok("published".to_owned()), "the owner can");
23780
23781        // Renaming the workflow moves the page type along: still reviewed.
23782        let other = draft_named(&pool, page.page_type_id, "second").await;
23783        wf.name = "Studio review".to_owned();
23784        wf.save(&pool).await.expect("rename");
23785        assert_eq!(crate::workflow::rebind_page_types(&pool, "Owner review", "Studio review").await.expect("rebind"), 1);
23786        assert_eq!(save(&pool, &other, "published", None, false).await, Err("review required"));
23787    }
23788
23789    /// Save `page` with a new title; `actor` None is the CMS's own save.
23790    async fn retitle(pool: &Pool, page: &Page, title: &str, actor: Option<&PageEditActor>) -> super::PageEditOutcome {
23791        let mut form = crate::page_form::prefill(pool, page).await;
23792        form.insert("title".into(), title.to_owned());
23793        let invalidator: std::sync::Arc<dyn crate::cache_invalidate::PageCacheInvalidator> =
23794            std::sync::Arc::new(crate::cache_invalidate::Noop);
23795        let id = page.id.get().copied().expect("id");
23796        match apply_page_edit(pool, &rustango::tenancy::TenantSlug::new(1, "t"), &invalidator, None, "", false, id, &form, actor).await.expect("save") {
23797            Ok(o) => o,
23798            Err(_) => panic!("refused"),
23799        }
23800    }
23801
23802    async fn stored_title(pool: &Pool, page: &Page) -> String {
23803        Page::objects()
23804            .where_(Page::id.eq(page.id.get().copied().expect("id")))
23805            .first(pool)
23806            .await
23807            .expect("query")
23808            .expect("page")
23809            .title
23810    }
23811
23812    /// With re-approval on, an editor's save of a live page waits for the
23813    /// review: visitors keep the live version until the approval applies
23814    /// it; cancelling the review drops it; a superuser's save supersedes it.
23815    #[tokio::test]
23816    async fn a_live_page_edit_waits_for_review() {
23817        let pool = mem_pool().await;
23818        let page = draft(&pool).await;
23819        bind_review(&pool, page.page_type_id, true).await;
23820        assert_eq!(save(&pool, &page, "published", None, true).await, Ok("published".to_owned()));
23821        let id = page.id.get().copied().expect("id");
23822        let mut mia = rustango::tenancy::auth::User {
23823            id: Auto::Unset,
23824            username: "mia".to_owned(),
23825            password_hash: String::new(),
23826            email: None,
23827            is_superuser: false,
23828            active: true,
23829            created_at: chrono::Utc::now(),
23830            data: serde_json::json!({}),
23831            password_changed_at: None,
23832            sessions_revoked_at: None,
23833        };
23834        mia.save(&pool).await.expect("user");
23835        let editor = PageEditActor { id: mia.id.get().copied().expect("id"), username: "mia".to_owned(), is_superuser: false };
23836
23837        let out = retitle(&pool, &page, "Proposed", Some(&editor)).await;
23838        assert!(out.held_for_review && out.reapproval_kicked);
23839        assert_eq!(stored_title(&pool, &page).await, "Draft", "the live page is unchanged");
23840        let held = crate::pending_change::for_page(&pool, id).await.expect("q").expect("held");
23841        assert_eq!(held.form_map().get("title").map(String::as_str), Some("Proposed"));
23842        let mut state = crate::workflow::active_state_for_page(&pool, id).await.expect("q").expect("review started");
23843
23844        // The approval applies it through the normal save path.
23845        let tasks = crate::workflow::tasks_for(&pool, state.workflow_id).await.expect("tasks");
23846        crate::workflow::approve_current(&pool, &mut state, &tasks, editor.id, "").await.expect("approve");
23847        let applied = retitle(&pool, &page, "Proposed", None).await;
23848        assert!(!applied.held_for_review);
23849        assert_eq!(stored_title(&pool, &page).await, "Proposed");
23850
23851        // Cancelling the review drops a held change.
23852        retitle(&pool, &page, "Second try", Some(&editor)).await;
23853        let mut state = crate::workflow::active_state_for_page(&pool, id).await.expect("q").expect("review restarted");
23854        crate::workflow::cancel(&pool, &mut state, editor.id).await.expect("cancel");
23855        assert!(crate::pending_change::for_page(&pool, id).await.expect("q").is_none());
23856
23857        // A superuser's direct save supersedes one.
23858        retitle(&pool, &page, "Third try", Some(&editor)).await;
23859        let owner = PageEditActor { id: 1, username: "owner".to_owned(), is_superuser: true };
23860        assert!(!retitle(&pool, &page, "Owner's", Some(&owner)).await.held_for_review);
23861        assert_eq!(stored_title(&pool, &page).await, "Owner's");
23862        assert!(crate::pending_change::for_page(&pool, id).await.expect("q").is_none());
23863    }
23864
23865    async fn draft_named(pool: &Pool, type_id: i64, slug: &str) -> Page {
23866        let mut p = draft_template(type_id);
23867        slug.clone_into(&mut p.slug);
23868        p.path = "0002/".to_owned();
23869        p.url_path = format!("/{slug}");
23870        p.save(pool).await.expect("page");
23871        p
23872    }
23873}
23874
23875#[cfg(all(test, feature = "sqlite"))]
23876mod partial_save_tests {
23877    //! #903 — a page save writes only what changed.
23878    use super::publish_gate_tests::{bind_review, draft, draft_template, mem_pool, publish_headline_schema};
23879    use super::{apply_page_edit, PageEditActor, PageEditOutcome};
23880    use crate::page::Page;
23881    use rustango::core::Column as _;
23882    use rustango::sql::{FetcherPool as _, Pool, UpdaterPool as _};
23883    use std::collections::HashMap;
23884
23885    async fn edit(pool: &Pool, page: &Page, form: &HashMap<String, String>) -> PageEditOutcome {
23886        let owner = user(pool, "owner", true).await;
23887        edit_as(pool, page, form, &owner).await
23888    }
23889
23890    /// A real user (so the page log and held changes can name them).
23891    async fn user(pool: &Pool, name: &str, superuser: bool) -> PageEditActor {
23892        use rustango::tenancy::auth::User;
23893        let user = match User::objects().where_(User::username.eq(name)).first(pool).await.expect("user") {
23894            Some(u) => u,
23895            None => {
23896                let mut u = User {
23897                    id: rustango::sql::Auto::Unset,
23898                    username: name.to_owned(),
23899                    password_hash: String::new(),
23900                    email: None,
23901                    is_superuser: superuser,
23902                    active: true,
23903                    created_at: chrono::Utc::now(),
23904                    data: serde_json::json!({}),
23905                    password_changed_at: None,
23906                    sessions_revoked_at: None,
23907                };
23908                u.save(pool).await.expect("user");
23909                u
23910            }
23911        };
23912        PageEditActor { id: user.id.get().copied().expect("id"), username: name.to_owned(), is_superuser: superuser }
23913    }
23914
23915    async fn edit_as(pool: &Pool, page: &Page, form: &HashMap<String, String>, actor: &PageEditActor) -> PageEditOutcome {
23916        let invalidator: std::sync::Arc<dyn crate::cache_invalidate::PageCacheInvalidator> =
23917            std::sync::Arc::new(crate::cache_invalidate::Noop);
23918        let id = page.id.get().copied().expect("id");
23919        match apply_page_edit(pool, &rustango::tenancy::TenantSlug::new(1, "t"), &invalidator, None, "", false, id, form, Some(actor))
23920            .await
23921            .expect("save")
23922        {
23923            Ok(o) => o,
23924            Err(_) => panic!("refused"),
23925        }
23926    }
23927
23928    async fn stored(pool: &Pool, page: &Page) -> Page {
23929        Page::objects()
23930            .where_(Page::id.eq(page.id.get().copied().expect("id")))
23931            .first(pool)
23932            .await
23933            .expect("query")
23934            .expect("page")
23935    }
23936
23937    /// (revisions, page-log entries) recorded for `page`.
23938    async fn history(pool: &Pool, page: &Page) -> (usize, usize) {
23939        let id = page.id.get().copied().expect("id");
23940        let revisions = crate::revision::Revision::objects()
23941            .where_(crate::revision::Revision::page_id.eq(id))
23942            .fetch(pool)
23943            .await
23944            .expect("revisions")
23945            .len();
23946        let log = crate::page_log::PageLogEntry::objects()
23947            .where_(crate::page_log::PageLogEntry::page_id.eq(id))
23948            .fetch(pool)
23949            .await
23950            .expect("log")
23951            .len();
23952        (revisions, log)
23953    }
23954
23955    fn at(rfc3339: &str) -> chrono::DateTime<chrono::Utc> {
23956        chrono::DateTime::parse_from_rfc3339(rfc3339).expect("time").with_timezone(&chrono::Utc)
23957    }
23958
23959    /// Re-saving a live page as the editor shows it writes nothing: the
23960    /// timestamps, the history and the tag rows stay as they were. The
23961    /// form's minute-precision schedule, its unchecked boxes, the f32
23962    /// priority and tag spelling all count as unchanged.
23963    #[tokio::test]
23964    async fn a_save_without_changes_writes_nothing() {
23965        let pool = mem_pool().await;
23966        let page = draft(&pool).await;
23967        let mut form = crate::page_form::prefill(&pool, &page).await;
23968        form.insert("status".into(), "published".into());
23969        form.insert("tags".into(), "news, Big Story".into());
23970        form.insert("sitemap_priority".into(), "0.7".into());
23971        form.remove("show_in_menus");
23972        form.remove("robots_index");
23973        assert!(!edit(&pool, &page, &form).await.unchanged);
23974
23975        // Times the form can't post exactly: seconds on the go-live.
23976        let past = at("2020-01-02T03:04:05Z");
23977        let go_live = at("2020-01-01T10:00:30Z");
23978        Page::objects()
23979            .where_(Page::id.eq(page.id.get().copied().expect("id")))
23980            .update()
23981            .set("updated_at", past)
23982            .set("last_published_at", past)
23983            .set("go_live_at", go_live)
23984            .execute_pool(&pool)
23985            .await
23986            .expect("backdate");
23987        let before = stored(&pool, &page).await;
23988        let history_before = history(&pool, &before).await;
23989        let tags_before = crate::page_tag::tags_for_page(&pool, before.id.get().copied().expect("id"))
23990            .await
23991            .expect("tags");
23992
23993        let mut form = crate::page_form::prefill(&pool, &before).await;
23994        form.insert("tags".into(), "Big  Story,news".into());
23995        let out = edit(&pool, &before, &form).await;
23996        assert!(out.unchanged, "nothing changed");
23997
23998        let after = stored(&pool, &before).await;
23999        assert_eq!(after.updated_at.get(), Some(&past));
24000        assert_eq!(after.last_published_at, Some(past));
24001        assert_eq!(after.go_live_at, Some(go_live), "the stored seconds stay");
24002        assert_eq!(history(&pool, &after).await, history_before, "no revision, no log entry");
24003        let tags_after = crate::page_tag::tags_for_page(&pool, after.id.get().copied().expect("id"))
24004            .await
24005            .expect("tags");
24006        let ids = |t: &[crate::page_tag::PageTag]| t.iter().map(|r| r.id.get().copied()).collect::<Vec<_>>();
24007        assert_eq!(ids(&tags_after), ids(&tags_before), "tag rows untouched");
24008    }
24009
24010    /// A save changing one field writes that column (and the change
24011    /// stamp) only: a move, re-order or theme set while the editor had
24012    /// the page open survives.
24013    #[tokio::test]
24014    async fn a_save_writes_only_the_changed_column() {
24015        let pool = mem_pool().await;
24016        let page = draft(&pool).await;
24017        let id = page.id.get().copied().expect("id");
24018        // The editor loads the page...
24019        let mut form = crate::page_form::prefill(&pool, &page).await;
24020        // ...meanwhile it moves, and gets a theme.
24021        let mut theme = crate::theme::tests::fixture_theme();
24022        theme.save(&pool).await.expect("theme");
24023        let theme_id = theme.id.get().copied().expect("theme id");
24024        let past = at("2020-01-02T03:04:05Z");
24025        Page::objects()
24026            .where_(Page::id.eq(id))
24027            .update()
24028            .set("path", "0009/")
24029            .set("sort_order", 7_i32)
24030            .set("theme_id", theme_id)
24031            .set("updated_at", past)
24032            .execute_pool(&pool)
24033            .await
24034            .expect("concurrent move");
24035        let history_before = history(&pool, &page).await;
24036
24037        form.insert("seo_title".into(), "New SEO title".into());
24038        let out = edit(&pool, &page, &form).await;
24039        assert!(!out.unchanged);
24040
24041        let after = stored(&pool, &page).await;
24042        assert_eq!(after.seo_title, "New SEO title");
24043        assert_eq!(after.title, page.title);
24044        assert_eq!(after.path, "0009/", "the move survives");
24045        assert_eq!(after.sort_order, 7);
24046        assert_eq!(after.theme_id, Some(theme_id), "the theme survives");
24047        assert_eq!(after.published_at, None);
24048        assert!(after.updated_at.get().is_some_and(|t| *t > past), "updated_at moves");
24049        let (revisions, log) = history(&pool, &after).await;
24050        assert_eq!((revisions, log), (history_before.0 + 1, history_before.1 + 1));
24051    }
24052
24053    /// The type's content counts: changing only a builder field is a
24054    /// change, and saving the same value again is not.
24055    #[tokio::test]
24056    async fn content_changes_are_detected() {
24057        let pool = mem_pool().await;
24058        let page = draft(&pool).await;
24059        publish_headline_schema(&pool, page.page_type_id).await;
24060        let mut form = crate::page_form::prefill(&pool, &page).await;
24061        form.insert("pb__headline".into(), "Hello".into());
24062        assert!(!edit(&pool, &page, &form).await.unchanged, "a new headline is a change");
24063        let form = crate::page_form::prefill(&pool, &stored(&pool, &page).await).await;
24064        assert_eq!(form.get("pb__headline").map(String::as_str), Some("Hello"));
24065        let before = history(&pool, &page).await;
24066        assert!(edit(&pool, &page, &form).await.unchanged, "the same headline is not");
24067        assert_eq!(history(&pool, &page).await, before);
24068    }
24069
24070    /// Tags are diffed: the kept tag keeps its row, only the difference
24071    /// is written, and the same set again writes nothing.
24072    #[tokio::test]
24073    async fn tags_are_diffed() {
24074        let pool = mem_pool().await;
24075        let id = draft(&pool).await.id.get().copied().expect("id");
24076        let names = |v: &[&str]| v.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
24077        assert!(crate::page_tag::replace_tags(&pool, id, &names(&["a", "b"])).await.expect("tags"));
24078        let row_of = |rows: &[crate::page_tag::PageTag], n: &str| {
24079            rows.iter().find(|r| r.name == n).and_then(|r| r.id.get().copied())
24080        };
24081        let first = crate::page_tag::tags_for_page(&pool, id).await.expect("tags");
24082        assert!(crate::page_tag::replace_tags(&pool, id, &names(&["B", "c"])).await.expect("tags"));
24083        let second = crate::page_tag::tags_for_page(&pool, id).await.expect("tags");
24084        assert_eq!(second.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(), ["b", "c"]);
24085        assert_eq!(row_of(&second, "b"), row_of(&first, "b"), "the kept tag keeps its row");
24086        assert!(!crate::page_tag::replace_tags(&pool, id, &names(&["c", "b", "b"])).await.expect("tags"));
24087        let third = crate::page_tag::tags_for_page(&pool, id).await.expect("tags");
24088        assert_eq!(
24089            third.iter().map(|r| r.id.get().copied()).collect::<Vec<_>>(),
24090            second.iter().map(|r| r.id.get().copied()).collect::<Vec<_>>()
24091        );
24092    }
24093
24094    /// With re-approval on edit, an editor re-saving a live page untouched
24095    /// holds nothing and starts no review; a real change still waits.
24096    #[tokio::test]
24097    async fn an_unchanged_save_is_not_held_for_review() {
24098        let pool = mem_pool().await;
24099        let page = draft(&pool).await;
24100        let id = page.id.get().copied().expect("id");
24101        publish_headline_schema(&pool, page.page_type_id).await;
24102        let mut form = crate::page_form::prefill(&pool, &page).await;
24103        form.insert("status".into(), "published".into());
24104        form.insert("tags".into(), "news".into());
24105        form.insert("pb__headline".into(), "Hello".into());
24106        edit(&pool, &page, &form).await;
24107        bind_review(&pool, page.page_type_id, true).await;
24108        let mia = user(&pool, "mia", false).await;
24109
24110        let live = stored(&pool, &page).await;
24111        let mut form = crate::page_form::prefill(&pool, &live).await;
24112        form.insert("_action".into(), "continue".into());
24113        let out = edit_as(&pool, &live, &form, &mia).await;
24114        assert!(out.unchanged && !out.held_for_review && !out.reapproval_kicked);
24115        assert!(crate::pending_change::for_page(&pool, id).await.expect("q").is_none(), "nothing held");
24116        assert!(crate::workflow::active_state_for_page(&pool, id).await.expect("q").is_none(), "no review");
24117
24118        // A changed tag or headline is a change, and waits.
24119        let mut tagged = form.clone();
24120        tagged.insert("tags".into(), "news,more".into());
24121        assert!(edit_as(&pool, &live, &tagged, &mia).await.held_for_review);
24122        let mut state = crate::workflow::active_state_for_page(&pool, id).await.expect("q").expect("review started");
24123        crate::workflow::cancel(&pool, &mut state, mia.id).await.expect("cancel");
24124        form.insert("pb__headline".into(), "Changed".into());
24125        assert!(edit_as(&pool, &live, &form, &mia).await.held_for_review);
24126        assert!(crate::pending_change::for_page(&pool, id).await.expect("q").is_some());
24127    }
24128
24129    /// A rename after the page moved builds its URL under the parent it
24130    /// has now, and rewrites its children from where they are now.
24131    #[tokio::test]
24132    async fn a_rename_after_a_move_uses_the_current_parent() {
24133        let pool = mem_pool().await;
24134        let a = draft(&pool).await; // "/draft", path 0001/
24135        let type_id = a.page_type_id;
24136        let row = |slug: &str, path: &str, url: &str, parent: Option<i64>, depth: i32| {
24137            let mut p = draft_template(type_id);
24138            slug.clone_into(&mut p.slug);
24139            path.clone_into(&mut p.path);
24140            url.clone_into(&mut p.url_path);
24141            p.parent_id = parent;
24142            p.depth = depth;
24143            p
24144        };
24145        let mut b = row("b", "0002/", "/b", None, 1);
24146        b.save(&pool).await.expect("b");
24147        let mut p = row("p", "0001/0003/", "/draft/p", a.id.get().copied(), 2);
24148        p.save(&pool).await.expect("p");
24149        let mut c = row("c", "0001/0003/0004/", "/draft/p/c", p.id.get().copied(), 3);
24150        c.save(&pool).await.expect("c");
24151
24152        // The editor loads p; then p (with c) moves under b.
24153        let mut form = crate::page_form::prefill(&pool, &p).await;
24154        Page::objects()
24155            .where_(Page::id.eq(p.id.get().copied().expect("id")))
24156            .update()
24157            .set("parent_id", b.id.get().copied().expect("id"))
24158            .set("path", "0002/0003/")
24159            .set("url_path", "/b/p")
24160            .execute_pool(&pool)
24161            .await
24162            .expect("move p");
24163        Page::objects()
24164            .where_(Page::id.eq(c.id.get().copied().expect("id")))
24165            .update()
24166            .set("path", "0002/0003/0004/")
24167            .set("url_path", "/b/p/c")
24168            .execute_pool(&pool)
24169            .await
24170            .expect("move c");
24171
24172        form.insert("slug".into(), "renamed".into());
24173        edit(&pool, &p, &form).await;
24174        let p_after = stored(&pool, &p).await;
24175        assert_eq!(p_after.url_path, "/b/renamed");
24176        assert_eq!(p_after.path, "0002/0003/", "the move stays");
24177        assert_eq!(p_after.parent_id, b.id.get().copied());
24178        assert_eq!(stored(&pool, &c).await.url_path, "/b/renamed/c");
24179    }
24180
24181    /// A schedule posted with seconds is compared to the second: moving
24182    /// it by 30 s is a change. Posted to the minute, the stored seconds
24183    /// are kept.
24184    #[tokio::test]
24185    async fn schedule_precision_follows_the_posted_text() {
24186        let pool = mem_pool().await;
24187        let page = draft(&pool).await;
24188        let id = page.id.get().copied().expect("id");
24189        let future = |t: &str| at(&format!("2099-01-01T{t}Z"));
24190        Page::objects()
24191            .where_(Page::id.eq(id))
24192            .update()
24193            .set("go_live_at", future("10:00:30"))
24194            .set("status", "scheduled")
24195            .execute_pool(&pool)
24196            .await
24197            .expect("schedule");
24198        let page = stored(&pool, &page).await;
24199        let mut form = crate::page_form::prefill(&pool, &page).await;
24200
24201        form.insert("go_live_at".into(), "2099-01-01T10:00Z".into());
24202        assert!(edit(&pool, &page, &form).await.unchanged, "the admin input posts minutes");
24203        assert_eq!(stored(&pool, &page).await.go_live_at, Some(future("10:00:30")));
24204
24205        form.insert("go_live_at".into(), "2099-01-01T10:00:00Z".into());
24206        assert!(!edit(&pool, &page, &form).await.unchanged, "a script posts seconds");
24207        assert_eq!(stored(&pool, &page).await.go_live_at, Some(future("10:00:00")));
24208    }
24209
24210    #[test]
24211    fn same_instant_or_compares_at_the_posted_precision() {
24212        let s = Some(at("2026-01-01T10:00:30Z"));
24213        assert_eq!(super::same_instant_or(s, Some(at("2026-01-01T10:00:00Z")), true), s);
24214        assert_eq!(
24215            super::same_instant_or(s, Some(at("2026-01-01T10:00:00Z")), false),
24216            Some(at("2026-01-01T10:00:00Z"))
24217        );
24218        assert_eq!(super::same_instant_or(s, Some(at("2026-01-01T10:00:30Z")), false), s);
24219        assert_eq!(super::same_instant_or(s, None, true), None);
24220    }
24221
24222    /// The reference index is diffed the same way, duplicates included.
24223    #[tokio::test]
24224    async fn references_are_diffed() {
24225        use crate::reference_index::{reindex_source, Reference, ReferenceIndex, KIND_MEDIA, KIND_PAGE};
24226        let pool = mem_pool().await;
24227        let id = draft(&pool).await.id.get().copied().expect("id");
24228        let refs = |ids: &[i64]| {
24229            ids.iter()
24230                .map(|m| Reference { to_kind: KIND_MEDIA, to_id: *m, field_path: "body".to_owned() })
24231                .collect::<Vec<_>>()
24232        };
24233        let rows = |pool: Pool| async move {
24234            let mut v: Vec<(i64, Option<i64>)> = ReferenceIndex::objects()
24235                .where_(ReferenceIndex::from_id.eq(id))
24236                .fetch(&pool)
24237                .await
24238                .expect("refs")
24239                .into_iter()
24240                .map(|r| (r.to_id, r.id.get().copied()))
24241                .collect();
24242            v.sort_unstable();
24243            v
24244        };
24245        reindex_source(&pool, KIND_PAGE, id, refs(&[1, 2, 2])).await.expect("index");
24246        let first = rows(pool.clone()).await;
24247        reindex_source(&pool, KIND_PAGE, id, refs(&[2, 3, 2])).await.expect("index");
24248        let second = rows(pool.clone()).await;
24249        assert_eq!(second.iter().map(|r| r.0).collect::<Vec<_>>(), [2, 2, 3]);
24250        assert_eq!(&second[..2], &first[1..], "the kept references keep their rows");
24251        reindex_source(&pool, KIND_PAGE, id, refs(&[3, 2, 2])).await.expect("index");
24252        assert_eq!(rows(pool.clone()).await, second, "the same set writes nothing");
24253    }
24254
24255    // #903 phase 2 — concurrent editors.
24256
24257    /// The edit form for `page` as loaded, carrying its baseline.
24258    async fn loaded_form(pool: &Pool, page: &Page) -> HashMap<String, String> {
24259        let mut form = crate::page_form::prefill(pool, page).await;
24260        form.insert(
24261            crate::page_baseline::BASELINE_KEY.into(),
24262            crate::page_baseline::Baseline::of("t", page).token(),
24263        );
24264        form
24265    }
24266
24267    /// Someone else saves `column = value` while the form is open.
24268    async fn concurrent_set(pool: &Pool, page: &Page, column: &'static str, value: impl Into<rustango::core::SqlValue>) {
24269        Page::objects()
24270            .where_(Page::id.eq(page.id.get().copied().expect("id")))
24271            .update()
24272            .set(column, value.into())
24273            .execute_pool(pool)
24274            .await
24275            .expect("concurrent save");
24276    }
24277
24278    async fn try_edit(
24279        pool: &Pool,
24280        page: &Page,
24281        form: &HashMap<String, String>,
24282        actor: Option<&PageEditActor>,
24283    ) -> Result<PageEditOutcome, super::PageEditRefusal> {
24284        let invalidator: std::sync::Arc<dyn crate::cache_invalidate::PageCacheInvalidator> =
24285            std::sync::Arc::new(crate::cache_invalidate::Noop);
24286        let id = page.id.get().copied().expect("id");
24287        apply_page_edit(pool, &rustango::tenancy::TenantSlug::new(1, "t"), &invalidator, None, "", false, id, form, actor)
24288            .await
24289            .expect("save")
24290    }
24291
24292    /// Two editors changing different fields both keep their edits: the
24293    /// field this editor left as loaded isn't written back.
24294    #[tokio::test]
24295    async fn edits_to_different_fields_both_survive() {
24296        let pool = mem_pool().await;
24297        let page = draft(&pool).await;
24298        let mut form = loaded_form(&pool, &page).await;
24299        concurrent_set(&pool, &page, "seo_title", "Theirs").await;
24300        form.insert("og_title".into(), "Mine".into());
24301        let out = edit(&pool, &page, &form).await;
24302        assert!(!out.unchanged);
24303        let after = stored(&pool, &page).await;
24304        assert_eq!(after.seo_title, "Theirs", "their edit survives");
24305        assert_eq!(after.og_title, "Mine", "mine is written");
24306    }
24307
24308    /// The same field changed on both sides is refused with both values,
24309    /// and nothing is written.
24310    #[tokio::test]
24311    async fn the_same_field_changed_twice_is_a_conflict() {
24312        let pool = mem_pool().await;
24313        let page = draft(&pool).await;
24314        let mut form = loaded_form(&pool, &page).await;
24315        concurrent_set(&pool, &page, "title", "Their title").await;
24316        let before = stored(&pool, &page).await;
24317        let history_before = history(&pool, &before).await;
24318        form.insert("title".into(), "My title".into());
24319        form.insert("og_title".into(), "Mine".into());
24320        let owner = user(&pool, "owner", true).await;
24321        match try_edit(&pool, &page, &form, Some(&owner)).await {
24322            Err(super::PageEditRefusal::Conflict { conflicts, page: shown }) => {
24323                assert_eq!(conflicts.len(), 1);
24324                assert_eq!(conflicts[0].field, "title");
24325                assert_eq!(conflicts[0].theirs, "Their title");
24326                assert_eq!(conflicts[0].yours, "My title");
24327                assert_eq!(shown.title, "My title", "the form shows the editor's value");
24328                assert_eq!(shown.og_title, "Mine");
24329            }
24330            Ok(_) => panic!("saved over a concurrent change"),
24331            Err(_) => panic!("refused for another reason"),
24332        }
24333        let after = stored(&pool, &page).await;
24334        assert_eq!(after.title, "Their title");
24335        assert_eq!(after.og_title, before.og_title, "nothing written, not even the other field");
24336        assert_eq!(after.updated_at.get(), before.updated_at.get());
24337        assert_eq!(history(&pool, &after).await, history_before);
24338
24339        // Saved again from the re-shown form (a fresh baseline), the
24340        // editor's value goes in.
24341        let mut again = loaded_form(&pool, &after).await;
24342        again.insert("title".into(), "My title".into());
24343        assert!(!edit(&pool, &after, &again).await.unchanged);
24344        assert_eq!(stored(&pool, &page).await.title, "My title");
24345    }
24346
24347    /// A save with no actor (an approved held change) has nobody to show a
24348    /// conflict to: its values win.
24349    #[tokio::test]
24350    async fn a_save_without_an_actor_resolves_conflicts_to_its_values() {
24351        let pool = mem_pool().await;
24352        let page = draft(&pool).await;
24353        let mut form = loaded_form(&pool, &page).await;
24354        concurrent_set(&pool, &page, "title", "Their title").await;
24355        form.insert("title".into(), "Approved title".into());
24356        assert!(try_edit(&pool, &page, &form, None).await.is_ok());
24357        assert_eq!(stored(&pool, &page).await.title, "Approved title");
24358    }
24359
24360    /// A post without a baseline (API, MCP, an old form) saves as before:
24361    /// the posted values win.
24362    #[tokio::test]
24363    async fn a_save_without_a_baseline_keeps_last_write_wins() {
24364        let pool = mem_pool().await;
24365        let page = draft(&pool).await;
24366        let mut form = crate::page_form::prefill(&pool, &page).await;
24367        concurrent_set(&pool, &page, "seo_title", "Theirs").await;
24368        concurrent_set(&pool, &page, "title", "Their title").await;
24369        form.insert("title".into(), "My title".into());
24370        assert!(!edit(&pool, &page, &form).await.unchanged);
24371        let after = stored(&pool, &page).await;
24372        assert_eq!(after.title, "My title");
24373        assert_eq!(after.seo_title, page.seo_title, "the loaded value is written back");
24374    }
24375
24376    /// A tampered baseline, or one minted for another page or tenant, is ignored:
24377    /// the save goes ahead as one without a baseline.
24378    #[tokio::test]
24379    async fn a_tampered_baseline_is_ignored() {
24380        let pool = mem_pool().await;
24381        let page = draft(&pool).await;
24382        let other = {
24383            let mut p = page.clone();
24384            p.id = rustango::sql::Auto::Set(page.id.get().copied().expect("id") + 1);
24385            p
24386        };
24387        let token = crate::page_baseline::Baseline::of("t", &page).token();
24388        let tampered = {
24389            let mut t = token.into_bytes();
24390            let at = t.len() - 1;
24391            t[at] = if t[at] == b'0' { b'1' } else { b'0' };
24392            String::from_utf8(t).expect("ascii")
24393        };
24394        for bad in [
24395            tampered,
24396            crate::page_baseline::Baseline::of("t", &other).token(),
24397            crate::page_baseline::Baseline::of("another-tenant", &page).token(),
24398            "garbage".to_owned(),
24399        ] {
24400            let current = stored(&pool, &page).await;
24401            let mut form = crate::page_form::prefill(&pool, &current).await;
24402            form.insert(crate::page_baseline::BASELINE_KEY.into(), bad);
24403            concurrent_set(&pool, &page, "title", "Their title").await;
24404            form.insert("title".into(), "My title".into());
24405            let owner = user(&pool, "owner", true).await;
24406            assert!(try_edit(&pool, &page, &form, Some(&owner)).await.is_ok(), "no conflict without a valid baseline");
24407            assert_eq!(stored(&pool, &page).await.title, "My title");
24408        }
24409    }
24410
24411    /// The scheduler published the page while the form was open: saving
24412    /// another field with the baseline keeps it published.
24413    #[tokio::test]
24414    async fn a_page_the_scheduler_published_stays_published() {
24415        let pool = mem_pool().await;
24416        let page = draft(&pool).await;
24417        let id = page.id.get().copied().expect("id");
24418        let soon = chrono::Utc::now() + chrono::Duration::hours(1);
24419        Page::objects()
24420            .where_(Page::id.eq(id))
24421            .update()
24422            .set("status", "scheduled")
24423            .set("go_live_at", soon)
24424            .execute_pool(&pool)
24425            .await
24426            .expect("schedule");
24427        let loaded = stored(&pool, &page).await;
24428        let mut form = loaded_form(&pool, &loaded).await;
24429        // The sweep runs: go-live passed, the page is live.
24430        let past = chrono::Utc::now() - chrono::Duration::minutes(5);
24431        Page::objects()
24432            .where_(Page::id.eq(id))
24433            .update()
24434            .set("status", "published")
24435            .set("go_live_at", past)
24436            .execute_pool(&pool)
24437            .await
24438            .expect("publish");
24439        form.insert("seo_title".into(), "Edited".into());
24440        assert!(!edit(&pool, &loaded, &form).await.unchanged);
24441        let after = stored(&pool, &page).await;
24442        assert_eq!(after.status, "published");
24443        assert_eq!(after.go_live_at.map(|t| t.timestamp() / 60), Some(past.timestamp() / 60));
24444        assert_eq!(after.seo_title, "Edited");
24445    }
24446
24447    /// Checkboxes post nothing when unticked: a box this editor left as
24448    /// loaded keeps another editor's change, one this editor unticked is
24449    /// written, and both unticking the same box is no conflict (a two-value
24450    /// field can't be changed to different values from one baseline).
24451    #[tokio::test]
24452    async fn checkboxes_merge_three_ways() {
24453        let pool = mem_pool().await;
24454        let page = draft(&pool).await;
24455        let owner = user(&pool, "owner", true).await;
24456        assert!(page.robots_index && page.show_in_menus);
24457
24458        // They untick one box, I untick the other: both stand.
24459        let mut form = loaded_form(&pool, &page).await;
24460        assert_eq!(form.get("robots_index").map(String::as_str), Some("on"));
24461        concurrent_set(&pool, &page, "robots_index", false).await;
24462        form.remove("show_in_menus");
24463        assert!(try_edit(&pool, &page, &form, Some(&owner)).await.is_ok());
24464        let after = stored(&pool, &page).await;
24465        assert!(!after.robots_index, "their unticking survives the box I left ticked");
24466        assert!(!after.show_in_menus, "my unticking is written");
24467
24468        // They tick one box, I tick the other: both stand.
24469        let mut form = loaded_form(&pool, &after).await;
24470        concurrent_set(&pool, &page, "show_in_menus", true).await;
24471        form.insert("robots_index".into(), "on".into());
24472        assert!(try_edit(&pool, &page, &form, Some(&owner)).await.is_ok());
24473        let after = stored(&pool, &page).await;
24474        assert!(after.robots_index && after.show_in_menus);
24475
24476        // Both untick the same box: the same change, no conflict.
24477        let mut form = loaded_form(&pool, &after).await;
24478        concurrent_set(&pool, &page, "robots_index", false).await;
24479        form.remove("robots_index");
24480        assert!(try_edit(&pool, &page, &form, Some(&owner)).await.is_ok(), "same change on both sides");
24481        assert!(!stored(&pool, &page).await.robots_index);
24482    }
24483
24484    /// Another editor renames the page (and so its subtree's URLs) while
24485    /// this editor changes another field: the rename stands, and this save
24486    /// moves no URL.
24487    #[tokio::test]
24488    async fn a_concurrent_rename_survives_an_edit_to_another_field() {
24489        let pool = mem_pool().await;
24490        let page = draft(&pool).await;
24491        let pid = page.id.get().copied().expect("id");
24492        let mut child = draft_template(page.page_type_id);
24493        child.slug = "child".to_owned();
24494        child.path = "0001/0001/".to_owned();
24495        child.url_path = "/draft/child".to_owned();
24496        child.depth = 2;
24497        child.parent_id = Some(pid);
24498        child.save(&pool).await.expect("child");
24499        let mut mine = loaded_form(&pool, &page).await;
24500
24501        let mut theirs = crate::page_form::prefill(&pool, &page).await;
24502        theirs.insert("slug".into(), "renamed".into());
24503        assert!(!edit(&pool, &page, &theirs).await.unchanged);
24504        assert_eq!(stored(&pool, &child).await.url_path, "/renamed/child");
24505
24506        mine.insert("og_title".into(), "Mine".into());
24507        assert!(!edit(&pool, &page, &mine).await.unchanged);
24508        let after = stored(&pool, &page).await;
24509        assert_eq!(after.slug, "renamed");
24510        assert_eq!(after.url_path, "/renamed");
24511        assert_eq!(after.og_title, "Mine");
24512        assert_eq!(stored(&pool, &child).await.url_path, "/renamed/child", "descendants untouched");
24513    }
24514
24515    /// Autosave writes a field only when this editor changed it and nobody
24516    /// else did, and hands back the baseline with what it wrote.
24517    #[tokio::test]
24518    async fn autosave_merges_and_returns_the_rebased_baseline() {
24519        let pool = mem_pool().await;
24520        let page = draft(&pool).await;
24521        let id = page.id.get().copied().expect("id");
24522        let mut form = loaded_form(&pool, &page).await;
24523        concurrent_set(&pool, &page, "seo_title", "Theirs").await;
24524        form.insert("title".into(), "Typed".into());
24525        form.insert("seo_description".into(), "Mine".into());
24526        let res = super::autosave_page(&pool, "t", None, id, &form).await.expect("autosave");
24527        assert_eq!(res.status(), axum::http::StatusCode::NO_CONTENT);
24528        let token = res
24529            .headers()
24530            .get(crate::page_baseline::BASELINE_HEADER)
24531            .and_then(|v| v.to_str().ok())
24532            .expect("rebased baseline")
24533            .to_owned();
24534        let after = stored(&pool, &page).await;
24535        assert_eq!(after.title, "Typed");
24536        assert_eq!(after.seo_description, "Mine");
24537        assert_eq!(after.seo_title, "Theirs", "their field isn't overwritten with the loaded value");
24538        let rebased = crate::page_baseline::Baseline::parse(&token, "t", id).expect("verifies");
24539        assert!(rebased.matches("title", "Typed"));
24540        assert!(!rebased.matches("seo_title", "Theirs"), "a field autosave didn't write keeps its baseline");
24541
24542        // A field both changed: autosave leaves it for the real save.
24543        form.insert(crate::page_baseline::BASELINE_KEY.into(), token);
24544        concurrent_set(&pool, &page, "title", "Other").await;
24545        form.insert("title".into(), "Typed more".into());
24546        let res = super::autosave_page(&pool, "t", None, id, &form).await.expect("autosave");
24547        assert_eq!(res.status(), axum::http::StatusCode::NO_CONTENT);
24548        assert_eq!(stored(&pool, &page).await.title, "Other");
24549
24550        // The editor's own save after an autosave is no conflict.
24551        let mut form = loaded_form(&pool, &stored(&pool, &page).await).await;
24552        form.insert("title".into(), "Draft 2".into());
24553        let res = super::autosave_page(&pool, "t", None, id, &form).await.expect("autosave");
24554        let token = res.headers().get(crate::page_baseline::BASELINE_HEADER).and_then(|v| v.to_str().ok()).expect("header").to_owned();
24555        form.insert(crate::page_baseline::BASELINE_KEY.into(), token);
24556        form.insert("title".into(), "Draft 3".into());
24557        let owner = user(&pool, "owner", true).await;
24558        assert!(try_edit(&pool, &page, &form, Some(&owner)).await.is_ok(), "no conflict with my own autosave");
24559        assert_eq!(stored(&pool, &page).await.title, "Draft 3");
24560
24561        // Without a baseline: written as posted, no header.
24562        let mut plain = crate::page_form::prefill(&pool, &stored(&pool, &page).await).await;
24563        plain.insert("title".into(), "Plain".into());
24564        let res = super::autosave_page(&pool, "t", None, id, &plain).await.expect("autosave");
24565        assert!(res.headers().get(crate::page_baseline::BASELINE_HEADER).is_none());
24566        assert_eq!(stored(&pool, &page).await.title, "Plain");
24567    }
24568
24569    /// The refused save comes back as the edit form with status 409 and
24570    /// the editor's values: page fields, tags, categories, the type's own
24571    /// fields and page-builder values, all escaped.
24572    #[tokio::test]
24573    async fn the_conflict_screen_shows_the_editors_values() {
24574        let pool = mem_pool().await;
24575        crate::error_pages::ensure_table(&pool).await.expect("error page table");
24576        let page = draft(&pool).await;
24577        let id = page.id.get().copied().expect("id");
24578        crate::page_type_model::PageType::objects()
24579            .where_(crate::page_type_model::PageType::id.eq(page.page_type_id))
24580            .update()
24581            .set("type_name", crate::error_pages::TYPE_NAME.to_owned())
24582            .execute_pool(&pool)
24583            .await
24584            .expect("error page type");
24585        publish_headline_schema(&pool, page.page_type_id).await;
24586        crate::category::upsert_taxonomy(&pool, &crate::category::CategoryTaxonomy).await.expect("taxonomy");
24587        let tax = crate::category::find_taxonomy(&pool, "category").await.expect("q").expect("row");
24588        let mut cats = Vec::new();
24589        for name in ["Mugs", "Plates"] {
24590            let c = crate::category::model::create(
24591                &pool,
24592                tax.id.get().copied().expect("id"),
24593                crate::category::NewCategory {
24594                    name: name.to_owned(),
24595                    slug: String::new(),
24596                    description: String::new(),
24597                    parent_id: None,
24598                    featured_image_id: None,
24599                    thumbnail_id: None,
24600                },
24601            )
24602            .await
24603            .expect("category");
24604            cats.push(c.id.get().copied().expect("id"));
24605        }
24606
24607        let mut form = loaded_form(&pool, &page).await;
24608        concurrent_set(&pool, &page, "title", "Their title").await;
24609        form.insert("title".into(), "<script>alert(1)</script>".into());
24610        form.insert("tags".into(), "<script>tag</script>, pottery".into());
24611        form.insert("categories".into(), format!("[\"{}\"]", cats[1]));
24612        form.insert("status_code".into(), "503".into());
24613        form.insert("pb__headline".into(), "My headline".into());
24614        let owner = user(&pool, "owner", true).await;
24615        let (conflicts, shown) = match try_edit(&pool, &page, &form, Some(&owner)).await {
24616            Err(super::PageEditRefusal::Conflict { conflicts, page }) => (conflicts, page),
24617            _ => panic!("expected a conflict"),
24618        };
24619        let mut tera = tera::Tera::default();
24620        crate::admin::register_templates(&mut tera).expect("templates");
24621        let state = crate::admin::AdminState {
24622            tera: std::sync::Arc::new(tera),
24623            signing_secret: std::sync::Arc::new(Vec::new()),
24624            cache_invalidator: crate::cache_invalidate::noop(),
24625            mailer: None,
24626            mailer_from: std::sync::Arc::new(String::new()),
24627        };
24628        let mut org = rustango::tenancy::Org::new("t");
24629        org.id = rustango::sql::Auto::Set(1);
24630        let res = super::render_page_edit_form(
24631            &state,
24632            &pool,
24633            &org,
24634            &axum::http::HeaderMap::new(),
24635            None,
24636            id,
24637            super::EditQuery::default(),
24638            Some(super::EditConflict { conflicts, page: *shown, form }),
24639        )
24640        .await
24641        .expect("render");
24642        assert_eq!(res.status(), axum::http::StatusCode::CONFLICT);
24643        let bytes = axum::body::to_bytes(res.into_body(), usize::MAX).await.expect("body");
24644        let html = String::from_utf8(bytes.to_vec()).expect("utf8");
24645        assert!(html.contains("data-edit-conflict"), "conflict notice");
24646        assert!(html.contains("data-conflict-field=\"title\""));
24647        assert!(html.contains("Their title"), "the saved value is listed");
24648        assert!(!html.contains("<script>alert(1)") && !html.contains("<script>tag"), "posted markup is escaped");
24649        assert!(html.contains("&lt;script&gt;alert(1)"), "my title, escaped");
24650        assert!(html.contains("&lt;script&gt;tag"), "my tags, escaped");
24651        assert!(html.contains("pottery"));
24652        assert!(
24653            html.contains(&format!("value=\"{}\" data-multivalue-option checked", cats[1])),
24654            "my category is ticked"
24655        );
24656        assert!(
24657            !html.contains(&format!("value=\"{}\" data-multivalue-option checked", cats[0])),
24658            "the other isn't"
24659        );
24660        assert!(html.contains("My headline"), "my page-builder value");
24661        let fresh = crate::page_baseline::Baseline::of("t", &stored(&pool, &page).await).token();
24662        assert!(html.contains(&fresh), "a baseline of the page as stored now");
24663        let select = html.find("name=\"status_code\"").expect("status code select");
24664        let after_select = &html[select..];
24665        let opt503 = after_select.find("value=\"503\"").expect("503 option");
24666        assert!(after_select[opt503..opt503 + 40].contains("selected"), "my extension value: {}", &after_select[opt503..opt503 + 40]);
24667    }
24668}
24669
24670#[cfg(test)]
24671mod active_upload_tests {
24672    use super::refuse_active_upload;
24673
24674    #[test]
24675    fn page_like_types_are_refused_and_media_is_not() {
24676        for bad in ["text/html", "application/xhtml+xml", "text/javascript", "application/xml"] {
24677            assert!(refuse_active_upload(bad).is_err(), "{bad}");
24678        }
24679        for ok in ["image/png", "image/svg+xml", "application/pdf", "text/plain", "video/mp4"] {
24680            assert!(refuse_active_upload(ok).is_ok(), "{ok}");
24681        }
24682    }
24683}
24684
24685#[cfg(all(test, feature = "sqlite"))]
24686mod bounded_list_tests {
24687    //! #629 — the counts and lookups that replaced whole-table reads.
24688    use super::{counts_by, latest_page_activity};
24689    use crate::page::{Page, PageStatus};
24690    use rustango::core::{Column as _, Model as _};
24691    use rustango::sql::{Auto, Pool};
24692
24693    async fn mem_pool() -> Pool {
24694        let pool = Pool::connect("sqlite::memory:").await.expect("mem pool");
24695        for schema in [
24696            &crate::PageType::SCHEMA,
24697            &Page::SCHEMA,
24698            &crate::media::Media::SCHEMA,
24699            &crate::theme::Theme::SCHEMA,
24700        ] {
24701            let ddl = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(
24702                pool.dialect(),
24703                schema,
24704            );
24705            for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
24706                rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
24707                    .await
24708                    .expect("ddl");
24709            }
24710        }
24711        pool
24712    }
24713
24714    async fn page_type(pool: &Pool, name: &str) -> i64 {
24715        let mut pt = crate::PageType {
24716            id: Auto::Unset,
24717            app_label: "cms".to_owned(),
24718            type_name: name.to_owned(),
24719            verbose_name: name.to_owned(),
24720            default_template: "page.html".to_owned(),
24721            view_mode: "auto".to_owned(),
24722            is_creatable: true,
24723            allowed_parent_types: serde_json::json!([]),
24724            allowed_child_types: serde_json::json!([]),
24725            workflow: String::new(),
24726            created_at: Auto::Unset,
24727            updated_at: Auto::Unset,
24728        };
24729        pt.save(pool).await.expect("page type");
24730        pt.id.get().copied().expect("type id")
24731    }
24732
24733    async fn page(
24734        pool: &Pool,
24735        type_id: i64,
24736        n: i64,
24737        published_at: Option<chrono::DateTime<chrono::Utc>>,
24738    ) {
24739        let mut p = Page {
24740            id: Auto::Unset,
24741            page_type_id: type_id,
24742            title: format!("p{n}"),
24743            slug: format!("p{n}"),
24744            path: format!("{n:04x}/"),
24745            url_path: format!("/p{n}"),
24746            preview_path: String::new(),
24747            template_override: String::new(),
24748            depth: 1,
24749            parent_id: None,
24750            locale_variant_of: None,
24751            alias_of: None,
24752            theme_id: None,
24753            sort_order: 0,
24754            status: PageStatus::Published.as_str().to_owned(),
24755            published_at,
24756            last_published_at: None,
24757            go_live_at: None,
24758            expire_at: None,
24759            seo_title: String::new(),
24760            seo_description: String::new(),
24761            robots_index: true,
24762            sitemap_priority: 0.5,
24763            show_in_menus: true,
24764            og_title: String::new(),
24765            og_description: String::new(),
24766            og_image_media_id: None,
24767            twitter_card: "summary".to_owned(),
24768            notification_pre_published_sent: false,
24769            created_at: Auto::Unset,
24770            updated_at: Auto::Unset,
24771        };
24772        p.save(pool).await.expect("page");
24773    }
24774
24775    #[tokio::test]
24776    async fn counts_by_groups_in_sql_and_honours_the_filter() {
24777        let pool = mem_pool().await;
24778        let (a, b) = (page_type(&pool, "A").await, page_type(&pool, "B").await);
24779        for (n, t) in [(1, a), (2, a), (3, a), (4, b)] {
24780            page(&pool, t, n, None).await;
24781        }
24782        let all = counts_by(&pool, Page::objects(), "page_type_id").await.expect("counts");
24783        assert_eq!(all.get(&a), Some(&3));
24784        assert_eq!(all.get(&b), Some(&1));
24785        assert_eq!(all.len(), 2);
24786        let some = counts_by(&pool, Page::objects().where_(Page::slug.ne("p1".to_owned())), "page_type_id")
24787            .await
24788            .expect("counts");
24789        assert_eq!(some.get(&a), Some(&2));
24790    }
24791
24792    #[tokio::test]
24793    async fn latest_activity_is_the_newest_publish_or_creation() {
24794        let pool = mem_pool().await;
24795        let (t, empty) = (page_type(&pool, "A").await, page_type(&pool, "B").await);
24796        let old = chrono::Utc::now() - chrono::Duration::days(400);
24797        page(&pool, t, 1, Some(old)).await;
24798        page(&pool, t, 2, Some(old + chrono::Duration::days(3))).await;
24799        assert_eq!(
24800            latest_page_activity(&pool, t).await.expect("latest"),
24801            Some(old + chrono::Duration::days(3)),
24802        );
24803        // A never-published page counts by its creation, which is newer.
24804        page(&pool, t, 3, None).await;
24805        let latest = latest_page_activity(&pool, t).await.expect("latest").expect("some");
24806        assert!(latest > old + chrono::Duration::days(300));
24807        assert_eq!(latest_page_activity(&pool, empty).await.expect("latest"), None);
24808    }
24809}