Skip to main content

rustango_cms/
page_tag.rs

1//! Page tag system.
2//!
3//! Tags are how editors organize blog-style content. Each \`PageTag\`
4//! row is a (page_id, name) pair; tag names are tenant-global
5//! strings (lowercased + trimmed on insert).
6//!
7//! Editor UI: a multi-select on the Promote tab with autocomplete
8//! from existing tags. List + API filter chips lookup by tag.
9
10use chrono::{DateTime, Utc};
11use rustango::sql::Auto;
12use rustango::Model;
13use serde::{Deserialize, Serialize};
14
15#[derive(Model, Debug, Clone, Serialize, Deserialize)]
16#[rustango(
17    table = "cms_page_tag",
18    app = "cms",
19    display = "name",
20    admin(
21        list_display = "page_id, name",
22        ordering = "name, page_id",
23        list_filter = "name",
24    )
25)]
26pub struct PageTag {
27    #[rustango(primary_key)]
28    pub id: Auto<i64>,
29
30    #[rustango(fk = "cms_page", on = "id", index)]
31    pub page_id: i64,
32
33    /// Tag name, lowercased + trimmed. Per-page-unique enforced at
34    /// the application layer (composite unique on the SQL side is
35    /// dialect-drifty in our ORM today).
36    #[rustango(max_length = 64, index)]
37    pub name: String,
38
39    #[rustango(auto_now_add)]
40    pub created_at: Auto<DateTime<Utc>>,
41}
42
43/// Normalize a tag name: trim + lowercase + collapse internal
44/// whitespace to single dashes (so \"Hello World\" → \"hello-world\").
45#[must_use]
46pub fn normalize_name(raw: &str) -> String {
47    raw.split_whitespace()
48        .collect::<Vec<_>>()
49        .join("-")
50        .to_lowercase()
51}
52
53/// Every tag for a page, in alphabetical order.
54///
55/// # Errors
56/// Driver / query failures.
57pub async fn tags_for_page(
58    pool: &rustango::sql::Pool,
59    page_id: i64,
60) -> Result<Vec<PageTag>, rustango::sql::ExecError> {
61    use rustango::core::Column as _;
62    use rustango::sql::FetcherPool as _;
63    PageTag::objects()
64        .where_(PageTag::page_id.eq(page_id))
65        .order_by(&[("name", false)])
66        .fetch(pool)
67        .await
68}
69
70/// `names` normalized via [`normalize_name`], empties and repeats dropped.
71fn wanted_names(names: &[String]) -> Vec<String> {
72    let mut wanted: Vec<String> = Vec::new();
73    for n in names {
74        let norm = normalize_name(n);
75        if !norm.is_empty() && !wanted.contains(&norm) {
76            wanted.push(norm);
77        }
78    }
79    wanted
80}
81
82/// Whether [`replace_tags`] with `names` would change the page's tags,
83/// judged without writing.
84///
85/// # Errors
86/// Driver / query failures.
87pub async fn tags_differ(
88    pool: &rustango::sql::Pool,
89    page_id: i64,
90    names: &[String],
91) -> Result<bool, rustango::sql::ExecError> {
92    let mut wanted = wanted_names(names);
93    let mut have: Vec<String> = tags_for_page(pool, page_id).await?.into_iter().map(|t| t.name).collect();
94    wanted.sort_unstable();
95    have.sort_unstable();
96    Ok(wanted != have)
97}
98
99/// Replace the tag set for a page with `names`, writing only the
100/// difference: tags no longer named are deleted, new ones inserted, and
101/// an unchanged set writes nothing. Tag names are normalized via
102/// [`normalize_name`]. Returns whether anything changed.
103///
104/// # Errors
105/// Driver / query failures.
106pub async fn replace_tags(
107    pool: &rustango::sql::Pool,
108    page_id: i64,
109    names: &[String],
110) -> Result<bool, rustango::sql::ExecError> {
111    use rustango::core::Column as _;
112    use rustango::sql::FetcherPool as _;
113    let wanted = wanted_names(names);
114    let existing: Vec<PageTag> = PageTag::objects()
115        .where_(PageTag::page_id.eq(page_id))
116        .fetch(pool)
117        .await?;
118    let mut changed = false;
119    let mut kept = std::collections::HashSet::new();
120    for row in existing {
121        // A duplicate row (older versions could leave one) goes too.
122        if wanted.contains(&row.name) && kept.insert(row.name.clone()) {
123            continue;
124        }
125        row.delete(pool).await?;
126        changed = true;
127    }
128    for name in wanted {
129        if kept.contains(&name) {
130            continue;
131        }
132        let mut row = PageTag {
133            id: Auto::Unset,
134            page_id,
135            name,
136            created_at: Auto::Unset,
137        };
138        row.insert(pool).await?;
139        changed = true;
140    }
141    Ok(changed)
142}
143
144/// Pre-fetch every tag attached to any page in `page_ids`, grouped
145/// by `page_id`. Single `IN (…)` query instead of N point
146/// lookups so the public-render handler can join tags onto every
147/// `children` ctx entry without an N+1.
148///
149/// Tags within each bucket arrive in `name` ascending order so
150/// templates iterate predictably.
151///
152/// # Errors
153/// Driver / query failures.
154pub async fn prefetch_for_pages(
155    pool: &rustango::sql::Pool,
156    page_ids: &[i64],
157) -> Result<std::collections::HashMap<i64, Vec<PageTag>>, rustango::sql::ExecError> {
158    use rustango::core::Column as _;
159    use rustango::sql::FetcherPool as _;
160    if page_ids.is_empty() {
161        return Ok(std::collections::HashMap::new());
162    }
163    let rows: Vec<PageTag> = PageTag::objects()
164        .where_(PageTag::page_id.is_in(page_ids.iter().copied()))
165        .order_by(&[("name", false)])
166        .fetch(pool)
167        .await?;
168    let mut by_page: std::collections::HashMap<i64, Vec<PageTag>> =
169        std::collections::HashMap::new();
170    for row in rows {
171        by_page.entry(row.page_id).or_default().push(row);
172    }
173    Ok(by_page)
174}
175
176/// Every page id tagged with `name`.
177///
178/// # Errors
179/// Driver / query failures.
180pub async fn pages_with_tag(
181    pool: &rustango::sql::Pool,
182    name: &str,
183) -> Result<Vec<i64>, rustango::sql::ExecError> {
184    use rustango::core::Column as _;
185    use rustango::sql::FetcherPool as _;
186    let norm = normalize_name(name);
187    let rows: Vec<PageTag> = PageTag::objects()
188        .where_(PageTag::name.eq(norm))
189        .fetch(pool)
190        .await?;
191    Ok(rows.into_iter().map(|r| r.page_id).collect())
192}
193
194/// Every distinct tag in the tenant + its usage count, sorted by
195/// (-count, name).
196///
197/// # Errors
198/// Driver / query failures.
199pub async fn all_tags(
200    pool: &rustango::sql::Pool,
201) -> Result<Vec<(String, usize)>, rustango::sql::ExecError> {
202    use rustango::sql::FetcherPool as _;
203    let rows: Vec<PageTag> = PageTag::objects().fetch(pool).await?;
204    let mut counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
205    for row in rows {
206        *counts.entry(row.name).or_default() += 1;
207    }
208    let mut out: Vec<(String, usize)> = counts.into_iter().collect();
209    out.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
210    Ok(out)
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn normalize_lowercases() {
219        assert_eq!(normalize_name("Hello"), "hello");
220    }
221
222    #[test]
223    fn normalize_collapses_whitespace_to_dash() {
224        assert_eq!(normalize_name("  Hello   World "), "hello-world");
225    }
226
227    #[test]
228    fn normalize_empty_stays_empty() {
229        assert_eq!(normalize_name("   "), "");
230    }
231
232    #[test]
233    fn normalize_idempotent() {
234        let once = normalize_name("Foo Bar");
235        let twice = normalize_name(&once);
236        assert_eq!(once, twice);
237    }
238}