Skip to main content

rustango_cms/
theme_seed.rs

1//! Bootstrap-time hydration of the six bundled themes + their brand
2//! colors into each tenant.
3//!
4//! Theme rows live in [`fixtures/cms_theme.json`] and are loaded via
5//! [`rustango::fixtures::Fixture`] — pure data, easy to diff / edit,
6//! reproducible across tenants. Brand colors stay in code because
7//! their `theme_id` FK has to be resolved against the just-inserted
8//! row, which fixtures don't natively handle.
9//!
10//! ## Idempotency
11//!
12//! [`ensure_themes_seeded`] runs on every boot and reconciles by slug:
13//! it inserts fixture themes whose slug the tenant lacks (with brand
14//! colors) and never updates an existing row, so renames and recolors
15//! survive. On a tenant that already has themes, new built-ins land
16//! with `is_default` / `is_admin_default` cleared. A deleted bundled
17//! preset comes back on the next boot, since its slug is missing again.
18//!
19//! [`fixtures/cms_theme.json`]: ../../../fixtures/cms_theme.json
20
21use rustango::core::Column as _;
22use rustango::fixtures::Fixture;
23use rustango::sql::{ExecError, FetcherPool as _, Pool};
24
25use crate::theme::{BrandColor, Theme};
26
27/// Bundled theme JSON — embedded at compile time via `include_str!`
28/// so the binary ships fully self-contained.
29const THEME_FIXTURE: &str = include_str!("../fixtures/cms_theme.json");
30
31/// Brand colors per theme slug — `(slug, name, light_hex, dark_hex)`
32/// quads inserted with `theme_id` resolved against the just-loaded
33/// row. The bundled set is small (two colors × six themes) so an
34/// inline table beats a parallel JSON fixture with hand-rolled FK
35/// resolution.
36const BRAND_COLORS: &[(&str, &[(&str, &str, &str, &str)])] = &[
37    (
38        "editor-classic",
39        &[
40            ("primary", "Primary", "#1b32e7", "#bdc2ff"),
41            ("secondary", "Accent", "#942f00", "#ffb59c"),
42        ],
43    ),
44    (
45        "lumina",
46        &[
47            ("primary", "Primary", "#6366f1", "#a5b4fc"),
48            ("secondary", "Accent", "#06b6d4", "#67e8f9"),
49        ],
50    ),
51    (
52        "wagtail-teal",
53        &[
54            ("primary", "Primary", "#00838F", "#26C6DA"),
55            ("secondary", "Accent", "#43A047", "#66BB6A"),
56        ],
57    ),
58    (
59        "forest",
60        &[
61            ("primary", "Primary", "#2E7D32", "#66BB6A"),
62            ("secondary", "Accent", "#6750A4", "#B39DDB"),
63        ],
64    ),
65    (
66        "aurora-violet",
67        &[
68            ("primary", "Primary", "#6750A4", "#D0BCFF"),
69            ("secondary", "Accent", "#00ACC1", "#4DD0E1"),
70        ],
71    ),
72    (
73        "slate",
74        &[
75            ("primary", "Primary", "#475569", "#94A3B8"),
76            ("secondary", "Accent", "#0EA5E9", "#38BDF8"),
77        ],
78    ),
79    (
80        "sunset",
81        &[
82            ("primary", "Primary", "#E25822", "#FF8A65"),
83            ("secondary", "Accent", "#FFB300", "#FFD54F"),
84        ],
85    ),
86    (
87        "ink",
88        &[
89            ("primary", "Primary", "#111111", "#fafafa"),
90            ("secondary", "Accent", "#2563EB", "#60A5FA"),
91        ],
92    ),
93];
94
95/// Which fixture rows this tenant is missing, with their flags adjusted
96/// for how the tenant is arriving.
97///
98/// Split out from [`ensure_themes_seeded`] because it is the whole risk of
99/// the reconcile and the only part worth testing without a pool: it now
100/// runs on **every** boot for every tenant, so a mistake here duplicates
101/// rows or silently restyles a live admin.
102fn rows_to_insert(
103    raw: &serde_json::Value,
104    have: &std::collections::HashSet<String>,
105    bootstrapping: bool,
106) -> Vec<serde_json::Value> {
107    let mut rows: Vec<serde_json::Value> = raw.as_array().cloned().unwrap_or_default();
108    rows.retain(|r| {
109        r.get("slug")
110            .and_then(serde_json::Value::as_str)
111            .is_none_or(|slug| !have.contains(slug))
112    });
113    // Arriving at a site that already has themes, a new built-in must not
114    // become the active one — that would restyle a live admin nobody asked
115    // to restyle, and would leave two rows claiming to be the default.
116    // It lands as an option; an editor chooses it.
117    if !bootstrapping {
118        for r in &mut rows {
119            if let Some(obj) = r.as_object_mut() {
120                obj.insert("is_default".to_owned(), serde_json::Value::Bool(false));
121                obj.insert("is_admin_default".to_owned(), serde_json::Value::Bool(false));
122            }
123        }
124    }
125    rows
126}
127
128/// Hydrate the bundled theme presets + their brand colors into the
129/// current tenant. Inserts every built-in theme whose slug the tenant
130/// lacks and never updates an existing row (see the module docs).
131///
132/// Called for each tenant from [`crate::seed::ensure_seeded`].
133///
134/// # Errors
135/// Driver / query failures propagate. A malformed
136/// `fixtures/cms_theme.json` file surfaces as a fixture-format
137/// error — that would be a compile-time bug in this crate, not a
138/// runtime concern (the JSON is checked into the repo).
139pub async fn ensure_themes_seeded(pool: &Pool) -> Result<(), ExecError> {
140    // Reconcile by slug rather than bailing wholesale.
141    //
142    // The old guard returned as soon as *any* theme row existed, to avoid
143    // overwriting an editor's customizations. It did protect those — and
144    // it also meant a theme added to the fixture in a later release never
145    // reached an existing tenant, not even as something to pick. The site
146    // was stuck with whatever shipped the day it was bootstrapped.
147    //
148    // Insert missing slugs; never update an existing row. That keeps the
149    // original protection (customizations are still never touched) while
150    // letting new built-ins arrive.
151    let existing: Vec<Theme> = Theme::objects().fetch(pool).await?;
152    let bootstrapping = existing.is_empty();
153    let have: std::collections::HashSet<String> =
154        existing.into_iter().map(|t| t.slug).collect();
155
156    // Load the theme rows. Framework `Fixture::from_value` requires
157    // a top-level JSON array; we shipped one in cms_theme.json.
158    let raw: serde_json::Value = serde_json::from_str(THEME_FIXTURE)
159        .map_err(|e| ExecError::Driver(rustango::sql::sqlx::Error::Decode(Box::new(e))))?;
160    let rows = rows_to_insert(&raw, &have, bootstrapping);
161    let added: std::collections::HashSet<String> = rows
162        .iter()
163        .filter_map(|r| {
164            r.get("slug")
165                .and_then(serde_json::Value::as_str)
166                .map(ToOwned::to_owned)
167        })
168        .collect();
169    if rows.is_empty() {
170        return Ok(());
171    }
172    let fixture = Fixture::new("cms_theme")
173        .from_value(serde_json::Value::Array(rows))
174        .map_err(fixture_to_exec_err)?;
175    fixture
176        .load_into_pool("cms_theme", pool)
177        .await
178        .map_err(fixture_to_exec_err)?;
179
180    // Look up the just-loaded rows by slug so we can stamp brand
181    // colors with the correct `theme_id`. One round-trip per theme;
182    // 6 themes total, fine.
183    for (slug, colors) in BRAND_COLORS {
184        // Only for themes this pass created. Re-stamping an existing one
185        // would append a duplicate swatch set on every boot.
186        if !added.contains(*slug) {
187            continue;
188        }
189        let theme = Theme::objects()
190            .where_(Theme::slug.eq((*slug).to_owned()))
191            .first(pool)
192            .await?;
193        let Some(theme) = theme else {
194            // Fixture didn't include this slug — surfacing the gap
195            // is more useful than silently dropping the colors.
196            tracing::warn!(
197                target: "rustango_cms::theme_seed",
198                slug = *slug,
199                "brand-color group has no matching theme in cms_theme.json",
200            );
201            continue;
202        };
203        let theme_id = theme.id.get().copied().unwrap_or_default();
204        for (idx, (cslug, cname, light, dark)) in colors.iter().enumerate() {
205            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
206            let mut row = BrandColor {
207                id: rustango::sql::Auto::Unset,
208                theme_id,
209                slug: (*cslug).to_owned(),
210                name: (*cname).to_owned(),
211                color_value: (*light).to_owned(),
212                color_value_dark: (*dark).to_owned(),
213                sort_order: idx as i32,
214            };
215            row.insert(pool).await?;
216        }
217    }
218    Ok(())
219}
220
221/// Coerce a [`rustango::fixtures::FixtureError`] into [`ExecError`]
222/// so the seeder's `?` chain still works.
223fn fixture_to_exec_err(e: rustango::fixtures::FixtureError) -> ExecError {
224    ExecError::Driver(rustango::sql::sqlx::Error::Decode(Box::new(e)))
225}
226
227#[cfg(test)]
228mod reconcile_tests {
229    use super::*;
230    use serde_json::json;
231
232    fn fixture() -> serde_json::Value {
233        json!([
234            { "slug": "paper",          "is_default": true,  "is_admin_default": true },
235            { "slug": "editor-classic", "is_default": false, "is_admin_default": false },
236        ])
237    }
238
239    fn slugs(v: &[serde_json::Value]) -> Vec<&str> {
240        v.iter().filter_map(|r| r["slug"].as_str()).collect()
241    }
242
243    #[test]
244    fn a_fresh_tenant_gets_every_theme_with_its_shipped_default() {
245        let rows = rows_to_insert(&fixture(), &std::collections::HashSet::new(), true);
246        assert_eq!(slugs(&rows), ["paper", "editor-classic"]);
247        // the shipped default survives bootstrapping — otherwise a new
248        // tenant would come up with no active theme at all
249        assert_eq!(rows[0]["is_default"], json!(true));
250        assert_eq!(rows[0]["is_admin_default"], json!(true));
251    }
252
253    #[test]
254    fn an_existing_tenant_gets_only_what_it_lacks() {
255        let have = ["editor-classic".to_owned()].into_iter().collect();
256        let rows = rows_to_insert(&fixture(), &have, false);
257        assert_eq!(slugs(&rows), ["paper"], "must not re-insert a theme it has");
258    }
259
260    /// The regression that matters: a new built-in arriving at a live site
261    /// must never take over. Shipping `is_default: true` into a tenant that
262    /// already has an active theme would restyle its admin unannounced and
263    /// leave two rows both claiming to be the default.
264    #[test]
265    fn a_new_theme_never_activates_itself_on_a_live_site() {
266        let have = ["editor-classic".to_owned()].into_iter().collect();
267        let rows = rows_to_insert(&fixture(), &have, false);
268        assert_eq!(rows[0]["slug"], json!("paper"));
269        assert_eq!(rows[0]["is_default"], json!(false));
270        assert_eq!(rows[0]["is_admin_default"], json!(false));
271    }
272
273    #[test]
274    fn a_fully_seeded_tenant_inserts_nothing() {
275        let have = ["paper".to_owned(), "editor-classic".to_owned()]
276            .into_iter()
277            .collect();
278        assert!(rows_to_insert(&fixture(), &have, false).is_empty());
279    }
280}