28.2 KiB · text History 263b40b
use axum::{
    extract::{Form, Path, Query, State},
    http::{HeaderMap, StatusCode},
    response::{Html, IntoResponse, Redirect, Response},
};
use chrono::Utc;
use minijinja::context;
use sea_orm::*;
use serde::{Deserialize, Serialize};
use tracing::error;
use uuid::Uuid;

use crate::category_tree::{color_widget_css, CategoryTree, MAX_DEPTH};
use crate::moderation::{self, Actor};
use crate::policy::{PostingRule, ReactionRule};
use crate::entities::categories;
use crate::middleware::UserContext;
use crate::AppState;

const DEFAULT_COLOR: &str = "#0088CC";

fn require_staff(u: &UserContext) -> Result<(), StatusCode> {
    if u.user.is_staff {
        Ok(())
    } else {
        Err(StatusCode::FORBIDDEN)
    }
}

/// Lowercase ASCII slug: alphanumerics kept, runs of anything else collapse to
/// a single hyphen, leading/trailing hyphens trimmed.
fn slugify(s: &str) -> String {
    let mut out = String::new();
    let mut prev_dash = false;
    for ch in s.trim().chars() {
        if ch.is_ascii_alphanumeric() {
            out.push(ch.to_ascii_lowercase());
            prev_dash = false;
        } else if !out.is_empty() && !prev_dash {
            out.push('-');
            prev_dash = true;
        }
    }
    while out.ends_with('-') {
        out.pop();
    }
    out
}

#[derive(Debug, Deserialize)]
pub struct CategoryForm {
    pub name: String,
    pub slug: Option<String>,
    pub description: Option<String>,
    pub color: Option<String>,
    pub position: Option<i32>,
    /// Empty string / absent = top level; otherwise a parent category UUID.
    pub parent_id: Option<String>,
    /// "public" / empty = anyone; "0".."4" = min trust level to view.
    pub min_trust_level: Option<String>,
    /// Who may start topics / reply: "viewers", "0".."4", "staff"
    /// ([`PostingRule::parse`]). Absent on a new subcategory = its parent's.
    pub topic_rule: Option<String>,
    pub reply_rule: Option<String>,
    /// `all`, `none` or `some` (then the `rk_<key>=on` checkboxes); absent or
    /// `inherit` on a new subcategory = its parent's.
    pub reactions: Option<String>,
    /// The `rk_<key>` checkboxes (urlencoded forms have no lists).
    #[serde(flatten)]
    pub extra: std::collections::HashMap<String, String>,
}

/// The reactions field: `inherit` keeps `inherit`; `some` needs at least
/// one known key.
fn parse_reactions(
    form: &CategoryForm,
    inherit: ReactionRule,
    known: &[String],
) -> Result<ReactionRule, &'static str> {
    match form.reactions.as_deref().map(str::trim) {
        None | Some("inherit") => Ok(inherit),
        Some("all") => Ok(ReactionRule::All),
        Some("none") => Ok(ReactionRule::Off),
        Some("some") => {
            let keys: Vec<String> = known
                .iter()
                .filter(|k| form.extra.get(&format!("rk_{k}")).is_some_and(|v| !v.is_empty()))
                .cloned()
                .collect();
            if keys.is_empty() {
                Err("Pick at least one reaction, or choose none.")
            } else {
                Ok(ReactionRule::Only(keys))
            }
        }
        Some(_) => Err("Unknown reactions setting."),
    }
}

/// Every reaction type's key, emoji and whether it's active, for the forms.
async fn reaction_choices(state: &AppState) -> Result<Vec<(String, String, bool)>, StatusCode> {
    Ok(crate::entities::reaction_types::Entity::find()
        .order_by_asc(crate::entities::reaction_types::Column::Position)
        .all(state.db.as_ref())
        .await
        .map_err(ise("load reaction types"))?
        .into_iter()
        .map(|t| (t.key, t.emoji, t.is_active))
        .collect())
}

/// A posting-rule field: absent = `inherit`; present but unreadable = an
/// error for the form.
fn parse_rule(raw: &Option<String>, inherit: Option<i32>) -> Result<Option<i32>, &'static str> {
    match raw.as_deref().map(str::trim) {
        None | Some("inherit") => Ok(inherit),
        Some(s) => PostingRule::parse(s).map(PostingRule::to_column).ok_or("Unknown posting rule."),
    }
}

/// "view TL1+ · topics staff · replies TL3+" for the moderation log.
fn reactions_summary(r: &ReactionRule) -> String {
    match r {
        ReactionRule::All => "reactions: all".into(),
        ReactionRule::Off => "reactions: off".into(),
        ReactionRule::Only(k) => format!("reactions: {}", k.join(", ")),
    }
}

fn permissions_summary(min_trust: Option<i32>, topic: Option<i32>, reply: Option<i32>) -> String {
    let view = match min_trust {
        None => "public".to_string(),
        Some(0) => "signed-in".into(),
        Some(n) => format!("TL{n}+"),
    };
    let rule = |v| PostingRule::from_column(v).badge().unwrap_or_else(|| "anyone who can read".into());
    format!("read: {view} · start topics: {} · reply: {}", rule(topic), rule(reply))
}

/// The posting-rule choices: form value, label.
const RULE_OPTIONS: [(&str, &str); 7] = [
    ("viewers", "Anyone who can read it"),
    ("0", "Signed-in users"),
    ("1", "Trust level 1+ (Basic)"),
    ("2", "Trust level 2+ (Member)"),
    ("3", "Trust level 3+ (Regular)"),
    ("4", "Trust level 4 (Leader)"),
    ("staff", "Staff only"),
];

fn parse_min_trust(raw: &Option<String>) -> Option<i32> {
    match raw.as_deref().map(str::trim) {
        None | Some("") | Some("public") => None,
        Some(s) => s.parse::<i32>().ok().map(|n| n.clamp(0, 4)),
    }
}

#[derive(Serialize)]
struct ParentOption {
    id: Uuid,
    name: String,
    depth: i32,
}

#[derive(Debug, Deserialize)]
pub struct ManageQuery {
    /// `classic` or `focus`; see [`super::focus::resolve_view`].
    pub view: Option<String>,
}

/// Manage categories (staff only): an indented table in Classic, nested
/// cards in Focus ([`manage_focus`]).
pub async fn manage_categories(
    State(state): State<AppState>,
    Query(q): Query<ManageQuery>,
    headers: HeaderMap,
    user: UserContext,
) -> Result<Response, StatusCode> {
    require_staff(&user)?;
    let view = super::focus::view_for(&state, q.view.as_deref(), Some(&user), &headers);
    let page = if view.mode == super::focus::ViewMode::Focus {
        manage_focus(&state, &user).await?
    } else {
        manage_classic(&state, &user).await?
    };
    Ok(view.respond(page))
}

async fn manage_classic(state: &AppState, user: &UserContext) -> Result<Html<String>, StatusCode> {
    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load categories"))?;
    #[derive(Serialize)]
    struct Row {
        id: Uuid,
        name: String,
        slug: String,
        color: String,
        position: i32,
        depth: i32,
        min_trust: Option<i32>,
        rules: Vec<String>,
    }
    let rows: Vec<Row> = tree
        .flatten()
        .into_iter()
        .filter_map(|(id, depth)| {
            tree.get(id).map(|c| Row {
                id: c.id,
                name: c.name.clone(),
                slug: c.slug.clone(),
                color: c.color.clone(),
                position: c.position,
                depth,
                min_trust: c.min_trust_level,
                rules: super::forum::posting_badges(c),
            })
        })
        .collect();

    render(state, "admin/categories.html", context! {
        title => "Manage categories",
        app_name => state.config.app_name,
        user => user.user.clone(),
        categories => rows,
    })
}

// --- Focus: nested cards with inline add (pin_flip's board and its `+`) ---

/// Colours offered to a new category, picked by how many siblings it has so
/// neighbours differ. The classic form keeps [`DEFAULT_COLOR`].
const NEW_COLORS: [&str; 10] = [
    "#0088CC", "#12A89D", "#3AB54A", "#F7941D", "#E45735",
    "#BF1E2E", "#92278F", "#652D90", "#25AAE2", "#8C6238",
];

/// A category card and everything nested in it.
#[derive(Serialize)]
struct CardNode {
    id: Uuid,
    name: String,
    slug: String,
    description: Option<String>,
    widget_bg: String,
    min_trust: Option<i32>,
    /// Posting-rule badges ("Staff start topics").
    rules: Vec<String>,
    depth: i32,
    /// Live topics in this category alone, and with everything under it.
    own_count: u64,
    count: u64,
    children: Vec<CardNode>,
    /// The `+` inside this card: absent at [`MAX_DEPTH`].
    add: Option<AddSlot>,
    /// Just added inline (highlighted once).
    fresh: bool,
}

/// A `+` (or, `adding`, its inline form) for a new category under `parent`.
#[derive(Serialize)]
struct AddSlot {
    /// Empty for the top level (the form's `parent_id`).
    parent: String,
    parent_name: Option<String>,
    depth: i32,
    adding: bool,
    color: String,
    min_trust: String,
    /// Posting rules, as form values; a subcategory starts with its parent's.
    topic_rule: String,
    reply_rule: String,
    /// `all` / `none` / `some`, and the keys for `some`; a subcategory
    /// starts with its parent's.
    reactions: String,
    reaction_keys: Vec<String>,
    name: String,
    error: Option<String>,
}

fn add_slot(tree: &CategoryTree, parent: Option<Uuid>) -> Option<AddSlot> {
    let (depth, siblings, parent_cat) = match parent {
        Some(pid) => (tree.depth(pid) + 1, tree.children(pid).len(), tree.get(pid)),
        None => (1, tree.roots().len(), None),
    };
    if depth > MAX_DEPTH {
        return None;
    }
    Some(AddSlot {
        parent: parent.map(|p| p.to_string()).unwrap_or_default(),
        parent_name: parent_cat.map(|c| c.name.clone()),
        depth,
        adding: false,
        color: NEW_COLORS[siblings % NEW_COLORS.len()].to_string(),
        // A new subcategory starts as visible as its parent.
        min_trust: parent_cat
            .and_then(|c| c.min_trust_level)
            .map(|n| n.to_string())
            .unwrap_or_else(|| "public".into()),
        topic_rule: PostingRule::from_column(parent_cat.and_then(|c| c.topic_min_trust)).form_value(),
        reply_rule: PostingRule::from_column(parent_cat.and_then(|c| c.reply_min_trust)).form_value(),
        reactions: parent_cat.map(ReactionRule::of).unwrap_or_default().mode().to_string(),
        reaction_keys: parent_cat.map(ReactionRule::of).unwrap_or_default().keys(),
        name: String::new(),
        error: None,
    })
}

fn card_node(
    tree: &CategoryTree,
    counts: &std::collections::HashMap<Uuid, u64>,
    all: &std::collections::HashSet<Uuid>,
    id: Uuid,
    depth: i32,
    fresh: Option<Uuid>,
) -> Option<CardNode> {
    let c = tree.get(id)?;
    Some(CardNode {
        id,
        name: c.name.clone(),
        slug: c.slug.clone(),
        description: c.description.clone(),
        widget_bg: color_widget_css(&tree.widget_colors(id)),
        min_trust: c.min_trust_level,
        rules: super::forum::posting_badges(c),
        depth,
        own_count: counts.get(&id).copied().unwrap_or(0),
        count: super::focus::subtree_count(tree, all, counts, id),
        children: tree
            .children(id)
            .iter()
            .filter_map(|&ch| card_node(tree, counts, all, ch, depth + 1, fresh))
            .collect(),
        add: add_slot(tree, Some(id)),
        fresh: fresh == Some(id),
    })
}

async fn manage_focus(state: &AppState, user: &UserContext) -> Result<Html<String>, StatusCode> {
    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load categories"))?;
    let counts = super::focus::topic_counts(state).await?;
    let all: std::collections::HashSet<Uuid> = tree.flatten().into_iter().map(|(id, _)| id).collect();
    let cards: Vec<CardNode> = tree
        .roots()
        .iter()
        .filter_map(|&id| card_node(&tree, &counts, &all, id, 1, None))
        .collect();
    render(state, "admin/categories_focus.html", context! {
        title => "Manage categories",
        app_name => state.config.app_name,
        user => user.user.clone(),
        cards => cards,
        add => add_slot(&tree, None),
        max_depth => MAX_DEPTH,
        rule_options => RULE_OPTIONS,
    })
}

#[derive(Debug, Deserialize)]
pub struct SlotQuery {
    /// The parent category; absent for the top level.
    pub parent: Option<Uuid>,
    /// `1` = the form, otherwise the `+` again (cancel).
    pub form: Option<u8>,
}

/// The inline add's swaps: `+` -> form (`?form=1`) and form -> `+` (cancel).
pub async fn category_add_slot(
    State(state): State<AppState>,
    Query(q): Query<SlotQuery>,
    user: UserContext,
) -> Result<Html<String>, StatusCode> {
    require_staff(&user)?;
    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load categories"))?;
    if q.parent.is_some_and(|p| tree.get(p).is_none()) {
        return Err(StatusCode::NOT_FOUND);
    }
    let mut slot = add_slot(&tree, q.parent).ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
    slot.adding = q.form == Some(1);
    render(&state, "admin/_category_add.html", context! { add => slot, rule_options => RULE_OPTIONS })
}

/// The inline add's submit: on success the new card followed by a fresh `+`
/// (so another can follow); on a problem the form again, with what was typed
/// and why. Always 200, so htmx swaps either.
pub async fn create_category_inline(
    State(state): State<AppState>,
    user: UserContext,
    Form(form): Form<CategoryForm>,
) -> Result<Html<String>, StatusCode> {
    require_staff(&user)?;
    let parent = parse_parent(&form.parent_id).ok().flatten();
    let typed = (form.name.clone(), form.color.clone(), form.min_trust_level.clone());
    let typed_rules = (form.topic_rule.clone(), form.reply_rule.clone());
    let typed_reactions = form.reactions.clone();
    match insert_category(&state, &user, form, true).await? {
        Ok(created) => {
            let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load categories"))?;
            let depth = tree.depth(created.id);
            let counts = std::collections::HashMap::new();
            let all = std::collections::HashSet::from([created.id]);
            let card = card_node(&tree, &counts, &all, created.id, depth, Some(created.id))
                .ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;
            render(&state, "admin/_category_added.html", context! {
                card => card,
                add => add_slot(&tree, created.parent_id),
                max_depth => MAX_DEPTH,
                rule_options => RULE_OPTIONS,
            })
        }
        Err(msg) => {
            let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load categories"))?;
            let mut slot = add_slot(&tree, parent.filter(|p| tree.get(*p).is_some()))
                .ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
            slot.adding = true;
            slot.name = typed.0;
            if let Some(c) = typed.1.filter(|c| !c.trim().is_empty()) {
                slot.color = c;
            }
            if let Some(t) = typed.2 {
                slot.min_trust = t;
            }
            if let Some(t) = typed_rules.0 {
                slot.topic_rule = t;
            }
            if let Some(t) = typed_rules.1 {
                slot.reply_rule = t;
            }
            if let Some(r) = typed_reactions.filter(|r| r != "inherit") {
                slot.reactions = r;
            }
            slot.error = Some(msg.to_string());
            render(&state, "admin/_category_add.html", context! { add => slot, rule_options => RULE_OPTIONS })
        }
    }
}

/// New-category form (staff only).
pub async fn new_category_form(
    State(state): State<AppState>,
    user: UserContext,
) -> Result<Html<String>, StatusCode> {
    require_staff(&user)?;
    render_form(&state, &user, None, None).await
}

/// Edit-category form (staff only).
pub async fn edit_category_form(
    State(state): State<AppState>,
    user: UserContext,
    Path(id): Path<Uuid>,
) -> Result<Html<String>, StatusCode> {
    require_staff(&user)?;
    let category = categories::Entity::find_by_id(id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load category"))?
        .ok_or(StatusCode::NOT_FOUND)?;
    render_form(&state, &user, Some(category), None).await
}

/// Validate and insert a category. `Ok(Err(msg))` is a problem with the form
/// (shown to the user); `Err` a server failure. With no position given the
/// classic form keeps its old default (0); the inline add puts the new
/// category after its siblings.
async fn insert_category(
    state: &AppState,
    user: &UserContext,
    form: CategoryForm,
    append: bool,
) -> Result<Result<categories::Model, &'static str>, StatusCode> {
    let name = form.name.trim().to_string();
    let slug = derive_slug(&form);
    if name.is_empty() || slug.is_empty() {
        return Ok(Err("Name (and a non-empty slug) are required."));
    }
    if slug_taken(state, &slug, None).await? {
        return Ok(Err("That slug is already in use."));
    }
    let parent = match parse_parent(&form.parent_id) {
        Ok(p) => p,
        Err(e) => return Ok(Err(e)),
    };
    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load tree"))?;
    let parent_id = match tree.validate_parent(parent, None) {
        Ok(p) => p,
        Err(e) => return Ok(Err(e)),
    };
    let position = match form.position {
        Some(p) => p,
        None if append => {
            let siblings = match parent_id {
                Some(pid) => tree.children(pid),
                None => tree.roots(),
            };
            siblings.iter().filter_map(|id| tree.get(*id)).map(|c| c.position + 1).max().unwrap_or(0)
        }
        None => 0,
    };

    // A subcategory starts with its parent's posting rules unless the form
    // says otherwise (as it starts as visible as its parent).
    let parent_cat = parent_id.and_then(|p| tree.get(p));
    let topic_min_trust = match parse_rule(&form.topic_rule, parent_cat.and_then(|c| c.topic_min_trust)) {
        Ok(v) => v,
        Err(e) => return Ok(Err(e)),
    };
    let reply_min_trust = match parse_rule(&form.reply_rule, parent_cat.and_then(|c| c.reply_min_trust)) {
        Ok(v) => v,
        Err(e) => return Ok(Err(e)),
    };
    let known: Vec<String> = reaction_choices(state).await?.into_iter().map(|(k, _, _)| k).collect();
    let reactions = match parse_reactions(&form, parent_cat.map(ReactionRule::of).unwrap_or_default(), &known) {
        Ok(r) => r,
        Err(e) => return Ok(Err(e)),
    };
    let (reactions_enabled, reaction_keys) = reactions.to_columns();
    let min_trust_level = parse_min_trust(&form.min_trust_level);

    let now = Utc::now();
    let active = categories::ActiveModel {
        id: Set(Uuid::now_v7()),
        name: Set(name),
        slug: Set(slug),
        description: Set(clean_opt(form.description)),
        color: Set(clean_color(form.color)),
        position: Set(position),
        parent_id: Set(parent_id),
        min_trust_level: Set(min_trust_level),
        topic_min_trust: Set(topic_min_trust),
        reply_min_trust: Set(reply_min_trust),
        reactions_enabled: Set(reactions_enabled),
        reaction_keys: Set(reaction_keys),
        created_at: Set(now.into()),
        updated_at: Set(now.into()),
    };
    let model = active.insert(state.db.as_ref()).await.map_err(ise("insert category"))?;
    if min_trust_level.is_some() || topic_min_trust.is_some() || reply_min_trust.is_some() || reactions != ReactionRule::All {
        moderation::log(
            state.db.as_ref(),
            Actor::web(&user.user),
            "category_permissions",
            "category",
            Some(model.id),
            &model.name,
            Some(&format!(
                "created with {} · {}",
                permissions_summary(min_trust_level, topic_min_trust, reply_min_trust),
                reactions_summary(&reactions)
            )),
        )
        .await;
    }
    Ok(Ok(model))
}

/// Create a category (staff only).
pub async fn create_category(
    State(state): State<AppState>,
    user: UserContext,
    Form(form): Form<CategoryForm>,
) -> Result<Response, StatusCode> {
    require_staff(&user)?;
    match insert_category(&state, &user, form, false).await? {
        Ok(_) => Ok(Redirect::to("/admin/categories").into_response()),
        Err(e) => form_err(&state, &user, None, e).await,
    }
}

/// Update a category (staff only).
pub async fn update_category(
    State(state): State<AppState>,
    user: UserContext,
    Path(id): Path<Uuid>,
    Form(form): Form<CategoryForm>,
) -> Result<Response, StatusCode> {
    require_staff(&user)?;

    let existing = categories::Entity::find_by_id(id)
        .one(state.db.as_ref())
        .await
        .map_err(ise("load category"))?
        .ok_or(StatusCode::NOT_FOUND)?;

    let name = form.name.trim().to_string();
    let slug = derive_slug(&form);
    if name.is_empty() || slug.is_empty() {
        return form_err(&state, &user, Some(existing), "Name (and a non-empty slug) are required.").await;
    }
    if slug_taken(&state, &slug, Some(id)).await? {
        return form_err(&state, &user, Some(existing), "That slug is already in use.").await;
    }

    let parent = match parse_parent(&form.parent_id) {
        Ok(p) => p,
        Err(e) => return form_err(&state, &user, Some(existing), e).await,
    };
    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load tree"))?;
    let parent_id = match tree.validate_parent(parent, Some(id)) {
        Ok(p) => p,
        Err(e) => return form_err(&state, &user, Some(existing), e).await,
    };

    let topic_min_trust = match parse_rule(&form.topic_rule, existing.topic_min_trust) {
        Ok(v) => v,
        Err(e) => return form_err(&state, &user, Some(existing), e).await,
    };
    let reply_min_trust = match parse_rule(&form.reply_rule, existing.reply_min_trust) {
        Ok(v) => v,
        Err(e) => return form_err(&state, &user, Some(existing), e).await,
    };
    let known: Vec<String> = reaction_choices(&state).await?.into_iter().map(|(k, _, _)| k).collect();
    let reactions = match parse_reactions(&form, ReactionRule::of(&existing), &known) {
        Ok(r) => r,
        Err(e) => return form_err(&state, &user, Some(existing), e).await,
    };
    let min_trust_level = parse_min_trust(&form.min_trust_level);
    let before = (existing.min_trust_level, existing.topic_min_trust, existing.reply_min_trust, ReactionRule::of(&existing));
    let after = (min_trust_level, topic_min_trust, reply_min_trust, reactions.clone());

    let mut active: categories::ActiveModel = existing.into();
    active.name = Set(name);
    active.slug = Set(slug);
    active.description = Set(clean_opt(form.description));
    active.color = Set(clean_color(form.color));
    active.position = Set(form.position.unwrap_or(0));
    active.parent_id = Set(parent_id);
    active.min_trust_level = Set(min_trust_level);
    active.topic_min_trust = Set(topic_min_trust);
    active.reply_min_trust = Set(reply_min_trust);
    let (reactions_enabled, reaction_keys) = reactions.to_columns();
    active.reactions_enabled = Set(reactions_enabled);
    active.reaction_keys = Set(reaction_keys);
    active.updated_at = Set(Utc::now().into());
    let updated = active.update(state.db.as_ref()).await.map_err(ise("update category"))?;
    if before != after {
        moderation::log(
            state.db.as_ref(),
            Actor::web(&user.user),
            "category_permissions",
            "category",
            Some(updated.id),
            &updated.name,
            Some(&format!(
                "{} · {} → {} · {}",
                permissions_summary(before.0, before.1, before.2),
                reactions_summary(&before.3),
                permissions_summary(after.0, after.1, after.2),
                reactions_summary(&after.3)
            )),
        )
        .await;
    }

    Ok(Redirect::to("/admin/categories").into_response())
}

/// Delete a category — staff only. Children are promoted (FK SetNull); topics in
/// this exact category cascade.
pub async fn delete_category(
    State(state): State<AppState>,
    user: UserContext,
    Path(id): Path<Uuid>,
) -> Result<Redirect, StatusCode> {
    require_staff(&user)?;
    categories::Entity::delete_by_id(id)
        .exec(state.db.as_ref())
        .await
        .map_err(ise("delete category"))?;
    Ok(Redirect::to("/admin/categories"))
}

fn parse_parent(raw: &Option<String>) -> Result<Option<Uuid>, &'static str> {
    match raw.as_deref().map(str::trim) {
        None | Some("") | Some("none") => Ok(None),
        Some(s) => Uuid::parse_str(s).map(Some).map_err(|_| "Invalid parent category."),
    }
}

fn derive_slug(form: &CategoryForm) -> String {
    let raw = form
        .slug
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .unwrap_or(form.name.as_str());
    slugify(raw)
}

fn clean_opt(s: Option<String>) -> Option<String> {
    s.map(|s| s.trim().to_string()).filter(|s| !s.is_empty())
}

fn clean_color(c: Option<String>) -> String {
    c.map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| DEFAULT_COLOR.to_string())
}

async fn slug_taken(state: &AppState, slug: &str, except: Option<Uuid>) -> Result<bool, StatusCode> {
    let mut q = categories::Entity::find().filter(categories::Column::Slug.eq(slug));
    if let Some(id) = except {
        q = q.filter(categories::Column::Id.ne(id));
    }
    let n = q.count(state.db.as_ref()).await.map_err(ise("check slug"))?;
    Ok(n > 0)
}

async fn form_err(
    state: &AppState,
    user: &UserContext,
    category: Option<categories::Model>,
    error: &str,
) -> Result<Response, StatusCode> {
    Ok(render_form(state, user, category, Some(error)).await?.into_response())
}

async fn render_form(
    state: &AppState,
    user: &UserContext,
    category: Option<categories::Model>,
    error: Option<&str>,
) -> Result<Html<String>, StatusCode> {
    let editing = category.is_some();
    let editing_id = category.as_ref().map(|c| c.id);

    let tree = CategoryTree::load(state.db.as_ref()).await.map_err(ise("load tree"))?;
    let parents: Vec<ParentOption> = tree
        .candidate_parents(editing_id)
        .into_iter()
        .filter_map(|(id, depth)| {
            tree.get(id).map(|c| ParentOption {
                id: c.id,
                name: c.name.clone(),
                depth,
            })
        })
        .collect();
    let selected_parent = category.as_ref().and_then(|c| c.parent_id);

    let current_min_trust = category.as_ref().and_then(|c| c.min_trust_level);
    // A new category: "same as the parent" until chosen otherwise.
    let rule_value = |v: Option<i32>| match &category {
        Some(_) => PostingRule::from_column(v).form_value(),
        None => "inherit".to_string(),
    };
    let topic_rule = rule_value(category.as_ref().and_then(|c| c.topic_min_trust));
    let reply_rule = rule_value(category.as_ref().and_then(|c| c.reply_min_trust));
    let current = category.as_ref().map(ReactionRule::of);
    render(state, "admin/category_form.html", context! {
        reactions => current.as_ref().map(|r| r.mode()).unwrap_or("inherit"),
        reaction_keys => current.map(|r| r.keys()).unwrap_or_default(),
        reaction_choices => reaction_choices(state).await?,
        title => if editing { "Edit category" } else { "New category" },
        app_name => state.config.app_name,
        user => user.user.clone(),
        category => category,
        parents => parents,
        selected_parent => selected_parent,
        default_color => DEFAULT_COLOR,
        current_min_trust => current_min_trust,
        topic_rule => topic_rule,
        reply_rule => reply_rule,
        rule_options => RULE_OPTIONS,
        creating => !editing,
        error => error,
    })
}

fn ise<E: std::fmt::Display>(ctx: &'static str) -> impl Fn(E) -> StatusCode {
    move |e| {
        error!(error = %e, "{ctx}");
        StatusCode::INTERNAL_SERVER_ERROR
    }
}

fn render(state: &AppState, name: &str, ctx: minijinja::Value) -> Result<Html<String>, StatusCode> {
    let template = state.env.get_template(name).map_err(|e| {
        error!(error = %e, template = name, "load template failed");
        StatusCode::INTERNAL_SERVER_ERROR
    })?;
    let rendered = template.render(ctx).map_err(|e| {
        error!(error = %e, template = name, "render template failed");
        StatusCode::INTERNAL_SERVER_ERROR
    })?;
    Ok(Html(rendered))
}

#[cfg(test)]
mod tests {
    use super::slugify;

    #[test]
    fn slugify_basics() {
        assert_eq!(slugify("Hello World"), "hello-world");
        assert_eq!(slugify("  Lots   of   spaces  "), "lots-of-spaces");
        assert_eq!(slugify("Caf\u{e9} & Bar!!"), "caf-bar");
        assert_eq!(slugify("---"), "");
    }
}