1pub mod brand;
16pub mod migrations;
17pub mod store;
18
19pub use brand::BrandSetting;
20pub use migrations::{migrations, MODULE_ID};
21pub use store::{get, load, save, set, SettingsError, SettingsModel};
22
23pub struct SettingsModule;
25
26impl laterite_core::Module for SettingsModule {
27 fn id(&self) -> laterite_core::ModuleId {
28 laterite_core::ModuleId::new(MODULE_ID)
29 }
30 fn migrations(&self) -> laterite_core::MigrationSet {
31 migrations()
32 }
33}
34
35use std::collections::HashMap;
36
37use askama::Template;
38use axum::response::{IntoResponse, Redirect, Response};
39use laterite_core::validation::Mode;
40use laterite_core::{t, Text, Translator};
41use serde::Serialize;
42use serde_json::{Map, Value};
43
44use crate::{render, render_error, AdminState};
45
46pub use crate::form::FormField;
53
54#[derive(Debug, Clone, Serialize)]
57#[non_exhaustive]
58pub struct SettingsItem {
59 pub code: String,
67 pub label: Text,
69 pub description: Text,
70 pub category: Text,
72 pub hint: Option<Text>,
76 pub order: i32,
78 pub icon: Option<String>,
81 pub permission: Option<String>,
84 pub link: Option<String>,
88 pub fields: Vec<FormField>,
89 pub(crate) route: Option<String>,
92}
93
94pub(crate) const MAX_DESCRIPTION: usize = 72;
99
100impl SettingsItem {
101 pub fn new(code: impl Into<String>, label: impl Into<Text>, fields: Vec<FormField>) -> Self {
107 Self {
108 code: code.into(),
109 label: label.into(),
110 description: Text::from(""),
111 category: Text::from(""),
112 hint: None,
113 order: 0,
114 icon: None,
115 permission: None,
116 link: None,
117 fields,
118 route: None,
119 }
120 }
121
122 pub fn description(mut self, text: impl Into<Text>) -> Self {
129 let text = text.into();
130 debug_assert!(
131 text.source().chars().count() <= MAX_DESCRIPTION,
132 "settings description is {} characters, over the {MAX_DESCRIPTION} that \
133 fit two sidebar lines; shorten it or move the detail to `hint`: {:?}",
134 text.source().chars().count(),
135 text.source(),
136 );
137 self.description = text;
138 self
139 }
140
141 pub fn hint(mut self, text: impl Into<Text>) -> Self {
144 self.hint = Some(text.into());
145 self
146 }
147
148 pub fn category(mut self, text: impl Into<Text>) -> Self {
150 self.category = text.into();
151 self
152 }
153
154 pub fn order(mut self, order: i32) -> Self {
156 self.order = order;
157 self
158 }
159
160 pub fn icon(mut self, icon: impl Into<String>) -> Self {
162 self.icon = Some(icon.into());
163 self
164 }
165
166 pub fn permission(mut self, permission: impl Into<String>) -> Self {
168 self.permission = Some(permission.into());
169 self
170 }
171
172 pub fn link(mut self, link: impl Into<String>) -> Self {
175 self.link = Some(link.into());
176 self
177 }
178
179 pub(crate) fn mount_at(&mut self, route: impl Into<String>) {
182 self.route = Some(route.into());
183 }
184
185 pub(crate) fn at(mut self, route: impl Into<String>) -> Self {
192 self.route = Some(route.into());
193 self
194 }
195
196 pub(crate) fn route(&self) -> String {
203 match &self.route {
204 Some(route) => route.clone(),
205 None => format!("/settings/{}", self.code.replace('.', "/")),
206 }
207 }
208
209 pub fn path(&self, admin_path: &str) -> String {
213 match &self.link {
214 Some(link) => format!("{admin_path}{link}"),
215 None => format!("{admin_path}{}", self.route()),
216 }
217 }
218}
219
220pub(crate) fn index(shell: crate::Shell) -> Response {
223 render(SettingsIndexTemplate { shell })
224}
225
226pub(crate) async fn edit_form(
229 state: &AdminState,
230 item: &SettingsItem,
231 shell: crate::Shell,
232) -> Response {
233 let mut stored = match store::get(&state.db, &item.code).await {
234 Ok(value) => value.unwrap_or_else(|| Value::Object(Map::new())),
235 Err(_) => return render_error(),
236 };
237 prefill_from_config(item, &mut stored, &state.app_name);
240 render(build(
241 item,
242 &state.field_types,
243 state.overrides.as_ref(),
244 None,
245 &stored,
246 &shell,
247 ))
248}
249
250pub(crate) async fn update(
252 state: &AdminState,
253 item: &SettingsItem,
254 data: HashMap<String, String>,
255 shell: crate::Shell,
256 session: &crate::session::SessionHandle,
257 user: &laterite_auth::AuthenticatedUser,
258) -> Response {
259 let value = match collect(item, &state.field_types, &data) {
262 Ok(value) => value,
263 Err(message) => {
264 let stored = store::get(&state.db, &item.code)
265 .await
266 .ok()
267 .flatten()
268 .unwrap_or(Value::Null);
269 return render(build(
270 item,
271 &state.field_types,
272 state.overrides.as_ref(),
273 Some(message),
274 &stored,
275 &shell,
276 ));
277 }
278 };
279 match store::set(&state.db, &item.code, &value).await {
280 Ok(()) => {
281 if item.code == brand::BrandSetting::CODE {
284 state.invalidate_brand();
285 }
286 crate::audit::record(
289 state,
290 user,
291 "backend.settings.update",
292 Some("settings"),
293 Some(item.code.as_str()),
294 None,
295 )
296 .await;
297 session.push_flash(crate::session::FlashLevel::Success, t!("Settings saved."));
298 Redirect::to(&format!("{}/settings", state.admin_path)).into_response()
299 }
300 Err(_) => render(build(
301 item,
302 &state.field_types,
303 state.overrides.as_ref(),
304 Some(t!("Could not save. Please try again.")),
305 &value,
306 &shell,
307 )),
308 }
309}
310
311fn collect(
319 item: &SettingsItem,
320 types: &crate::field::FieldRegistry,
321 data: &HashMap<String, String>,
322) -> Result<Value, Text> {
323 let mut object = Map::new();
324 for field in &item.fields {
325 let Some(field_type) = types.get(&field.field_type) else {
326 return Err(t!("This screen uses a field type that is not registered."));
327 };
328 let opts = field_type
329 .resolve_options(&field.options, types)
330 .map_err(|_| t!("This screen has a malformed field."))?;
331 let submitted = crate::field::SubmittedField::new(&field.name, data);
332 let value = match field_type.to_attr(&submitted, &opts, Mode::Update) {
335 Ok(Some(value)) => attr_to_json(value),
336 Ok(None) => Value::String(String::new()),
337 Err(_) => return Err(t!("Check the values and try again.")),
338 };
339 object.insert(field.name.clone(), value);
340 }
341 Ok(Value::Object(object))
342}
343
344fn attr_to_json(value: laterite_core::AttrValue) -> Value {
346 use laterite_core::AttrValue;
347 match value {
348 AttrValue::Null => Value::String(String::new()),
349 AttrValue::Bool(b) => Value::Bool(b),
350 AttrValue::Int(i) => Value::from(i),
351 AttrValue::Float(f) => Value::from(f),
352 AttrValue::Json(j) => j,
353 other => Value::String(other.to_text().unwrap_or_default()),
354 }
355}
356
357pub(crate) fn sidebar_groups(
363 items: &[SettingsItem],
364 admin_path: &str,
365 active_code: Option<&str>,
366 tr: &Translator,
367) -> Vec<CategoryView> {
368 let mut by_category: HashMap<String, Vec<&SettingsItem>> = HashMap::new();
370 for item in items {
371 by_category
372 .entry(tr.t(&item.category))
373 .or_default()
374 .push(item);
375 }
376 let mut groups: Vec<CategoryView> = by_category
377 .into_iter()
378 .map(|(category, mut items)| {
379 items.sort_by(|a, b| {
381 a.order
382 .cmp(&b.order)
383 .then_with(|| a.label.source().cmp(b.label.source()))
384 });
385 CategoryView {
386 min_order: items.iter().map(|i| i.order).min().unwrap_or(0),
387 name: category,
388 items: items
389 .iter()
390 .map(|i| ItemView {
391 label: tr.t(&i.label),
392 description: tr.t(&i.description),
393 path: i.path(admin_path),
394 icon: crate::icons::svg(i.icon.as_deref()),
395 active: active_code == Some(i.code.as_str()),
396 })
397 .collect(),
398 }
399 })
400 .collect();
401 groups.sort_by(|a, b| {
402 a.min_order
403 .cmp(&b.min_order)
404 .then_with(|| a.name.cmp(&b.name))
405 });
406 groups
407}
408
409fn prefill_from_config(item: &SettingsItem, stored: &mut Value, app_name: &str) {
416 if item.code != brand::BrandSetting::CODE {
417 return;
418 }
419 if let Value::Object(map) = stored {
420 let blank = map
421 .get("app_name")
422 .and_then(Value::as_str)
423 .unwrap_or("")
424 .trim()
425 .is_empty();
426 if blank {
427 map.insert("app_name".to_string(), Value::String(app_name.to_string()));
428 }
429 }
430}
431
432fn build(
433 item: &SettingsItem,
434 types: &crate::field::FieldRegistry,
435 overrides: &dyn crate::field::OverrideResolver,
436 error: Option<Text>,
437 stored: &Value,
438 shell: &crate::Shell,
439) -> SettingsFormTemplate {
440 let fields = item
441 .fields
442 .iter()
443 .map(|f| {
444 let label = shell.tt(&f.label);
445 let control = match types.get(&f.field_type) {
446 Some(ft) => {
447 let opts = ft
448 .resolve_options(&f.options, types)
449 .unwrap_or_else(|_| crate::field::ResolvedOptions::none());
450 let value = match stored.get(&f.name) {
451 Some(Value::Array(rows)) => {
452 crate::field::FieldValue::Json(Value::Array(rows.clone()))
453 }
454 Some(Value::String(text)) => {
455 crate::field::FieldValue::Text(ft.to_control(Some(text), &opts))
456 }
457 Some(Value::Null) | None => {
458 crate::field::FieldValue::Text(ft.to_control(None, &opts))
459 }
460 Some(other) => crate::field::FieldValue::Text(
461 ft.to_control(Some(&other.to_string()), &opts),
462 ),
463 };
464 let cx = crate::field::FieldCx {
465 name: &f.name,
466 id: &f.name,
467 label: &label,
468 value: &value,
469 required: false,
470 opts: &opts,
471 base: &shell.base,
472 i18n: shell.i18n(),
473 };
474 let scope = crate::field::OverrideScope {
475 surface: crate::field::Surface::Field,
476 view_key: &f.field_type,
477 resource: Some(&item.code),
478 field: Some(&f.name),
479 };
480 crate::field::render_field(ft.as_ref(), overrides, &scope, &cx).into_string()
481 }
482 None => String::new(),
483 };
484 FieldView {
485 label,
486 help: f.help.as_ref().map(|h| shell.tt(h)),
487 control,
488 }
489 })
490 .collect();
491 SettingsFormTemplate {
492 title: shell.tt(&item.label),
493 description: shell.tt(&item.description),
494 hint: item.hint.as_ref().map(|h| shell.tt(h)),
495 action: item.path(&shell.base),
496 error: error.map(|e| shell.tt(&e)),
497 fields,
498 shell: shell.clone(),
499 }
500}
501
502#[derive(Clone)]
504pub(crate) struct CategoryView {
505 pub(crate) name: String,
506 min_order: i32,
507 pub(crate) items: Vec<ItemView>,
508}
509
510#[derive(Clone)]
512pub(crate) struct ItemView {
513 pub(crate) label: String,
514 pub(crate) description: String,
515 pub(crate) path: String,
516 pub(crate) icon: &'static str,
518 pub(crate) active: bool,
520}
521
522#[derive(Template)]
523#[template(path = "settings_index.html")]
524struct SettingsIndexTemplate {
525 shell: crate::Shell,
526}
527
528struct FieldView {
529 label: String,
530 help: Option<String>,
531 control: String,
533}
534
535#[derive(Template)]
536#[template(path = "settings_form.html")]
537struct SettingsFormTemplate {
538 shell: crate::Shell,
539 title: String,
540 description: String,
541 hint: Option<String>,
544 action: String,
545 error: Option<String>,
546 fields: Vec<FieldView>,
547}
548
549#[cfg(test)]
550mod field_system_tests {
551 use super::*;
552
553 #[test]
554 #[should_panic(expected = "over the 72")]
555 fn a_lecture_of_a_description_is_refused() {
556 SettingsItem::new("acme.test", "Test", Vec::new()).description(
559 "What search engines and other crawlers may visit. The admin panel \
560 is always excluded, whatever you put here.",
561 );
562 }
563
564 #[test]
565 fn a_label_sized_description_passes_and_a_hint_carries_the_rest() {
566 let item = SettingsItem::new("acme.test", "Test", Vec::new())
567 .description("Which crawlers may visit, and what they may not.")
568 .hint(
569 "The admin panel is always excluded, whatever you put here, and a \
570 crawler obeys only the block that names it.",
571 );
572 assert!(item.description.source().chars().count() <= MAX_DESCRIPTION);
573 assert!(item.hint.is_some());
575 }
576
577 fn item(fields: Vec<FormField>) -> SettingsItem {
578 SettingsItem {
579 code: "acme.test".to_string(),
580 label: Text::new(""),
581 description: Text::new(""),
582 category: Text::new(""),
583 hint: None,
584 order: 0,
585 icon: None,
586 permission: None,
587 link: None,
588 fields,
589 route: None,
590 }
591 }
592
593 fn submitted(pairs: &[(&str, &str)]) -> HashMap<String, String> {
594 pairs
595 .iter()
596 .map(|(k, v)| (k.to_string(), v.to_string()))
597 .collect()
598 }
599
600 #[test]
603 fn settings_store_what_the_field_type_says() {
604 let cfg = item(vec![
605 FormField::text("name", "Name"),
606 FormField::switch("enabled", "Enabled"),
607 FormField::select("freq", "Frequency", vec![("daily", "Daily")]),
608 FormField::date("expires", "Expires"),
609 ]);
610 let stored = collect(
611 &cfg,
612 &crate::field::builtin_registry(),
613 &submitted(&[
614 ("name", "Acme"),
615 ("enabled", "on"),
616 ("freq", "daily"),
617 ("expires", "2026-12-31"),
618 ]),
619 )
620 .unwrap();
621
622 assert_eq!(stored["name"], "Acme");
623 assert_eq!(stored["enabled"], serde_json::json!(true));
625 assert_eq!(stored["freq"], "daily");
626 assert_eq!(stored["expires"], "2026-12-31");
627 }
628
629 #[test]
632 fn an_unticked_switch_clears() {
633 let cfg = item(vec![FormField::switch("enabled", "Enabled")]);
634 let stored = collect(&cfg, &crate::field::builtin_registry(), &submitted(&[])).unwrap();
635 assert_eq!(stored["enabled"], serde_json::json!(false));
636 }
637
638 #[test]
641 fn a_repeater_works_in_settings() {
642 let cfg = item(vec![FormField::repeater(
643 "rules",
644 "Rules",
645 vec![
646 FormField::text("path", "Path"),
647 FormField::switch("allow", "Allow"),
648 ],
649 )]);
650 let stored = collect(
651 &cfg,
652 &crate::field::builtin_registry(),
653 &submitted(&[
654 ("rules[0][path]", "/private"),
655 ("rules[1][path]", "/public"),
656 ("rules[1][allow]", "on"),
657 ]),
658 )
659 .unwrap();
660
661 let rows = stored["rules"].as_array().unwrap();
662 assert_eq!(rows.len(), 2);
663 assert_eq!(rows[0]["path"], "/private");
664 assert_eq!(rows[0]["allow"], serde_json::json!(false));
665 assert_eq!(rows[1]["allow"], serde_json::json!(true));
666 }
667
668 #[test]
669 fn a_screen_naming_an_unregistered_type_refuses_rather_than_rendering_blank() {
670 let cfg = item(vec![FormField::of("x", "X", "acme.nope")]);
671 assert!(collect(&cfg, &crate::field::builtin_registry(), &submitted(&[])).is_err());
672 }
673
674 #[test]
675 fn the_form_renders_each_control_through_its_type() {
676 let cfg = item(vec![
677 FormField::switch("enabled", "Enabled"),
678 FormField::repeater("rules", "Rules", vec![FormField::text("path", "Path")]),
679 ]);
680 let html = build(
681 &cfg,
682 &crate::field::builtin_registry(),
683 &crate::field::NoOverrides,
684 None,
685 &serde_json::json!({ "enabled": true, "rules": [{ "path": "/a" }] }),
686 &crate::Shell::test(),
687 )
688 .render()
689 .unwrap();
690
691 assert!(html.contains(r#"type="checkbox""#));
692 assert!(html.contains(r#"name="rules[0][path]""#));
693 assert!(html.contains(r#"value="/a""#));
694 assert!(html.contains("lat-repeater__blank"));
695 }
696}
697
698#[cfg(test)]
699mod tests {
700 use super::*;
701 use laterite_core::Db;
702
703 #[test]
704 fn brand_form_prefills_app_name_from_config_when_unset() {
705 let brand = brand::settings_item();
706 let mut unset = Value::Object(Map::new());
708 prefill_from_config(&brand, &mut unset, "Configured Name");
709 assert_eq!(unset["app_name"], serde_json::json!("Configured Name"));
710 let mut set = serde_json::json!({ "app_name": "Acme" });
712 prefill_from_config(&brand, &mut set, "Configured Name");
713 assert_eq!(set["app_name"], serde_json::json!("Acme"));
714 let mut other = Value::Object(Map::new());
716 prefill_from_config(&item(), &mut other, "Configured Name");
717 assert!(other.get("app_name").is_none());
718 }
719
720 fn item() -> SettingsItem {
721 SettingsItem {
722 code: "test.log".to_string(),
723 label: "Log Settings".into(),
724 description: "What the log records.".into(),
725 category: "Logs".into(),
726 hint: None,
727 order: 10,
728 icon: None,
729 permission: None,
730 link: None,
731 fields: vec![
732 FormField::switch("log_events", "Log events"),
733 FormField::switch("log_requests", "Log requests"),
734 FormField::text("retention_days", "Retention (days)"),
735 ],
736 route: None,
737 }
738 }
739
740 fn state(db: Db) -> AdminState {
741 AdminState::new(
742 laterite_auth::AuthService::new(db.clone(), laterite_auth::AuthConfig::default()),
743 db,
744 )
745 }
746
747 async fn test_db() -> (Db, laterite_core::testing::TestGuard) {
750 laterite_core::testing::connect_test(&[migrations()]).await
751 }
752
753 fn data(pairs: &[(&str, &str)]) -> HashMap<String, String> {
754 pairs
755 .iter()
756 .map(|(k, v)| (k.to_string(), v.to_string()))
757 .collect()
758 }
759
760 #[test]
761 fn group_orders_categories_then_items() {
762 let items = vec![
763 SettingsItem {
764 code: "b".into(),
765 label: "Beta".into(),
766 description: String::new().into(),
767 category: "System".into(),
768 hint: None,
769 order: 20,
770 icon: None,
771 permission: None,
772 link: None,
773 fields: vec![],
774 route: None,
775 },
776 SettingsItem {
777 code: "a".into(),
778 label: "Alpha".into(),
779 description: String::new().into(),
780 category: "System".into(),
781 hint: None,
782 order: 10,
783 icon: None,
784 permission: None,
785 link: None,
786 fields: vec![],
787 route: None,
788 },
789 SettingsItem {
790 code: "l".into(),
791 label: "Logs".into(),
792 description: String::new().into(),
793 category: "Logs".into(),
794 hint: None,
795 order: 5,
796 icon: None,
797 permission: None,
798 link: None,
799 fields: vec![],
800 route: None,
801 },
802 ];
803 let groups = sidebar_groups(&items, "/admin", None, &Translator::new("en"));
804 assert_eq!(groups[0].name, "Logs");
806 assert_eq!(groups[1].name, "System");
807 assert_eq!(groups[1].items[0].label, "Alpha");
809 assert_eq!(groups[1].items[1].label, "Beta");
810 assert!(groups.iter().flat_map(|g| &g.items).all(|i| !i.active));
812 }
813
814 #[test]
815 fn group_marks_only_the_active_item() {
816 let items = vec![item()];
817 let groups = sidebar_groups(&items, "/admin", Some("test.log"), &Translator::new("en"));
818 let active: Vec<&str> = groups
819 .iter()
820 .flat_map(|g| &g.items)
821 .filter(|i| i.active)
822 .map(|i| i.label.as_str())
823 .collect();
824 assert_eq!(active, ["Log Settings"]);
825 }
826
827 #[test]
828 fn settings_model_item_path_is_its_form() {
829 assert_eq!(item().path("/admin"), "/admin/settings/test/log");
832 assert_eq!(item().path("/manage"), "/manage/settings/test/log");
834
835 let mut resolved = item();
837 resolved.mount_at("/acme/logging/log");
838 assert_eq!(resolved.path("/admin"), "/admin/acme/logging/log");
839 }
840
841 #[test]
842 fn link_item_path_follows_the_link() {
843 let admins = crate::builtin_settings()
844 .into_iter()
845 .find(|i| i.code == "backend.administrators")
846 .unwrap();
847 assert_eq!(admins.category.source(), "Users");
848 assert!(admins.link.is_some());
849 assert!(admins.fields.is_empty());
850 assert_eq!(admins.path("/admin"), "/admin/users");
852 assert!(crate::builtin_settings()
853 .iter()
854 .any(|i| i.code == "backend.roles"));
855 }
856
857 #[tokio::test]
858 async fn update_persists_typed_values() {
859 let (db, _guard) = test_db().await;
860 let st = state(db.clone());
861
862 let it = item();
863 let resp = update(
864 &st,
865 &it,
866 data(&[("log_events", "on"), ("retention_days", "30")]),
868 crate::Shell::test(),
869 &crate::session::SessionHandle::from_blob(None),
870 &crate::audit::test_actor(),
871 )
872 .await;
873 assert_eq!(resp.status(), axum::http::StatusCode::SEE_OTHER);
874
875 let stored = store::get(&db, "test.log").await.unwrap().unwrap();
876 assert_eq!(stored["log_events"], serde_json::json!(true));
877 assert_eq!(stored["log_requests"], serde_json::json!(false));
878 assert_eq!(stored["retention_days"], serde_json::json!("30"));
879 }
880
881 #[test]
882 fn index_renders() {
883 let resp = index(crate::Shell::test());
884 assert_eq!(resp.status(), axum::http::StatusCode::OK);
885 }
886
887 #[tokio::test]
888 async fn edit_form_renders_for_unset_item() {
889 let (db, _guard) = test_db().await;
890 let st = state(db);
891 let it = item();
893 let resp = edit_form(&st, &it, crate::Shell::test()).await;
894 assert_eq!(resp.status(), axum::http::StatusCode::OK);
895 }
896}