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/// Returns whether anything changed.
116///
117/// # Errors
118/// Propagates query / write failures.
119pub async fn replace_for_taxonomy(
120    pool: &Pool,
121    page_id: i64,
122    taxonomy_id: i64,
123    category_ids: &[i64],
124) -> Result<bool, rustango::sql::ExecError> {
125    let existing: Vec<PageCategory> = PageCategory::objects()
126        .where_(PageCategory::page_id.eq(page_id))
127        .where_(PageCategory::taxonomy_id.eq(taxonomy_id))
128        .fetch(pool)
129        .await?;
130    let desired: std::collections::HashSet<i64> = category_ids.iter().copied().collect();
131    let mut changed = false;
132
133    for row in &existing {
134        if !desired.contains(&row.category_id) {
135            row.clone().delete(pool).await?;
136            changed = true;
137        }
138    }
139    let have: std::collections::HashMap<i64, PageCategory> =
140        existing.into_iter().map(|r| (r.category_id, r)).collect();
141
142    for (idx, cid) in category_ids.iter().enumerate() {
143        if let Some(row) = have.get(cid) {
144            if row.sort_order != idx as i32 {
145                let mut r = row.clone();
146                r.sort_order = idx as i32;
147                r.save(pool).await?;
148                changed = true;
149            }
150        } else {
151            let mut r = PageCategory {
152                id: Auto::Unset,
153                page_id,
154                category_id: *cid,
155                taxonomy_id,
156                sort_order: idx as i32,
157                created_at: Auto::Unset,
158            };
159            r.insert(pool).await?;
160            changed = true;
161        }
162    }
163    Ok(changed)
164}
165
166/// Delete every assignment referencing `category_id` (category deletion
167/// cascade), inside the caller's transaction.
168///
169/// # Errors
170/// Propagates query / delete failures.
171pub async fn delete_for_category_tx(
172    tx: &mut PoolTx<'_>,
173    category_id: i64,
174) -> Result<(), rustango::sql::ExecError> {
175    let rows: Vec<PageCategory> = PageCategory::objects()
176        .where_(PageCategory::category_id.eq(category_id))
177        .fetch_tx(tx)
178        .await?;
179    for row in rows {
180        row.delete_tx(tx).await?;
181    }
182    Ok(())
183}
184
185/// Delete every assignment for `page_id` (page deletion cascade).
186///
187/// # Errors
188/// Propagates query / delete failures.
189pub async fn delete_for_page(pool: &Pool, page_id: i64) -> Result<(), rustango::sql::ExecError> {
190    let rows: Vec<PageCategory> = PageCategory::objects()
191        .where_(PageCategory::page_id.eq(page_id))
192        .fetch(pool)
193        .await?;
194    for row in rows {
195        row.delete(pool).await?;
196    }
197    Ok(())
198}
199
200/// A page's category as templates see it: enough to show it and
201/// to filter or group by it (`{% if "mugs" in p.categories | map(attribute="slug") %}`).
202#[derive(Debug, Clone, Serialize)]
203pub struct CategoryRef {
204    pub id: i64,
205    pub name: String,
206    pub slug: String,
207    /// The vocabulary's slug, e.g. `category`.
208    pub taxonomy: String,
209}
210
211/// Every category of each page in `page_ids`, in chooser order, grouped by
212/// page id. Three queries whatever the page count; the render uses it for
213/// the page and its children.
214///
215/// # Errors
216/// Propagates query failures.
217pub async fn prefetch_for_pages(
218    pool: &Pool,
219    page_ids: &[i64],
220    locale_id: Option<i64>,
221) -> Result<std::collections::HashMap<i64, Vec<CategoryRef>>, rustango::sql::ExecError> {
222    use std::collections::HashMap;
223    if page_ids.is_empty() {
224        return Ok(HashMap::new());
225    }
226    let links: Vec<PageCategory> = PageCategory::objects()
227        .where_(PageCategory::page_id.is_in(page_ids.iter().copied()))
228        .order_by(&[("page_id", false), ("sort_order", false), ("id", false)])
229        .fetch(pool)
230        .await?;
231    if links.is_empty() {
232        return Ok(HashMap::new());
233    }
234    let cat_ids: std::collections::BTreeSet<i64> = links.iter().map(|l| l.category_id).collect();
235    let cats: HashMap<i64, Category> = Category::objects()
236        .where_(Category::id.is_in(cat_ids.into_iter()))
237        .fetch(pool)
238        .await?
239        .into_iter()
240        .filter_map(|c| c.id.get().copied().map(|id| (id, c)))
241        .collect();
242    let tax_ids: std::collections::BTreeSet<i64> = cats.values().map(|c| c.taxonomy_id).collect();
243    let tax_slugs: HashMap<i64, String> = crate::category::Taxonomy::objects()
244        .where_(crate::category::Taxonomy::id.is_in(tax_ids.into_iter()))
245        .fetch(pool)
246        .await?
247        .into_iter()
248        .filter_map(|t| t.id.get().copied().map(|id| (id, t.slug)))
249        .collect();
250    // #862 — the visitor's language: translated names, one more query.
251    let names: HashMap<i64, String> = match locale_id {
252        Some(lid) => {
253            let ids: Vec<i64> = cats.keys().copied().collect();
254            crate::category_translation::fetch_for_categories(pool, &ids, lid)
255                .await?
256                .into_iter()
257                .filter_map(|(id, mut fields)| fields.remove("name").map(|n| (id, n)))
258                .collect()
259        }
260        None => HashMap::new(),
261    };
262    let mut by_page: HashMap<i64, Vec<CategoryRef>> = HashMap::new();
263    for link in links {
264        let Some(c) = cats.get(&link.category_id) else {
265            continue;
266        };
267        by_page.entry(link.page_id).or_default().push(CategoryRef {
268            id: link.category_id,
269            name: names.get(&link.category_id).cloned().unwrap_or_else(|| c.name.clone()),
270            slug: c.slug.clone(),
271            taxonomy: tax_slugs.get(&c.taxonomy_id).cloned().unwrap_or_default(),
272        });
273    }
274    Ok(by_page)
275}
276
277/// Save a page's categories from the editor's `categories` field:
278/// a JSON array of category ids across every vocabulary. `None` (the
279/// field wasn't posted, e.g. a partial MCP save) leaves the page's
280/// categories alone; an empty array clears them. Ids that aren't
281/// categories are dropped rather than trusted. Returns whether anything
282/// changed.
283///
284/// # Errors
285/// Propagates query / write failures.
286pub async fn save_from_form(
287    pool: &Pool,
288    page_id: i64,
289    raw: Option<&str>,
290) -> Result<bool, rustango::sql::ExecError> {
291    let Some(raw) = raw else {
292        return Ok(false);
293    };
294    let wanted = parse_id_list(raw);
295    let cats: Vec<Category> = if wanted.is_empty() {
296        Vec::new()
297    } else {
298        Category::objects()
299            .where_(Category::id.is_in(wanted.iter().copied()))
300            .fetch(pool)
301            .await?
302    };
303    let taxonomy_of: std::collections::HashMap<i64, i64> = cats
304        .iter()
305        .filter_map(|c| c.id.get().copied().map(|id| (id, c.taxonomy_id)))
306        .collect();
307    let mut changed = false;
308    for tax in crate::category::taxonomies(pool).await? {
309        let Some(tax_id) = tax.id.get().copied() else {
310            continue;
311        };
312        let ids: Vec<i64> = wanted
313            .iter()
314            .copied()
315            .filter(|id| taxonomy_of.get(id) == Some(&tax_id))
316            .collect();
317        changed |= replace_for_taxonomy(pool, page_id, tax_id, &ids).await?;
318    }
319    Ok(changed)
320}
321
322/// Whether [`save_from_form`] with `raw` would change the page's
323/// categories (membership or order within a vocabulary), judged without
324/// writing.
325///
326/// # Errors
327/// Propagates query failures.
328pub async fn form_differs(pool: &Pool, page_id: i64, raw: &str) -> Result<bool, rustango::sql::ExecError> {
329    use std::collections::BTreeMap;
330    let wanted = parse_id_list(raw);
331    let cats: Vec<Category> = if wanted.is_empty() {
332        Vec::new()
333    } else {
334        Category::objects()
335            .where_(Category::id.is_in(wanted.iter().copied()))
336            .fetch(pool)
337            .await?
338    };
339    let taxonomy_of: std::collections::HashMap<i64, i64> = cats
340        .iter()
341        .filter_map(|c| c.id.get().copied().map(|id| (id, c.taxonomy_id)))
342        .collect();
343    let mut want: BTreeMap<i64, Vec<(i64, i32)>> = BTreeMap::new();
344    for id in wanted {
345        if let Some(tax) = taxonomy_of.get(&id) {
346            let list = want.entry(*tax).or_default();
347            let idx = i32::try_from(list.len()).unwrap_or(i32::MAX);
348            list.push((id, idx));
349        }
350    }
351    let mut rows: Vec<PageCategory> = PageCategory::objects()
352        .where_(PageCategory::page_id.eq(page_id))
353        .fetch(pool)
354        .await?;
355    rows.sort_by_key(|r| (r.taxonomy_id, r.sort_order));
356    let mut have: BTreeMap<i64, Vec<(i64, i32)>> = BTreeMap::new();
357    for r in rows {
358        have.entry(r.taxonomy_id).or_default().push((r.category_id, r.sort_order));
359    }
360    Ok(want != have)
361}
362
363/// One vocabulary's choices in the page editor.
364#[derive(Debug, Serialize)]
365pub struct EditorGroup {
366    pub taxonomy: String,
367    pub options: Vec<EditorOption>,
368}
369
370/// One category checkbox in the page editor.
371#[derive(Debug, Serialize)]
372pub struct EditorOption {
373    pub id: i64,
374    pub name: String,
375    /// Nesting level, for indenting child categories.
376    pub depth: i32,
377    pub checked: bool,
378}
379
380/// The page editor's category choices: each vocabulary that has
381/// categories, in tree order, with the page's current ones checked
382/// (`page_id` is `None` on the new-page form). Also returns the checked
383/// ids as the JSON array the form posts back.
384///
385/// # Errors
386/// Propagates query failures.
387pub async fn editor_groups(
388    pool: &Pool,
389    page_id: Option<i64>,
390) -> Result<(Vec<EditorGroup>, String), rustango::sql::ExecError> {
391    let chosen: std::collections::HashSet<i64> = match page_id {
392        Some(pid) => PageCategory::objects()
393            .where_(PageCategory::page_id.eq(pid))
394            .fetch(pool)
395            .await?
396            .into_iter()
397            .map(|r| r.category_id)
398            .collect(),
399        None => std::collections::HashSet::new(),
400    };
401    let all: Vec<Category> = Category::objects()
402        .order_by(&[("path", false)])
403        .fetch(pool)
404        .await?;
405    let mut groups = Vec::new();
406    for tax in crate::category::taxonomies(pool).await? {
407        let Some(tax_id) = tax.id.get().copied() else {
408            continue;
409        };
410        let options: Vec<EditorOption> = all
411            .iter()
412            .filter(|c| c.taxonomy_id == tax_id)
413            .filter_map(|c| {
414                let id = c.id.get().copied()?;
415                Some(EditorOption {
416                    id,
417                    name: c.name.clone(),
418                    depth: c.depth,
419                    checked: chosen.contains(&id),
420                })
421            })
422            .collect();
423        if !options.is_empty() {
424            groups.push(EditorGroup { taxonomy: tax.verbose_name, options });
425        }
426    }
427    let checked: Vec<String> = groups
428        .iter()
429        .flat_map(|g| g.options.iter())
430        .filter(|o| o.checked)
431        .map(|o| o.id.to_string())
432        .collect();
433    let json = serde_json::to_string(&checked).unwrap_or_else(|_| "[]".to_owned());
434    Ok((groups, json))
435}
436
437/// The page editor's category field name.
438pub const FORM_KEY: &str = "categories";
439
440/// A JSON array of ids, as numbers or strings; anything else is ignored,
441/// duplicates keep their first position.
442pub(crate) fn parse_id_list(raw: &str) -> Vec<i64> {
443    let Ok(serde_json::Value::Array(items)) = serde_json::from_str::<serde_json::Value>(raw) else {
444        return Vec::new();
445    };
446    let mut seen = std::collections::HashSet::new();
447    items
448        .iter()
449        .filter_map(|v| v.as_i64().or_else(|| v.as_str().and_then(|s| s.trim().parse().ok())))
450        .filter(|id| seen.insert(*id))
451        .collect()
452}
453
454#[cfg(test)]
455mod form_tests {
456    use super::parse_id_list;
457
458    #[test]
459    fn id_lists_accept_numbers_and_strings_and_drop_the_rest() {
460        assert_eq!(parse_id_list(r#"["3", 5, "x", null, "3"]"#), vec![3, 5]);
461        assert!(parse_id_list("not json").is_empty());
462        assert!(parse_id_list("{}").is_empty());
463    }
464}
465
466#[cfg(all(test, feature = "sqlite"))]
467mod prefetch_tests {
468    use super::*;
469    use rustango::core::Model as _;
470
471    /// The render gets each page's categories, in chooser order,
472    /// with their vocabulary; a page with none is absent.
473    #[tokio::test]
474    async fn prefetch_groups_categories_by_page_in_order() {
475        let pool = Pool::connect("sqlite::memory:").await.expect("pool");
476        for schema in [
477            &crate::page_type_model::PageType::SCHEMA,
478            &crate::media::Media::SCHEMA,
479            &crate::theme::Theme::SCHEMA,
480            &crate::page::Page::SCHEMA,
481            &crate::category::Taxonomy::SCHEMA,
482            &Category::SCHEMA,
483            &PageCategory::SCHEMA,
484            &crate::locale::Locale::SCHEMA,
485            &crate::category_translation::CategoryTranslation::SCHEMA,
486        ] {
487            let sql = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(pool.dialect(), schema);
488            for stmt in sql.split(';').map(str::trim).filter(|s| !s.is_empty()) {
489                rustango::sql::raw_execute_pool(&pool, stmt, Vec::new()).await.expect("ddl");
490            }
491        }
492        for sql in [
493            "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, '[]')",
494            "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', '', '')",
495        ] {
496            rustango::sql::raw_execute_pool(&pool, sql, Vec::new()).await.expect("row");
497        }
498        crate::category::upsert_taxonomy(&pool, &crate::category::CategoryTaxonomy).await.expect("taxonomy");
499        let tax = crate::category::find_taxonomy(&pool, "category").await.expect("q").expect("row");
500        let tax_id = tax.id.get().copied().expect("id");
501        let mut ids = Vec::new();
502        for name in ["Mugs", "Plates"] {
503            let c = crate::category::model::create(
504                &pool,
505                tax_id,
506                crate::category::NewCategory {
507                    name: name.to_owned(),
508                    slug: String::new(),
509                    description: String::new(),
510                    parent_id: None,
511                    featured_image_id: None,
512                    thumbnail_id: None,
513                },
514            )
515            .await
516            .expect("category");
517            ids.push(c.id.get().copied().expect("id"));
518        }
519        save_from_form(&pool, 1, Some(&format!("[{}, \"{}\"]", ids[1], ids[0]))).await.expect("save");
520
521        let by_page = prefetch_for_pages(&pool, &[1, 2], None).await.expect("prefetch");
522        let names: Vec<(&str, &str, &str)> = by_page[&1]
523            .iter()
524            .map(|c| (c.name.as_str(), c.slug.as_str(), c.taxonomy.as_str()))
525            .collect();
526        assert_eq!(names, [("Plates", "plates", "category"), ("Mugs", "mugs", "category")]);
527        assert!(!by_page.contains_key(&2));
528
529        // #862 — in another language, a translated name replaces the
530        // original; an untranslated one keeps it.
531        rustango::sql::raw_execute_pool(
532            &pool,
533            "INSERT INTO cms_locale (id, code, name, is_default, active, sort_order) VALUES (2, 'fr', 'Français', 0, 1, 1)",
534            Vec::new(),
535        )
536        .await
537        .expect("locale");
538        rustango::sql::raw_execute_pool(
539            &pool,
540            &format!(
541                "INSERT INTO cms_category_translation (category_id, locale_id, field_path, value, updated_at) VALUES ({}, 2, 'name', 'Assiettes', '2026-01-01T00:00:00Z')",
542                ids[1]
543            ),
544            Vec::new(),
545        )
546        .await
547        .expect("translation");
548        let fr: Vec<String> = prefetch_for_pages(&pool, &[1], Some(2)).await.expect("q")[&1]
549            .iter()
550            .map(|c| c.name.clone())
551            .collect();
552        assert_eq!(fr, ["Assiettes", "Mugs"]);
553
554        // A partial save (no field) keeps them; an empty list clears them.
555        save_from_form(&pool, 1, None).await.expect("untouched");
556        assert_eq!(prefetch_for_pages(&pool, &[1], None).await.expect("q")[&1].len(), 2);
557        save_from_form(&pool, 1, Some("[]")).await.expect("clear");
558        assert!(prefetch_for_pages(&pool, &[1], None).await.expect("q").is_empty());
559    }
560}