1use rustango::core::Column as _;
22use rustango::fixtures::Fixture;
23use rustango::sql::{ExecError, FetcherPool as _, Pool};
24
25use crate::theme::{BrandColor, Theme};
26
27const THEME_FIXTURE: &str = include_str!("../fixtures/cms_theme.json");
30
31const 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
95fn 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 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
128pub async fn ensure_themes_seeded(pool: &Pool) -> Result<(), ExecError> {
140 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 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 for (slug, colors) in BRAND_COLORS {
184 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 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
221fn 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 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 #[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}