Skip to main content

rustango_cms/
menu_item_translation.rs

1//! Per-field, per-locale translation overrides for **menu items**.
2//!
3//! The third member of the family, after [`crate::translation`] (pages)
4//! and [`crate::snippet_translation`] (snippets), and deliberately the
5//! same tall `(row_id, locale_id, field_path, value)` shape so the
6//! admin editor, the fetch helpers and the overlay semantics all
7//! transfer unchanged.
8//!
9//! Menus needed it for two separate reasons:
10//!
11//! * An **authored** label (`cms_menu_item.label`) had nowhere to store
12//!   a translation at all, so a headless client asking for `?locale=fr`
13//!   got English chrome around French content.
14//! * An **empty** label falls back to the target page's title, and that
15//!   fallback was untranslated too — even though the page's own title
16//!   translation was already sitting in `cms_translation`. That half is
17//!   fixed by the resolver reading page translations, not by this table.
18
19use chrono::{DateTime, Utc};
20use rustango::sql::Auto;
21use rustango::Model;
22use serde::{Deserialize, Serialize};
23
24/// One row per `(item_id, locale_id, field_path)`. An empty `value` is
25/// treated as "no override" and the canonical content shows through, so
26/// a partially-translated menu degrades per item rather than blanking.
27#[derive(Model, Debug, Clone, Serialize, Deserialize)]
28#[rustango(
29    table = "cms_menu_item_translation",
30    app = "cms",
31    admin(
32        list_display = "item_id, locale_id, field_path, value, updated_at",
33        ordering = "item_id",
34        list_filter = "locale_id, field_path",
35    )
36)]
37pub struct MenuItemTranslation {
38    #[rustango(primary_key)]
39    pub id: Auto<i64>,
40
41    #[rustango(fk = "cms_menu_item", on = "id", index)]
42    pub item_id: i64,
43
44    #[rustango(fk = "cms_locale", on = "id", index)]
45    pub locale_id: i64,
46
47    /// Field on `cms_menu_item`. `label` in practice; `external_url` is
48    /// accepted too, since a per-locale outbound link (a country site,
49    /// a translated PDF) is a real editorial need.
50    #[rustango(max_length = 64, index)]
51    pub field_path: String,
52
53    /// Localized value. Empty string = "no override".
54    pub value: String,
55
56    #[rustango(auto_now)]
57    pub updated_at: Auto<DateTime<Utc>>,
58}
59
60/// Field paths an editor may translate on a menu item.
61///
62/// Closed on purpose: unlike a snippet's open `data.*` bag, a menu item
63/// has a fixed set of columns, and the submit handler validates against
64/// this list rather than letting a typo create a row that nothing reads.
65pub const TRANSLATABLE_FIELDS: [&str; 2] = ["label", "external_url"];
66
67/// Fetch translations for every item in `item_ids` under one locale, as
68/// `{ item_id -> { field_path -> value } }`.
69///
70/// One `WHERE locale_id = ? AND item_id IN (…)` SELECT for a whole menu.
71/// This is the batching seam: resolving a menu must not cost a query per
72/// item, which is the N+1 that `resolve_all_menus` already suffers from.
73/// Empty `item_ids` → empty map, without touching the database.
74///
75/// # Errors
76/// Driver / query failures.
77pub async fn fetch_for_items(
78    pool: &rustango::sql::Pool,
79    item_ids: &[i64],
80    locale_id: i64,
81) -> Result<
82    std::collections::HashMap<i64, std::collections::HashMap<String, String>>,
83    rustango::sql::ExecError,
84> {
85    use rustango::core::Column as _;
86    use rustango::sql::FetcherPool as _;
87
88    if item_ids.is_empty() {
89        return Ok(std::collections::HashMap::new());
90    }
91    let rows: Vec<MenuItemTranslation> = MenuItemTranslation::objects()
92        .where_(MenuItemTranslation::locale_id.eq(locale_id))
93        .where_(MenuItemTranslation::item_id.is_in(item_ids.iter().copied()))
94        .fetch(pool)
95        .await?;
96    let mut out: std::collections::HashMap<i64, std::collections::HashMap<String, String>> =
97        std::collections::HashMap::new();
98    for row in rows {
99        if row.value.is_empty() {
100            continue;
101        }
102        out.entry(row.item_id)
103            .or_default()
104            .insert(row.field_path, row.value);
105    }
106    Ok(out)
107}
108
109/// Validate a translation `field_path` against [`TRANSLATABLE_FIELDS`].
110/// Pure, so the submit handler and the tests share one definition of
111/// what is editable.
112///
113/// # Errors
114/// A human-readable message naming the accepted fields.
115pub fn validate_field_path(raw: &str) -> Result<String, String> {
116    let p = raw.trim();
117    if TRANSLATABLE_FIELDS.contains(&p) {
118        return Ok(p.to_owned());
119    }
120    Err(format!(
121        "Unknown menu-item field '{p}'. Translatable fields: {}.",
122        TRANSLATABLE_FIELDS.join(", ")
123    ))
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    #[test]
131    fn validate_field_path_accepts_the_translatable_columns() {
132        assert_eq!(validate_field_path("label").unwrap(), "label");
133        assert_eq!(validate_field_path("  external_url ").unwrap(), "external_url");
134    }
135
136    #[test]
137    fn validate_field_path_rejects_anything_else() {
138        // A typo must fail loudly rather than storing a row no reader
139        // will ever look up.
140        assert!(validate_field_path("labl").is_err());
141        assert!(validate_field_path("").is_err());
142        assert!(validate_field_path("page_id").is_err());
143        assert!(validate_field_path("sort_order").is_err());
144    }
145}