Skip to main content

rustango_cms/category/
model.rs

1//! Category models — real, migration-tracked tables (not a JSON
2//! blob). Two models:
3//!
4//! - [`Taxonomy`] (`cms_taxonomy`) — the vocabulary registry, mirroring
5//!   `cms_page_type`: one row per registered vocabulary (`category`,
6//!   `countries`, …), synced from handlers at seed.
7//! - [`Category`] (`cms_category`) — the abstract base row shared by every
8//!   vocabulary: a materialized-path tree (like `cms_page`) with typed
9//!   columns `name` / `description` / `featured_image_id` / `thumbnail_id`
10//!   / `parent_id`, scoped to a taxonomy via `taxonomy_id`.
11//!
12//! Custom vocabularies add extra typed fields in their own per-type
13//! extension table (unique `category_id` FK), exactly like a page type's
14//! extension — see [`crate::category`].
15//!
16//! Parenting is cycle-guarded inside the move transaction (materialized-
17//! path prefix test) and [`build_tree`] is loop-safe (visited-set + depth
18//! cap), so a corrupted `parent_id` can never hang the process.
19
20use chrono::{DateTime, Utc};
21use rustango::core::Column as _;
22use rustango::sql::{Auto, FetcherPool as _, Pool};
23use rustango::Model;
24use serde::{Deserialize, Serialize};
25use std::collections::{HashMap, HashSet};
26
27use crate::tree::{depth_of, descendants_like, MaterializedPath};
28
29/// Default per-taxonomy nesting cap when a handler doesn't set one.
30/// Also the backstop that limits damage from a corrupted tree.
31pub const DEFAULT_MAX_DEPTH: i32 = 10;
32
33/// Hard ceiling for any tree walk regardless of a taxonomy's configured
34/// `max_depth` — a last-resort backstop against a corrupted DB cycle.
35const WALK_DEPTH_CAP: usize = 64;
36
37/// A registered vocabulary. One row per taxonomy, synced from the
38/// [`TaxonomyHandler`](crate::category::TaxonomyHandler) inventory at seed
39/// (`upsert_taxonomy`). Mirrors `cms_page_type`.
40#[derive(Model, Debug, Clone, Serialize, Deserialize)]
41#[rustango(
42    table = "cms_taxonomy",
43    app = "cms",
44    display = "verbose_name",
45    admin(
46        list_display = "slug, verbose_name, hierarchical, max_depth",
47        search_fields = "slug, verbose_name",
48        ordering = "slug",
49    )
50)]
51pub struct Taxonomy {
52    #[rustango(primary_key)]
53    pub id: Auto<i64>,
54
55    /// Stable identifier — the URL/registry key, unique across vocabularies.
56    #[rustango(max_length = 100, unique)]
57    pub slug: String,
58
59    /// Human label for the admin nav + headings.
60    #[rustango(max_length = 200)]
61    pub verbose_name: String,
62
63    /// `true` allows nested categories; `false` rejects any non-NULL parent.
64    #[rustango(default = "true")]
65    pub hierarchical: bool,
66
67    /// Nesting cap (create/move enforced).
68    #[rustango(default = "10")]
69    pub max_depth: i32,
70
71    /// Material Symbols icon name for the nav entry.
72    #[rustango(max_length = 80, default = "''")]
73    pub icon: String,
74
75    #[rustango(max_length = 255, default = "''")]
76    pub description: String,
77
78    /// Per-type extension table name for typed extra fields, `''` when the
79    /// vocabulary uses only the base [`Category`] columns. Analog of
80    /// `LibraryType.extension_table`.
81    #[rustango(max_length = 120, default = "''")]
82    pub ext_table: String,
83
84    #[rustango(auto_now_add)]
85    pub created_at: Auto<DateTime<Utc>>,
86    #[rustango(auto_now)]
87    pub updated_at: Auto<DateTime<Utc>>,
88}
89
90/// The abstract base category row — shared by every vocabulary, one row
91/// per term. Tree shape (`path`/`depth`/`parent_id`) mirrors
92/// [`crate::page::Page`]; extra per-vocabulary fields live in a per-type
93/// extension table keyed on `id`.
94#[derive(Model, Debug, Clone, Serialize, Deserialize)]
95#[rustango(
96    table = "cms_category",
97    app = "cms",
98    display = "name",
99    admin(
100        list_display = "taxonomy_id, name, slug, depth, sort_order",
101        search_fields = "name, slug",
102        ordering = "taxonomy_id, path",
103        list_filter = "taxonomy_id",
104    )
105)]
106pub struct Category {
107    #[rustango(primary_key)]
108    pub id: Auto<i64>,
109
110    /// Owning vocabulary — the discriminator (mirrors `page.page_type_id`).
111    #[rustango(fk = "cms_taxonomy", on = "id", index)]
112    pub taxonomy_id: i64,
113
114    /// Human-readable name (translatable via `cms_translation`).
115    #[rustango(max_length = 200)]
116    pub name: String,
117
118    /// URL/identifier slug, unique per (taxonomy, parent).
119    #[rustango(max_length = 200, index)]
120    pub slug: String,
121
122    /// Short blurb shown in listings / on the term page.
123    #[rustango(max_length = 1024, default = "''")]
124    pub description: String,
125
126    /// Featured image — FK into `cms_media`.
127    #[rustango(fk = "cms_media", on = "id")]
128    pub featured_image_id: Option<i64>,
129
130    /// Thumbnail — FK into `cms_media`.
131    #[rustango(fk = "cms_media", on = "id")]
132    pub thumbnail_id: Option<i64>,
133
134    /// Tree parent — None for a root category. Siblings share this.
135    #[rustango(fk = "cms_category", on = "id", index)]
136    pub parent_id: Option<i64>,
137
138    /// Materialized path of zero-padded segment ids, trailing slash
139    /// (e.g. `0001/0003/`). Indexed for cheap subtree prefix queries.
140    #[rustango(max_length = 510, index)]
141    pub path: String,
142
143    /// Cached `/`-separated segment count (root = 1).
144    pub depth: i32,
145
146    pub sort_order: i32,
147
148    #[rustango(auto_now_add)]
149    pub created_at: Auto<DateTime<Utc>>,
150    #[rustango(auto_now)]
151    pub updated_at: Auto<DateTime<Utc>>,
152}
153
154/// Errors from category tree mutations. `CycleAttempt` mirrors
155/// [`crate::tree_ops::TreeError::CycleAttempt`].
156#[derive(Debug, thiserror::Error)]
157pub enum CategoryError {
158    #[error(transparent)]
159    Db(#[from] rustango::sql::ExecError),
160    #[error(transparent)]
161    Sqlx(#[from] rustango::sql::sqlx::Error),
162    #[error("category {0} not found")]
163    NotFound(i64),
164    #[error("unknown taxonomy id {0} — is it registered/seeded?")]
165    UnknownTaxonomy(i64),
166    #[error("cannot move a category beneath itself or its own descendant")]
167    CycleAttempt,
168    #[error("taxonomy `{0}` is flat — categories cannot have a parent")]
169    FlatNoParent(String),
170    #[error("max depth {0} exceeded for taxonomy `{1}`")]
171    MaxDepthExceeded(i32, String),
172    #[error("a sibling category already uses slug `{0}`")]
173    DuplicateSlug(String),
174    #[error("category {0} still has {1} child categor(ies) — reparent or delete them first")]
175    HasChildren(i64, usize),
176    #[error("category path segment overflow (id out of range)")]
177    PathOverflow,
178}
179
180impl From<crate::tree::PathError> for CategoryError {
181    fn from(_: crate::tree::PathError) -> Self {
182        CategoryError::PathOverflow
183    }
184}
185
186/// A nested category for tree rendering — a row plus its (loop-safe)
187/// children.
188#[derive(Debug, Clone, Serialize)]
189pub struct CategoryNode {
190    #[serde(flatten)]
191    pub category: Category,
192    pub children: Vec<CategoryNode>,
193}
194
195/// Normalize a category slug like a page slug: lowercase, spaces/
196/// underscores → hyphens, strip anything but `[a-z0-9-]`, collapse
197/// repeats. Empty input falls back to `category`.
198#[must_use]
199pub fn normalize_slug(raw: &str) -> String {
200    let mut out = String::with_capacity(raw.len());
201    let mut prev_dash = false;
202    for ch in raw.trim().chars() {
203        let c = ch.to_ascii_lowercase();
204        if c.is_ascii_alphanumeric() {
205            out.push(c);
206            prev_dash = false;
207        } else if matches!(c, ' ' | '-' | '_') && !prev_dash && !out.is_empty() {
208            out.push('-');
209            prev_dash = true;
210        }
211    }
212    while out.ends_with('-') {
213        out.pop();
214    }
215    if out.is_empty() {
216        "category".to_owned()
217    } else {
218        out
219    }
220}
221
222/// Fetch a taxonomy row by id.
223async fn taxonomy(pool: &Pool, taxonomy_id: i64) -> Result<Taxonomy, CategoryError> {
224    Taxonomy::objects()
225        .where_(Taxonomy::id.eq(taxonomy_id))
226        .first(pool)
227        .await?
228        .ok_or(CategoryError::UnknownTaxonomy(taxonomy_id))
229}
230
231/// Fetch a category by id, scoped to its taxonomy.
232async fn fetch(pool: &Pool, taxonomy_id: i64, id: i64) -> Result<Option<Category>, CategoryError> {
233    Ok(Category::objects()
234        .where_(Category::id.eq(id))
235        .where_(Category::taxonomy_id.eq(taxonomy_id))
236        .first(pool)
237        .await?)
238}
239
240/// Immediate children of `parent` (None = roots) within a taxonomy,
241/// ordered by `sort_order` then `id`.
242///
243/// # Errors
244/// Propagates query failures.
245pub async fn children_of(
246    pool: &Pool,
247    taxonomy_id: i64,
248    parent: Option<i64>,
249) -> Result<Vec<Category>, CategoryError> {
250    let qs = Category::objects()
251        .where_(Category::taxonomy_id.eq(taxonomy_id))
252        .order_by(&[("sort_order", false), ("id", false)]);
253    let rows = match parent {
254        Some(pid) => qs.where_(Category::parent_id.eq(pid)).fetch(pool).await?,
255        None => qs.where_(Category::parent_id.is_null()).fetch(pool).await?,
256    };
257    Ok(rows)
258}
259
260/// Every category in a taxonomy, ordered by `path` (tree pre-order).
261///
262/// # Errors
263/// Propagates query failures.
264pub async fn all_in_taxonomy(
265    pool: &Pool,
266    taxonomy_id: i64,
267) -> Result<Vec<Category>, CategoryError> {
268    Ok(Category::objects()
269        .where_(Category::taxonomy_id.eq(taxonomy_id))
270        .order_by(&[("path", false)])
271        .fetch(pool)
272        .await?)
273}
274
275/// True if a sibling (same taxonomy + parent) already uses `slug`,
276/// optionally excluding `exclude_id` (for edits).
277async fn slug_taken(
278    pool: &Pool,
279    taxonomy_id: i64,
280    parent: Option<i64>,
281    slug: &str,
282    exclude_id: Option<i64>,
283) -> Result<bool, CategoryError> {
284    let siblings = children_of(pool, taxonomy_id, parent).await?;
285    Ok(siblings
286        .iter()
287        .any(|c| c.slug == slug && c.id.get().copied() != exclude_id))
288}
289
290/// A new category's base fields (extension fields are saved separately by
291/// the handler, keyed on the returned id).
292#[derive(Debug, Clone, Default)]
293pub struct NewCategory {
294    pub name: String,
295    pub slug: String,
296    pub description: String,
297    pub featured_image_id: Option<i64>,
298    pub thumbnail_id: Option<i64>,
299    pub parent_id: Option<i64>,
300}
301
302/// Create a category. Validates parent (exists, same taxonomy, allowed by
303/// `hierarchical`, within `max_depth`) and slug-uniqueness, then inserts
304/// and materializes its `path` in one transaction.
305///
306/// # Errors
307/// [`CategoryError`] for unknown taxonomy, flat-with-parent, depth
308/// overflow, duplicate slug, missing parent, or DB failure.
309pub async fn create(
310    pool: &Pool,
311    taxonomy_id: i64,
312    new: NewCategory,
313) -> Result<Category, CategoryError> {
314    let tax = taxonomy(pool, taxonomy_id).await?;
315    let base = if new.slug.trim().is_empty() {
316        &new.name
317    } else {
318        &new.slug
319    };
320    let slug = normalize_slug(base);
321
322    let (parent_path, parent_depth) = match new.parent_id {
323        None => (None, 0),
324        Some(pid) => {
325            if !tax.hierarchical {
326                return Err(CategoryError::FlatNoParent(tax.slug.clone()));
327            }
328            let parent = fetch(pool, taxonomy_id, pid)
329                .await?
330                .ok_or(CategoryError::NotFound(pid))?;
331            (Some(parent.path.clone()), parent.depth)
332        }
333    };
334    let new_depth = parent_depth + 1;
335    if new_depth > tax.max_depth.max(1) {
336        return Err(CategoryError::MaxDepthExceeded(
337            tax.max_depth,
338            tax.slug.clone(),
339        ));
340    }
341    if slug_taken(pool, taxonomy_id, new.parent_id, &slug, None).await? {
342        return Err(CategoryError::DuplicateSlug(slug));
343    }
344    let sort_order = children_of(pool, taxonomy_id, new.parent_id).await?.len() as i32;
345
346    // Insert then materialize the path in one transaction (mirrors
347    // tree_ops::create_child). A manual tx (not the `atomic!` macro) lets
348    // the `MaterializedPath` `PathError` map straight to `CategoryError`
349    // via `?` — the macro is fixed to `ExecError`.
350    let mut tx = rustango::sql::transaction_pool(pool).await?;
351    let mut cat = Category {
352        id: Auto::Unset,
353        taxonomy_id,
354        name: new.name,
355        slug,
356        description: new.description,
357        featured_image_id: new.featured_image_id,
358        thumbnail_id: new.thumbnail_id,
359        parent_id: new.parent_id,
360        path: String::new(),
361        depth: new_depth,
362        sort_order,
363        created_at: Auto::Unset,
364        updated_at: Auto::Unset,
365    };
366    cat.insert_tx(&mut tx).await?;
367    let id = cat.id.get().copied().unwrap_or_default();
368    let path = match &parent_path {
369        Some(pp) => MaterializedPath::child_of(pp, id)?,
370        None => MaterializedPath::root(id)?,
371    };
372    cat.depth = path.depth();
373    cat.path = path.into_string();
374    cat.save_tx(&mut tx).await?;
375    tx.commit().await?;
376    Ok(cat)
377}
378
379/// Update a category's base fields in place (name/slug/description/media).
380/// Re-checks slug uniqueness among siblings (excluding self). Does not
381/// re-parent — use [`move_to`] for that.
382///
383/// # Errors
384/// [`CategoryError::DuplicateSlug`], `NotFound`, or DB failure.
385pub async fn update(
386    pool: &Pool,
387    taxonomy_id: i64,
388    id: i64,
389    new: NewCategory,
390) -> Result<Category, CategoryError> {
391    let mut cat = fetch(pool, taxonomy_id, id)
392        .await?
393        .ok_or(CategoryError::NotFound(id))?;
394    let base = if new.slug.trim().is_empty() {
395        &new.name
396    } else {
397        &new.slug
398    };
399    let slug = normalize_slug(base);
400    if slug != cat.slug && slug_taken(pool, taxonomy_id, cat.parent_id, &slug, Some(id)).await? {
401        return Err(CategoryError::DuplicateSlug(slug));
402    }
403    cat.name = new.name;
404    cat.slug = slug;
405    cat.description = new.description;
406    cat.featured_image_id = new.featured_image_id;
407    cat.thumbnail_id = new.thumbnail_id;
408    cat.save(pool).await?;
409    Ok(cat)
410}
411
412/// Re-parent a category (and its whole subtree) under `new_parent`
413/// (None = root). Cycle-guarded: the new parent may not be the category
414/// itself or any of its descendants. Enforces `hierarchical` + `max_depth`
415/// for the deepest moved node.
416///
417/// # Errors
418/// [`CategoryError::CycleAttempt`], `FlatNoParent`, `MaxDepthExceeded`,
419/// `NotFound`, or DB failure.
420pub async fn move_to(
421    pool: &Pool,
422    taxonomy_id: i64,
423    id: i64,
424    new_parent: Option<i64>,
425) -> Result<(), CategoryError> {
426    let tax = taxonomy(pool, taxonomy_id).await?;
427    let cat = fetch(pool, taxonomy_id, id)
428        .await?
429        .ok_or(CategoryError::NotFound(id))?;
430
431    // Read the subtree BEFORE the tx (avoids single-conn SQLite deadlock).
432    let mut subtree: Vec<Category> = Category::objects()
433        .where_(Category::taxonomy_id.eq(taxonomy_id))
434        .where_(Category::path.like(descendants_like(&cat.path)))
435        .where_(Category::path.ne(cat.path.clone()))
436        .order_by(&[("path", false)])
437        .fetch(pool)
438        .await?;
439
440    let (new_path, new_depth) = match new_parent {
441        None => (MaterializedPath::root(id)?, 1),
442        Some(pid) => {
443            if !tax.hierarchical {
444                return Err(CategoryError::FlatNoParent(tax.slug.clone()));
445            }
446            let parent = fetch(pool, taxonomy_id, pid)
447                .await?
448                .ok_or(CategoryError::NotFound(pid))?;
449            if pid == id || parent.path.starts_with(&cat.path) {
450                return Err(CategoryError::CycleAttempt);
451            }
452            (
453                MaterializedPath::child_of(&parent.path, id)?,
454                parent.depth + 1,
455            )
456        }
457    };
458
459    let height = subtree
460        .iter()
461        .map(|d| d.depth)
462        .max()
463        .map_or(0, |m| m - cat.depth);
464    if new_depth + height > tax.max_depth.max(1) {
465        return Err(CategoryError::MaxDepthExceeded(
466            tax.max_depth,
467            tax.slug.clone(),
468        ));
469    }
470
471    let old_prefix = cat.path.clone();
472    let new_path = new_path.into_string();
473    if new_path == old_prefix {
474        return Ok(());
475    }
476
477    rustango::atomic!(pool, |tx| {
478        let mut guard = tx.lock().await?;
479        let tx = &mut *guard;
480        let mut moved = cat.clone();
481        moved.parent_id = new_parent;
482        moved.path = new_path.clone();
483        moved.depth = new_depth;
484        moved.save_tx(tx).await?;
485        for row in &mut subtree {
486            if let Some(suffix) = row.path.strip_prefix(&old_prefix) {
487                row.path = format!("{new_path}{suffix}");
488                row.depth = depth_of(&row.path);
489                row.save_tx(tx).await?;
490            }
491        }
492        Ok::<(), rustango::sql::ExecError>(())
493    })
494    .await?;
495    Ok(())
496}
497
498/// Delete a category. With children: `reparent = true` promotes them to
499/// the category's own parent; otherwise the delete is rejected
500/// ([`CategoryError::HasChildren`]). Page↔category assignments are cleaned
501/// by [`crate::category::assign::delete_for_category_tx`]. Returns 1.
502///
503/// # Errors
504/// [`CategoryError::HasChildren`] (children + not reparenting), `NotFound`,
505/// or DB failure.
506pub async fn delete(
507    pool: &Pool,
508    taxonomy_id: i64,
509    id: i64,
510    reparent: bool,
511) -> Result<usize, CategoryError> {
512    let cat = fetch(pool, taxonomy_id, id)
513        .await?
514        .ok_or(CategoryError::NotFound(id))?;
515    let children = children_of(pool, taxonomy_id, Some(id)).await?;
516    if !children.is_empty() && !reparent {
517        return Err(CategoryError::HasChildren(id, children.len()));
518    }
519    if reparent {
520        for child in &children {
521            let cid = child.id.get().copied().unwrap_or_default();
522            move_to(pool, taxonomy_id, cid, cat.parent_id).await?;
523        }
524    }
525    rustango::atomic!(pool, |tx| {
526        let mut guard = tx.lock().await?;
527        let tx = &mut *guard;
528        crate::category::assign::delete_for_category_tx(tx, id).await?;
529        crate::category_translation::delete_for_category_tx(tx, id).await?;
530        let row = cat.clone();
531        row.delete_tx(tx).await?;
532        Ok::<(), rustango::sql::ExecError>(())
533    })
534    .await?;
535    Ok(1)
536}
537
538/// Build a nested [`CategoryNode`] tree from a flat, path-ordered row
539/// list. **Loop-safe**: groups by `parent_id`, materializes generation by
540/// generation with a visited-set + a hard depth cap (`WALK_DEPTH_CAP`).
541/// A corrupted `parent_id` cycle yields a truncated tree + a single
542/// `tracing::error!`, never an infinite loop / OOM.
543#[must_use]
544pub fn build_tree(rows: Vec<Category>) -> Vec<CategoryNode> {
545    let mut by_parent: HashMap<Option<i64>, Vec<Category>> = HashMap::new();
546    for r in rows {
547        by_parent.entry(r.parent_id).or_default().push(r);
548    }
549    let mut visited: HashSet<i64> = HashSet::new();
550    build_level(&by_parent, None, 0, &mut visited)
551}
552
553fn build_level(
554    by_parent: &HashMap<Option<i64>, Vec<Category>>,
555    parent: Option<i64>,
556    depth: usize,
557    visited: &mut HashSet<i64>,
558) -> Vec<CategoryNode> {
559    if depth >= WALK_DEPTH_CAP {
560        tracing::error!(
561            target: "rustango_cms::category",
562            depth, "category tree exceeded depth cap — truncating (corrupted parent_id cycle?)"
563        );
564        return Vec::new();
565    }
566    let Some(children) = by_parent.get(&parent) else {
567        return Vec::new();
568    };
569    let mut out = Vec::with_capacity(children.len());
570    for cat in children {
571        let id = cat.id.get().copied().unwrap_or_default();
572        if !visited.insert(id) {
573            tracing::error!(
574                target: "rustango_cms::category",
575                category_id = id, "category already visited — skipping (cycle in parent_id)"
576            );
577            continue;
578        }
579        let kids = build_level(by_parent, Some(id), depth + 1, visited);
580        out.push(CategoryNode {
581            category: cat.clone(),
582            children: kids,
583        });
584    }
585    out
586}
587
588#[cfg(all(test, feature = "sqlite"))]
589mod tests {
590    use super::*;
591    use rustango::core::Model as _;
592    use rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect;
593
594    async fn mem_pool() -> Pool {
595        let pool = Pool::connect("sqlite::memory:").await.expect("mem pool");
596        // Create every table our FKs reference so inserts satisfy the
597        // constraints (cms_media/cms_page targets), mirroring the redirect
598        // tests. `cms_page` pulls in its own FK targets (type/media/theme).
599        for schema in [
600            &crate::page_type_model::PageType::SCHEMA,
601            &crate::media::Media::SCHEMA,
602            &crate::theme::Theme::SCHEMA,
603            &crate::page::Page::SCHEMA,
604            &Taxonomy::SCHEMA,
605            &Category::SCHEMA,
606            &crate::category::assign::PageCategory::SCHEMA,
607            &crate::locale::Locale::SCHEMA,
608            &crate::category_translation::CategoryTranslation::SCHEMA,
609        ] {
610            let ddl = create_table_if_not_exists_sql_with_dialect(pool.dialect(), schema);
611            for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
612                rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
613                    .await
614                    .expect("ddl");
615            }
616        }
617        pool
618    }
619
620    async fn mk_taxonomy(pool: &Pool, slug: &str, hierarchical: bool, max_depth: i32) -> i64 {
621        let mut t = Taxonomy {
622            id: Auto::Unset,
623            slug: slug.to_owned(),
624            verbose_name: slug.to_owned(),
625            hierarchical,
626            max_depth,
627            icon: String::new(),
628            description: String::new(),
629            ext_table: String::new(),
630            created_at: Auto::Unset,
631            updated_at: Auto::Unset,
632        };
633        t.insert(pool).await.expect("insert taxonomy");
634        t.id.get().copied().unwrap()
635    }
636
637    fn nc(name: &str, parent: Option<i64>) -> NewCategory {
638        NewCategory {
639            name: name.to_owned(),
640            parent_id: parent,
641            ..Default::default()
642        }
643    }
644
645    #[tokio::test]
646    async fn create_materializes_path_and_typed_columns() {
647        let pool = mem_pool().await;
648        let tax = mk_taxonomy(&pool, "category", true, 10).await;
649        let mut europe_nc = nc("Europe", None);
650        europe_nc.description = "The continent".to_owned();
651        let europe = create(&pool, tax, europe_nc).await.expect("root");
652        assert_eq!(europe.path, "0001/");
653        assert_eq!(europe.depth, 1);
654        assert_eq!(europe.slug, "europe");
655        assert_eq!(europe.description, "The continent");
656        assert_eq!(europe.featured_image_id, None);
657        let france = create(&pool, tax, nc("France", europe.id.get().copied()))
658            .await
659            .expect("child");
660        assert_eq!(france.path, "0001/0002/");
661        assert_eq!(france.depth, 2);
662    }
663
664    #[tokio::test]
665    async fn duplicate_sibling_slug_rejected_across_parents_ok() {
666        let pool = mem_pool().await;
667        let tax = mk_taxonomy(&pool, "category", true, 10).await;
668        let a = create(&pool, tax, nc("A", None)).await.unwrap();
669        let b = create(&pool, tax, nc("B", None)).await.unwrap();
670        create(&pool, tax, nc("News", a.id.get().copied()))
671            .await
672            .expect("first");
673        let dup = create(&pool, tax, nc("News", a.id.get().copied())).await;
674        assert!(
675            matches!(dup, Err(CategoryError::DuplicateSlug(_))),
676            "got {dup:?}"
677        );
678        create(&pool, tax, nc("News", b.id.get().copied()))
679            .await
680            .expect("under B ok");
681    }
682
683    #[tokio::test]
684    async fn move_into_own_descendant_is_cycle_rejected() {
685        let pool = mem_pool().await;
686        let tax = mk_taxonomy(&pool, "category", true, 10).await;
687        let root = create(&pool, tax, nc("Root", None)).await.unwrap();
688        let mid = create(&pool, tax, nc("Mid", root.id.get().copied()))
689            .await
690            .unwrap();
691        let leaf = create(&pool, tax, nc("Leaf", mid.id.get().copied()))
692            .await
693            .unwrap();
694        let res = move_to(
695            &pool,
696            tax,
697            root.id.get().copied().unwrap(),
698            leaf.id.get().copied(),
699        )
700        .await;
701        assert!(
702            matches!(res, Err(CategoryError::CycleAttempt)),
703            "got {res:?}"
704        );
705    }
706
707    #[tokio::test]
708    async fn move_rewrites_subtree_paths() {
709        let pool = mem_pool().await;
710        let tax = mk_taxonomy(&pool, "category", true, 10).await;
711        let a = create(&pool, tax, nc("A", None)).await.unwrap();
712        let b = create(&pool, tax, nc("B", None)).await.unwrap();
713        let ac = create(&pool, tax, nc("AC", a.id.get().copied()))
714            .await
715            .unwrap();
716        move_to(
717            &pool,
718            tax,
719            a.id.get().copied().unwrap(),
720            b.id.get().copied(),
721        )
722        .await
723        .expect("move");
724        let moved_a = fetch(&pool, tax, a.id.get().copied().unwrap())
725            .await
726            .unwrap()
727            .unwrap();
728        let moved_ac = fetch(&pool, tax, ac.id.get().copied().unwrap())
729            .await
730            .unwrap()
731            .unwrap();
732        assert!(moved_a.path.starts_with(&b.path));
733        assert!(moved_ac.path.starts_with(&moved_a.path));
734        assert_eq!(moved_ac.depth, moved_a.depth + 1);
735    }
736
737    #[tokio::test]
738    async fn flat_taxonomy_rejects_parent() {
739        let pool = mem_pool().await;
740        let tax = mk_taxonomy(&pool, "tags", false, 1).await;
741        let a = create(&pool, tax, nc("A", None)).await.unwrap();
742        let res = create(&pool, tax, nc("B", a.id.get().copied())).await;
743        assert!(
744            matches!(res, Err(CategoryError::FlatNoParent(_))),
745            "got {res:?}"
746        );
747    }
748
749    #[tokio::test]
750    async fn max_depth_enforced() {
751        let pool = mem_pool().await;
752        let tax = mk_taxonomy(&pool, "shallow", true, 2).await;
753        let a = create(&pool, tax, nc("A", None)).await.unwrap();
754        let b = create(&pool, tax, nc("B", a.id.get().copied()))
755            .await
756            .unwrap();
757        let res = create(&pool, tax, nc("C", b.id.get().copied())).await;
758        assert!(
759            matches!(res, Err(CategoryError::MaxDepthExceeded(2, _))),
760            "got {res:?}"
761        );
762    }
763
764    #[tokio::test]
765    async fn delete_blocks_with_children_then_reparents() {
766        let pool = mem_pool().await;
767        let tax = mk_taxonomy(&pool, "category", true, 10).await;
768        let root = create(&pool, tax, nc("Root", None)).await.unwrap();
769        let child = create(&pool, tax, nc("Child", root.id.get().copied()))
770            .await
771            .unwrap();
772        let blocked = delete(&pool, tax, root.id.get().copied().unwrap(), false).await;
773        assert!(
774            matches!(blocked, Err(CategoryError::HasChildren(_, 1))),
775            "got {blocked:?}"
776        );
777        delete(&pool, tax, root.id.get().copied().unwrap(), true)
778            .await
779            .expect("reparent delete");
780        let promoted = fetch(&pool, tax, child.id.get().copied().unwrap())
781            .await
782            .unwrap()
783            .unwrap();
784        assert_eq!(promoted.parent_id, None);
785        assert_eq!(promoted.depth, 1);
786    }
787
788    #[tokio::test]
789    async fn build_tree_survives_corrupted_cycle() {
790        let pool = mem_pool().await;
791        let tax = mk_taxonomy(&pool, "category", true, 10).await;
792        let a = create(&pool, tax, nc("A", None)).await.unwrap();
793        let b = create(&pool, tax, nc("B", a.id.get().copied()))
794            .await
795            .unwrap();
796        let aid = a.id.get().copied().unwrap();
797        let bid = b.id.get().copied().unwrap();
798        rustango::sql::raw_execute_pool(
799            &pool,
800            &format!("UPDATE cms_category SET parent_id = {bid} WHERE id = {aid}"),
801            Vec::new(),
802        )
803        .await
804        .unwrap();
805        let rows = Category::objects()
806            .where_(Category::taxonomy_id.eq(tax))
807            .fetch(&pool)
808            .await
809            .unwrap();
810        let tree = build_tree(rows); // must return, not hang
811        assert!(
812            tree.is_empty(),
813            "cyclic rows have no root → empty but returns"
814        );
815    }
816}