1use 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
29pub const DEFAULT_MAX_DEPTH: i32 = 10;
32
33const WALK_DEPTH_CAP: usize = 64;
36
37#[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 #[rustango(max_length = 100, unique)]
57 pub slug: String,
58
59 #[rustango(max_length = 200)]
61 pub verbose_name: String,
62
63 #[rustango(default = "true")]
65 pub hierarchical: bool,
66
67 #[rustango(default = "10")]
69 pub max_depth: i32,
70
71 #[rustango(max_length = 80, default = "''")]
73 pub icon: String,
74
75 #[rustango(max_length = 255, default = "''")]
76 pub description: String,
77
78 #[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#[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 #[rustango(fk = "cms_taxonomy", on = "id", index)]
112 pub taxonomy_id: i64,
113
114 #[rustango(max_length = 200)]
116 pub name: String,
117
118 #[rustango(max_length = 200, index)]
120 pub slug: String,
121
122 #[rustango(max_length = 1024, default = "''")]
124 pub description: String,
125
126 #[rustango(fk = "cms_media", on = "id")]
128 pub featured_image_id: Option<i64>,
129
130 #[rustango(fk = "cms_media", on = "id")]
132 pub thumbnail_id: Option<i64>,
133
134 #[rustango(fk = "cms_category", on = "id", index)]
136 pub parent_id: Option<i64>,
137
138 #[rustango(max_length = 510, index)]
141 pub path: String,
142
143 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#[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#[derive(Debug, Clone, Serialize)]
189pub struct CategoryNode {
190 #[serde(flatten)]
191 pub category: Category,
192 pub children: Vec<CategoryNode>,
193}
194
195#[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
222async 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
231async 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
240pub 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
260pub 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
275async 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#[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
302pub 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 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
379pub 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
412pub 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 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
498pub 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#[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 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); assert!(
812 tree.is_empty(),
813 "cyclic rows have no root → empty but returns"
814 );
815 }
816}