Skip to main content

rustango_cms/category/
assign.rs

1//! Page ↔ category assignments — the `cms_page_category` M2M,
2//! mirroring [`crate::page_snippet_m2m`] / [`crate::page_tag`]. A page can
3//! be filed under many categories across many vocabularies; the join row
4//! denormalizes `taxonomy_id` so the editor can replace one vocabulary's
5//! assignments without touching the others.
6
7use chrono::{DateTime, Utc};
8use rustango::core::Column as _;
9use rustango::sql::{Auto, FetcherPool as _, FetcherTx as _, Pool, PoolTx};
10use rustango::Model;
11use serde::{Deserialize, Serialize};
12
13use crate::category::model::Category;
14
15/// One page↔category link. `(page_id, category_id)` is unique at the app
16/// layer (composite SQL uniqueness is dialect-drifty in the ORM today).
17#[derive(Model, Debug, Clone, Serialize, Deserialize)]
18#[rustango(
19    table = "cms_page_category",
20    app = "cms",
21    display = "category_id",
22    admin(
23        list_display = "page_id, taxonomy_id, category_id, sort_order",
24        ordering = "page_id, taxonomy_id, sort_order",
25        list_filter = "taxonomy_id",
26    )
27)]
28pub struct PageCategory {
29    #[rustango(primary_key)]
30    pub id: Auto<i64>,
31
32    #[rustango(fk = "cms_page", on = "id", index)]
33    pub page_id: i64,
34
35    #[rustango(fk = "cms_category", on = "id", index)]
36    pub category_id: i64,
37
38    /// Denormalized owning vocabulary — lets the editor replace one
39    /// taxonomy's assignments without touching the others.
40    #[rustango(fk = "cms_taxonomy", on = "id", index)]
41    pub taxonomy_id: i64,
42
43    pub sort_order: i32,
44
45    #[rustango(auto_now_add)]
46    pub created_at: Auto<DateTime<Utc>>,
47}
48
49/// Category ids assigned to `page_id` within one taxonomy, in chooser
50/// order.
51///
52/// # Errors
53/// Propagates query failures.
54pub async fn category_ids_for_page(
55    pool: &Pool,
56    page_id: i64,
57    taxonomy_id: i64,
58) -> Result<Vec<i64>, rustango::sql::ExecError> {
59    let rows = PageCategory::objects()
60        .where_(PageCategory::page_id.eq(page_id))
61        .where_(PageCategory::taxonomy_id.eq(taxonomy_id))
62        .order_by(&[("sort_order", false), ("id", false)])
63        .fetch(pool)
64        .await?;
65    Ok(rows.into_iter().map(|r| r.category_id).collect())
66}
67
68/// Full [`Category`] rows assigned to `page_id` within one taxonomy, in
69/// chooser order (missing rows skipped). The template-time read.
70///
71/// # Errors
72/// Propagates query failures.
73pub async fn categories_for_page(
74    pool: &Pool,
75    page_id: i64,
76    taxonomy_id: i64,
77) -> Result<Vec<Category>, rustango::sql::ExecError> {
78    let ids = category_ids_for_page(pool, page_id, taxonomy_id).await?;
79    if ids.is_empty() {
80        return Ok(Vec::new());
81    }
82    let mut cats: Vec<Category> = Category::objects()
83        .where_(Category::id.is_in(ids.clone()))
84        .fetch(pool)
85        .await?;
86    let order: std::collections::HashMap<i64, usize> =
87        ids.iter().enumerate().map(|(i, id)| (*id, i)).collect();
88    cats.sort_by_key(|c| {
89        order
90            .get(&c.id.get().copied().unwrap_or_default())
91            .copied()
92            .unwrap_or(usize::MAX)
93    });
94    Ok(cats)
95}
96
97/// Page ids filed under `category_id`.
98///
99/// # Errors
100/// Propagates query failures.
101pub async fn pages_in_category(
102    pool: &Pool,
103    category_id: i64,
104) -> Result<Vec<i64>, rustango::sql::ExecError> {
105    let rows = PageCategory::objects()
106        .where_(PageCategory::category_id.eq(category_id))
107        .fetch(pool)
108        .await?;
109    Ok(rows.into_iter().map(|r| r.page_id).collect())
110}
111
112/// Replace all of a page's assignments **within one taxonomy** with
113/// `category_ids` (order preserved), leaving other vocabularies' links
114/// intact. Diff-based — mirrors [`crate::page_snippet_m2m::replace_all`].
115///
116/// # Errors
117/// Propagates query / write failures.
118pub async fn replace_for_taxonomy(
119    pool: &Pool,
120    page_id: i64,
121    taxonomy_id: i64,
122    category_ids: &[i64],
123) -> Result<(), rustango::sql::ExecError> {
124    let existing: Vec<PageCategory> = PageCategory::objects()
125        .where_(PageCategory::page_id.eq(page_id))
126        .where_(PageCategory::taxonomy_id.eq(taxonomy_id))
127        .fetch(pool)
128        .await?;
129    let desired: std::collections::HashSet<i64> = category_ids.iter().copied().collect();
130
131    for row in &existing {
132        if !desired.contains(&row.category_id) {
133            row.clone().delete_pool(pool).await?;
134        }
135    }
136    let have: std::collections::HashMap<i64, PageCategory> =
137        existing.into_iter().map(|r| (r.category_id, r)).collect();
138
139    for (idx, cid) in category_ids.iter().enumerate() {
140        if let Some(row) = have.get(cid) {
141            if row.sort_order != idx as i32 {
142                let mut r = row.clone();
143                r.sort_order = idx as i32;
144                r.save_pool(pool).await?;
145            }
146        } else {
147            let mut r = PageCategory {
148                id: Auto::Unset,
149                page_id,
150                category_id: *cid,
151                taxonomy_id,
152                sort_order: idx as i32,
153                created_at: Auto::Unset,
154            };
155            r.insert_pool(pool).await?;
156        }
157    }
158    Ok(())
159}
160
161/// Delete every assignment referencing `category_id` (category deletion
162/// cascade), inside the caller's transaction.
163///
164/// # Errors
165/// Propagates query / delete failures.
166pub async fn delete_for_category_tx(
167    tx: &mut PoolTx<'_>,
168    category_id: i64,
169) -> Result<(), rustango::sql::ExecError> {
170    let rows: Vec<PageCategory> = PageCategory::objects()
171        .where_(PageCategory::category_id.eq(category_id))
172        .fetch_tx(tx)
173        .await?;
174    for row in rows {
175        row.delete_tx(tx).await?;
176    }
177    Ok(())
178}
179
180/// Delete every assignment for `page_id` (page deletion cascade).
181///
182/// # Errors
183/// Propagates query / delete failures.
184pub async fn delete_for_page(pool: &Pool, page_id: i64) -> Result<(), rustango::sql::ExecError> {
185    let rows: Vec<PageCategory> = PageCategory::objects()
186        .where_(PageCategory::page_id.eq(page_id))
187        .fetch(pool)
188        .await?;
189    for row in rows {
190        row.delete_pool(pool).await?;
191    }
192    Ok(())
193}
194
195/// A page's category as templates see it: enough to show it and
196/// to filter or group by it (`{% if "mugs" in p.categories | map(attribute="slug") %}`).
197#[derive(Debug, Clone, Serialize)]
198pub struct CategoryRef {
199    pub id: i64,
200    pub name: String,
201    pub slug: String,
202    /// The vocabulary's slug, e.g. `category`.
203    pub taxonomy: String,
204}
205
206/// Every category of each page in `page_ids`, in chooser order, grouped by
207/// page id. Three queries whatever the page count; the render uses it for
208/// the page and its children.
209///
210/// # Errors
211/// Propagates query failures.
212pub async fn prefetch_for_pages(
213    pool: &Pool,
214    page_ids: &[i64],
215    locale_id: Option<i64>,
216) -> Result<std::collections::HashMap<i64, Vec<CategoryRef>>, rustango::sql::ExecError> {
217    use std::collections::HashMap;
218    if page_ids.is_empty() {
219        return Ok(HashMap::new());
220    }
221    let links: Vec<PageCategory> = PageCategory::objects()
222        .where_(PageCategory::page_id.is_in(page_ids.iter().copied()))
223        .order_by(&[("page_id", false), ("sort_order", false), ("id", false)])
224        .fetch(pool)
225        .await?;
226    if links.is_empty() {
227        return Ok(HashMap::new());
228    }
229    let cat_ids: std::collections::BTreeSet<i64> = links.iter().map(|l| l.category_id).collect();
230    let cats: HashMap<i64, Category> = Category::objects()
231        .where_(Category::id.is_in(cat_ids.into_iter()))
232        .fetch(pool)
233        .await?
234        .into_iter()
235        .filter_map(|c| c.id.get().copied().map(|id| (id, c)))
236        .collect();
237    let tax_ids: std::collections::BTreeSet<i64> = cats.values().map(|c| c.taxonomy_id).collect();
238    let tax_slugs: HashMap<i64, String> = crate::category::Taxonomy::objects()
239        .where_(crate::category::Taxonomy::id.is_in(tax_ids.into_iter()))
240        .fetch(pool)
241        .await?
242        .into_iter()
243        .filter_map(|t| t.id.get().copied().map(|id| (id, t.slug)))
244        .collect();
245    // #862 — the visitor's language: translated names, one more query.
246    let names: HashMap<i64, String> = match locale_id {
247        Some(lid) => {
248            let ids: Vec<i64> = cats.keys().copied().collect();
249            crate::category_translation::fetch_for_categories(pool, &ids, lid)
250                .await?
251                .into_iter()
252                .filter_map(|(id, mut fields)| fields.remove("name").map(|n| (id, n)))
253                .collect()
254        }
255        None => HashMap::new(),
256    };
257    let mut by_page: HashMap<i64, Vec<CategoryRef>> = HashMap::new();
258    for link in links {
259        let Some(c) = cats.get(&link.category_id) else {
260            continue;
261        };
262        by_page.entry(link.page_id).or_default().push(CategoryRef {
263            id: link.category_id,
264            name: names.get(&link.category_id).cloned().unwrap_or_else(|| c.name.clone()),
265            slug: c.slug.clone(),
266            taxonomy: tax_slugs.get(&c.taxonomy_id).cloned().unwrap_or_default(),
267        });
268    }
269    Ok(by_page)
270}
271
272/// Save a page's categories from the editor's `categories` field:
273/// a JSON array of category ids across every vocabulary. `None` (the
274/// field wasn't posted, e.g. a partial MCP save) leaves the page's
275/// categories alone; an empty array clears them. Ids that aren't
276/// categories are dropped rather than trusted.
277///
278/// # Errors
279/// Propagates query / write failures.
280pub async fn save_from_form(
281    pool: &Pool,
282    page_id: i64,
283    raw: Option<&str>,
284) -> Result<(), rustango::sql::ExecError> {
285    let Some(raw) = raw else {
286        return Ok(());
287    };
288    let wanted = parse_id_list(raw);
289    let cats: Vec<Category> = if wanted.is_empty() {
290        Vec::new()
291    } else {
292        Category::objects()
293            .where_(Category::id.is_in(wanted.iter().copied()))
294            .fetch(pool)
295            .await?
296    };
297    let taxonomy_of: std::collections::HashMap<i64, i64> = cats
298        .iter()
299        .filter_map(|c| c.id.get().copied().map(|id| (id, c.taxonomy_id)))
300        .collect();
301    for tax in crate::category::taxonomies(pool).await? {
302        let Some(tax_id) = tax.id.get().copied() else {
303            continue;
304        };
305        let ids: Vec<i64> = wanted
306            .iter()
307            .copied()
308            .filter(|id| taxonomy_of.get(id) == Some(&tax_id))
309            .collect();
310        replace_for_taxonomy(pool, page_id, tax_id, &ids).await?;
311    }
312    Ok(())
313}
314
315/// One vocabulary's choices in the page editor.
316#[derive(Debug, Serialize)]
317pub struct EditorGroup {
318    pub taxonomy: String,
319    pub options: Vec<EditorOption>,
320}
321
322/// One category checkbox in the page editor.
323#[derive(Debug, Serialize)]
324pub struct EditorOption {
325    pub id: i64,
326    pub name: String,
327    /// Nesting level, for indenting child categories.
328    pub depth: i32,
329    pub checked: bool,
330}
331
332/// The page editor's category choices: each vocabulary that has
333/// categories, in tree order, with the page's current ones checked
334/// (`page_id` is `None` on the new-page form). Also returns the checked
335/// ids as the JSON array the form posts back.
336///
337/// # Errors
338/// Propagates query failures.
339pub async fn editor_groups(
340    pool: &Pool,
341    page_id: Option<i64>,
342) -> Result<(Vec<EditorGroup>, String), rustango::sql::ExecError> {
343    let chosen: std::collections::HashSet<i64> = match page_id {
344        Some(pid) => PageCategory::objects()
345            .where_(PageCategory::page_id.eq(pid))
346            .fetch(pool)
347            .await?
348            .into_iter()
349            .map(|r| r.category_id)
350            .collect(),
351        None => std::collections::HashSet::new(),
352    };
353    let all: Vec<Category> = Category::objects()
354        .order_by(&[("path", false)])
355        .fetch(pool)
356        .await?;
357    let mut groups = Vec::new();
358    for tax in crate::category::taxonomies(pool).await? {
359        let Some(tax_id) = tax.id.get().copied() else {
360            continue;
361        };
362        let options: Vec<EditorOption> = all
363            .iter()
364            .filter(|c| c.taxonomy_id == tax_id)
365            .filter_map(|c| {
366                let id = c.id.get().copied()?;
367                Some(EditorOption {
368                    id,
369                    name: c.name.clone(),
370                    depth: c.depth,
371                    checked: chosen.contains(&id),
372                })
373            })
374            .collect();
375        if !options.is_empty() {
376            groups.push(EditorGroup { taxonomy: tax.verbose_name, options });
377        }
378    }
379    let checked: Vec<String> = groups
380        .iter()
381        .flat_map(|g| g.options.iter())
382        .filter(|o| o.checked)
383        .map(|o| o.id.to_string())
384        .collect();
385    let json = serde_json::to_string(&checked).unwrap_or_else(|_| "[]".to_owned());
386    Ok((groups, json))
387}
388
389/// The page editor's category field name.
390pub const FORM_KEY: &str = "categories";
391
392/// A JSON array of ids, as numbers or strings; anything else is ignored,
393/// duplicates keep their first position.
394fn parse_id_list(raw: &str) -> Vec<i64> {
395    let Ok(serde_json::Value::Array(items)) = serde_json::from_str::<serde_json::Value>(raw) else {
396        return Vec::new();
397    };
398    let mut seen = std::collections::HashSet::new();
399    items
400        .iter()
401        .filter_map(|v| v.as_i64().or_else(|| v.as_str().and_then(|s| s.trim().parse().ok())))
402        .filter(|id| seen.insert(*id))
403        .collect()
404}
405
406#[cfg(test)]
407mod form_tests {
408    use super::parse_id_list;
409
410    #[test]
411    fn id_lists_accept_numbers_and_strings_and_drop_the_rest() {
412        assert_eq!(parse_id_list(r#"["3", 5, "x", null, "3"]"#), vec![3, 5]);
413        assert!(parse_id_list("not json").is_empty());
414        assert!(parse_id_list("{}").is_empty());
415    }
416}
417
418#[cfg(all(test, feature = "sqlite"))]
419mod prefetch_tests {
420    use super::*;
421    use rustango::core::Model as _;
422
423    /// The render gets each page's categories, in chooser order,
424    /// with their vocabulary; a page with none is absent.
425    #[tokio::test]
426    async fn prefetch_groups_categories_by_page_in_order() {
427        let pool = Pool::connect("sqlite::memory:").await.expect("pool");
428        for schema in [
429            &crate::page_type_model::PageType::SCHEMA,
430            &crate::media::Media::SCHEMA,
431            &crate::theme::Theme::SCHEMA,
432            &crate::page::Page::SCHEMA,
433            &crate::category::Taxonomy::SCHEMA,
434            &Category::SCHEMA,
435            &PageCategory::SCHEMA,
436            &crate::locale::Locale::SCHEMA,
437            &crate::category_translation::CategoryTranslation::SCHEMA,
438        ] {
439            let sql = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(pool.dialect(), schema);
440            for stmt in sql.split(';').map(str::trim).filter(|s| !s.is_empty()) {
441                rustango::sql::raw_execute_pool(&pool, stmt, Vec::new()).await.expect("ddl");
442            }
443        }
444        for sql in [
445            "INSERT INTO cms_page_type (id, app_label, type_name, verbose_name, default_template, is_creatable, allowed_parent_types) VALUES (1, 'cms', 'P', 'P', 'p.html', 1, '[]')",
446            "INSERT INTO cms_page (id, page_type_id, title, slug, path, depth, sort_order, status, seo_title, seo_description) VALUES (1, 1, 'A', 'a', '0001/', 1, 0, 'published', '', ''), (2, 1, 'B', 'b', '0002/', 1, 0, 'published', '', '')",
447        ] {
448            rustango::sql::raw_execute_pool(&pool, sql, Vec::new()).await.expect("row");
449        }
450        crate::category::upsert_taxonomy(&pool, &crate::category::CategoryTaxonomy).await.expect("taxonomy");
451        let tax = crate::category::find_taxonomy(&pool, "category").await.expect("q").expect("row");
452        let tax_id = tax.id.get().copied().expect("id");
453        let mut ids = Vec::new();
454        for name in ["Mugs", "Plates"] {
455            let c = crate::category::model::create(
456                &pool,
457                tax_id,
458                crate::category::NewCategory {
459                    name: name.to_owned(),
460                    slug: String::new(),
461                    description: String::new(),
462                    parent_id: None,
463                    featured_image_id: None,
464                    thumbnail_id: None,
465                },
466            )
467            .await
468            .expect("category");
469            ids.push(c.id.get().copied().expect("id"));
470        }
471        save_from_form(&pool, 1, Some(&format!("[{}, \"{}\"]", ids[1], ids[0]))).await.expect("save");
472
473        let by_page = prefetch_for_pages(&pool, &[1, 2], None).await.expect("prefetch");
474        let names: Vec<(&str, &str, &str)> = by_page[&1]
475            .iter()
476            .map(|c| (c.name.as_str(), c.slug.as_str(), c.taxonomy.as_str()))
477            .collect();
478        assert_eq!(names, [("Plates", "plates", "category"), ("Mugs", "mugs", "category")]);
479        assert!(!by_page.contains_key(&2));
480
481        // #862 — in another language, a translated name replaces the
482        // original; an untranslated one keeps it.
483        rustango::sql::raw_execute_pool(
484            &pool,
485            "INSERT INTO cms_locale (id, code, name, is_default, active, sort_order) VALUES (2, 'fr', 'Français', 0, 1, 1)",
486            Vec::new(),
487        )
488        .await
489        .expect("locale");
490        rustango::sql::raw_execute_pool(
491            &pool,
492            &format!(
493                "INSERT INTO cms_category_translation (category_id, locale_id, field_path, value, updated_at) VALUES ({}, 2, 'name', 'Assiettes', '2026-01-01T00:00:00Z')",
494                ids[1]
495            ),
496            Vec::new(),
497        )
498        .await
499        .expect("translation");
500        let fr: Vec<String> = prefetch_for_pages(&pool, &[1], Some(2)).await.expect("q")[&1]
501            .iter()
502            .map(|c| c.name.clone())
503            .collect();
504        assert_eq!(fr, ["Assiettes", "Mugs"]);
505
506        // A partial save (no field) keeps them; an empty list clears them.
507        save_from_form(&pool, 1, None).await.expect("untouched");
508        assert_eq!(prefetch_for_pages(&pool, &[1], None).await.expect("q")[&1].len(), 2);
509        save_from_form(&pool, 1, Some("[]")).await.expect("clear");
510        assert!(prefetch_for_pages(&pool, &[1], None).await.expect("q").is_empty());
511    }
512}