Skip to main content

rustango_cms/category/
mod.rs

1//! Categories & taxonomies — hierarchical categorization, built
2//! the **same way pages are**: real migration-tracked models, not a JSON
3//! blob or a config file.
4//!
5//! - [`model::Category`] (`cms_category`) is the abstract base row — a
6//!   materialized-path tree with typed columns (name, description,
7//!   featured image, thumbnail, parent). Every vocabulary shares it.
8//! - [`model::Taxonomy`] (`cms_taxonomy`) is the vocabulary registry,
9//!   mirroring `cms_page_type`: one row per vocabulary, **synced from the
10//!   [`TaxonomyHandler`] inventory at seed** ([`upsert_taxonomy`]). The DB
11//!   rows are the runtime source of truth ([`taxonomies`]).
12//! - [`assign::PageCategory`] (`cms_page_category`) files pages under
13//!   categories.
14//!
15//! A **custom vocabulary** is registered in code exactly like a custom
16//! page type: implement [`TaxonomyHandler`] + `register_taxonomy!(T)`.
17//! Extra typed fields (a country's flag + ISO code) live in the handler's
18//! own per-type **extension table** (unique `category_id` FK) — the
19//! `error_pages`/page-type extension pattern. The built-in `category`
20//! vocabulary ships with only the base columns.
21//!
22//! The tables are created by a **migration** (`0005_categories.json`,
23//! generated via `cargo run --example gen_migration`), not runtime
24//! `ensure_table` — so they are tracked exactly like `cms_page`.
25
26pub mod assign;
27pub mod model;
28
29pub use assign::PageCategory;
30pub use model::{Category, CategoryError, CategoryNode, NewCategory, Taxonomy, DEFAULT_MAX_DEPTH};
31
32use rustango::sql::Pool;
33
34/// A code-registered vocabulary. Mirrors
35/// [`PageTypeHandler`](crate::page_type::PageTypeHandler): process-global,
36/// zero-arg constructible via the [`register_taxonomy!`](crate::register_taxonomy)
37/// factory. The definition is synced into a `cms_taxonomy` row at seed;
38/// the optional extension hooks back a custom typed-field table.
39#[async_trait::async_trait]
40pub trait TaxonomyHandler: Send + Sync + 'static {
41    /// Stable identifier — the URL/registry key, unique across vocabularies.
42    fn slug(&self) -> &'static str;
43    /// Human label for the admin nav + headings.
44    fn verbose_name(&self) -> &'static str;
45    /// `true` allows nested categories; `false` rejects any non-NULL parent.
46    fn hierarchical(&self) -> bool {
47        true
48    }
49    /// Nesting cap (create/move enforced).
50    fn max_depth(&self) -> i32 {
51        DEFAULT_MAX_DEPTH
52    }
53    /// Material Symbols icon for the nav entry.
54    fn icon(&self) -> Option<&'static str> {
55        None
56    }
57    fn description(&self) -> Option<&'static str> {
58        None
59    }
60    /// Per-type extension table name (typed extra fields), or `None` for a
61    /// base-columns-only vocabulary like the built-in `category`.
62    fn ext_table(&self) -> Option<&'static str> {
63        None
64    }
65    /// Extra field widgets for the category editor (custom vocabularies),
66    /// prefilled from the extension row. Rendered through the shared
67    /// `_widget.html` macro alongside the base fields.
68    async fn ext_widgets(
69        &self,
70        _pool: &Pool,
71        _category_id: i64,
72    ) -> Result<Vec<crate::widget::Widget>, rustango::sql::ExecError> {
73        Ok(Vec::new())
74    }
75    /// Persist the extension row from the posted form (custom vocabularies).
76    async fn save_ext(
77        &self,
78        _pool: &Pool,
79        _category_id: i64,
80        _form: &std::collections::HashMap<String, String>,
81    ) -> Result<(), rustango::sql::ExecError> {
82        Ok(())
83    }
84}
85
86/// Inventory registration for a [`TaxonomyHandler`] (mirrors
87/// `PageTypeHandlerRegistration`). Populated by
88/// [`register_taxonomy!`](crate::register_taxonomy).
89pub struct TaxonomyHandlerRegistration {
90    pub factory: fn() -> Box<dyn TaxonomyHandler>,
91}
92
93inventory::collect!(TaxonomyHandlerRegistration);
94
95/// Every code-registered vocabulary handler in the binary.
96pub fn registered_handlers() -> impl Iterator<Item = Box<dyn TaxonomyHandler>> {
97    inventory::iter::<TaxonomyHandlerRegistration>
98        .into_iter()
99        .map(|r| (r.factory)())
100}
101
102/// The code handler for `slug` (for the extension hooks).
103#[must_use]
104pub fn find_handler(slug: &str) -> Option<Box<dyn TaxonomyHandler>> {
105    registered_handlers().find(|h| h.slug() == slug)
106}
107
108/// Sync a `cms_taxonomy` row from a registered handler — find-or-create
109/// keyed on the natural key `slug`, mirroring `upsert_page_type`
110/// (`seed.rs`). Called per-tenant at seed.
111///
112/// # Errors
113/// Propagates query / write failures.
114pub async fn upsert_taxonomy(
115    pool: &Pool,
116    handler: &dyn TaxonomyHandler,
117) -> Result<(), rustango::sql::ExecError> {
118    use rustango::core::Column as _;
119    use rustango::sql::{Auto, FetcherPool as _};
120
121    let mut existing: Vec<Taxonomy> = Taxonomy::objects()
122        .where_(Taxonomy::slug.eq(handler.slug().to_owned()))
123        .fetch(pool)
124        .await?;
125    if let Some(mut row) = existing.pop() {
126        row.verbose_name = handler.verbose_name().to_owned();
127        row.hierarchical = handler.hierarchical();
128        row.max_depth = handler.max_depth().max(1);
129        row.icon = handler.icon().unwrap_or_default().to_owned();
130        row.description = handler.description().unwrap_or_default().to_owned();
131        row.ext_table = handler.ext_table().unwrap_or_default().to_owned();
132        row.save(pool).await?;
133    } else {
134        let mut row = Taxonomy {
135            id: Auto::Unset,
136            slug: handler.slug().to_owned(),
137            verbose_name: handler.verbose_name().to_owned(),
138            hierarchical: handler.hierarchical(),
139            max_depth: handler.max_depth().max(1),
140            icon: handler.icon().unwrap_or_default().to_owned(),
141            description: handler.description().unwrap_or_default().to_owned(),
142            ext_table: handler.ext_table().unwrap_or_default().to_owned(),
143            created_at: Auto::Unset,
144            updated_at: Auto::Unset,
145        };
146        row.insert(pool).await?;
147    }
148    Ok(())
149}
150
151/// Every registered vocabulary, from the DB (the runtime source of truth,
152/// seeded from handlers), ordered by slug.
153///
154/// # Errors
155/// Propagates query failures.
156pub async fn taxonomies(pool: &Pool) -> Result<Vec<Taxonomy>, rustango::sql::ExecError> {
157    use rustango::sql::FetcherPool as _;
158    Taxonomy::objects()
159        .order_by(&[("slug", false)])
160        .fetch(pool)
161        .await
162}
163
164/// The `cms_taxonomy` row for `slug`, if seeded.
165///
166/// # Errors
167/// Propagates query failures.
168pub async fn find_taxonomy(
169    pool: &Pool,
170    slug: &str,
171) -> Result<Option<Taxonomy>, rustango::sql::ExecError> {
172    use rustango::core::Column as _;
173    Taxonomy::objects()
174        .where_(Taxonomy::slug.eq(slug.to_owned()))
175        .first(pool)
176        .await
177}
178
179/// The built-in hierarchical `category` vocabulary shipped with every
180/// tenant. Base columns only — name, description,
181/// featured image, thumbnail, parent. The flat [`page_tag`](crate::page_tag)
182/// story stays the tags vocabulary.
183#[derive(Default)]
184pub struct CategoryTaxonomy;
185
186impl TaxonomyHandler for CategoryTaxonomy {
187    fn slug(&self) -> &'static str {
188        "category"
189    }
190    fn verbose_name(&self) -> &'static str {
191        "Categories"
192    }
193    fn hierarchical(&self) -> bool {
194        true
195    }
196    fn icon(&self) -> Option<&'static str> {
197        Some("category")
198    }
199    fn description(&self) -> Option<&'static str> {
200        Some("Hierarchical content categories.")
201    }
202}
203
204crate::register_taxonomy!(CategoryTaxonomy);
205
206#[cfg(all(test, feature = "sqlite"))]
207mod tests {
208    use super::*;
209    use rustango::core::Model as _;
210    use rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect;
211
212    #[test]
213    fn built_in_category_is_registered() {
214        let found = registered_handlers().any(|h| h.slug() == "category");
215        assert!(found, "built-in category vocabulary must be registered");
216        let h = find_handler("category").expect("handler");
217        assert!(h.hierarchical());
218        assert_eq!(h.verbose_name(), "Categories");
219    }
220
221    #[tokio::test]
222    async fn upsert_taxonomy_is_idempotent_find_or_create() {
223        let pool = Pool::connect("sqlite::memory:").await.expect("pool");
224        let ddl = create_table_if_not_exists_sql_with_dialect(pool.dialect(), &Taxonomy::SCHEMA);
225        for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
226            rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
227                .await
228                .expect("ddl");
229        }
230        let h = CategoryTaxonomy;
231        upsert_taxonomy(&pool, &h).await.expect("first");
232        upsert_taxonomy(&pool, &h).await.expect("second");
233        let all = taxonomies(&pool).await.expect("list");
234        assert_eq!(
235            all.iter().filter(|t| t.slug == "category").count(),
236            1,
237            "one row, not duplicated"
238        );
239        let cat = find_taxonomy(&pool, "category")
240            .await
241            .expect("q")
242            .expect("row");
243        assert!(cat.hierarchical);
244        assert_eq!(cat.verbose_name, "Categories");
245    }
246}