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(&item.path(&state.admin_path)).into_response()
302 }
303 Err(_) => render(build(
304 item,
305 &state.field_types,
306 state.overrides.as_ref(),
307 Some(t!("Could not save. Please try again.")),
308 &value,
309 &shell,
310 )),
311 }
312}
313
314fn collect(
322 item: &SettingsItem,
323 types: &crate::field::FieldRegistry,
324 data: &HashMap<String, String>,
325) -> Result<Value, Text> {
326 let mut object = Map::new();
327 for field in &item.fields {
328 let Some(field_type) = types.get(&field.field_type) else {
329 return Err(t!("This screen uses a field type that is not registered."));
330 };
331 let opts = field_type
332 .resolve_options(&field.options, types)
333 .map_err(|_| t!("This screen has a malformed field."))?;
334 let submitted = crate::field::SubmittedField::new(&field.name, data);
335 let value = match field_type.to_attr(&submitted, &opts, Mode::Update) {
338 Ok(Some(value)) => attr_to_json(value),
339 Ok(None) => Value::String(String::new()),
340 Err(_) => return Err(t!("Check the values and try again.")),
341 };
342 object.insert(field.name.clone(), value);
343 }
344 Ok(Value::Object(object))
345}
346
347fn attr_to_json(value: laterite_core::AttrValue) -> Value {
349 use laterite_core::AttrValue;
350 match value {
351 AttrValue::Null => Value::String(String::new()),
352 AttrValue::Bool(b) => Value::Bool(b),
353 AttrValue::Int(i) => Value::from(i),
354 AttrValue::Float(f) => Value::from(f),
355 AttrValue::Json(j) => j,
356 other => Value::String(other.to_text().unwrap_or_default()),
357 }
358}
359
360pub(crate) fn sidebar_groups(
366 items: &[SettingsItem],
367 admin_path: &str,
368 active_code: Option<&str>,
369 tr: &Translator,
370 icons: crate::icons::Icons<'_>,
371) -> Vec<CategoryView> {
372 let mut by_category: HashMap<String, Vec<&SettingsItem>> = HashMap::new();
374 for item in items {
375 by_category
376 .entry(tr.t(&item.category))
377 .or_default()
378 .push(item);
379 }
380 let mut groups: Vec<CategoryView> = by_category
381 .into_iter()
382 .map(|(category, mut items)| {
383 items.sort_by(|a, b| {
385 a.order
386 .cmp(&b.order)
387 .then_with(|| a.label.source().cmp(b.label.source()))
388 });
389 CategoryView {
390 min_order: items.iter().map(|i| i.order).min().unwrap_or(0),
391 name: category,
392 items: items
393 .iter()
394 .map(|i| ItemView {
395 label: tr.t(&i.label),
396 description: tr.t(&i.description),
397 path: i.path(admin_path),
398 icon: icons.render(i.icon.as_deref()),
399 active: active_code == Some(i.code.as_str()),
400 })
401 .collect(),
402 }
403 })
404 .collect();
405 groups.sort_by(|a, b| {
406 a.min_order
407 .cmp(&b.min_order)
408 .then_with(|| a.name.cmp(&b.name))
409 });
410 groups
411}
412
413fn prefill_from_config(item: &SettingsItem, stored: &mut Value, app_name: &str) {
420 if item.code != brand::BrandSetting::CODE {
421 return;
422 }
423 if let Value::Object(map) = stored {
424 let blank = map
425 .get("app_name")
426 .and_then(Value::as_str)
427 .unwrap_or("")
428 .trim()
429 .is_empty();
430 if blank {
431 map.insert("app_name".to_string(), Value::String(app_name.to_string()));
432 }
433 }
434}
435
436fn build(
437 item: &SettingsItem,
438 types: &crate::field::FieldRegistry,
439 overrides: &dyn crate::field::OverrideResolver,
440 error: Option<Text>,
441 stored: &Value,
442 shell: &crate::Shell,
443) -> SettingsFormTemplate {
444 let fields = item
445 .fields
446 .iter()
447 .map(|f| {
448 let label = shell.tt(&f.label);
449 let control = match types.get(&f.field_type) {
450 Some(ft) => {
451 let opts = ft
452 .resolve_options(&f.options, types)
453 .unwrap_or_else(|_| crate::field::ResolvedOptions::none());
454 let value = match stored.get(&f.name) {
455 Some(Value::Array(rows)) => {
456 crate::field::FieldValue::Json(Value::Array(rows.clone()))
457 }
458 Some(Value::String(text)) => {
459 crate::field::FieldValue::Text(ft.to_control(Some(text), &opts))
460 }
461 Some(Value::Null) | None => {
462 crate::field::FieldValue::Text(ft.to_control(None, &opts))
463 }
464 Some(other) => crate::field::FieldValue::Text(
465 ft.to_control(Some(&other.to_string()), &opts),
466 ),
467 };
468 let cx = crate::field::FieldCx {
469 name: &f.name,
470 id: &f.name,
471 label: &label,
472 value: &value,
473 required: false,
474 opts: &opts,
475 base: &shell.base,
476 i18n: shell.i18n(),
477 };
478 let scope = crate::field::OverrideScope {
479 surface: crate::field::Surface::Field,
480 view_key: &f.field_type,
481 resource: Some(&item.code),
482 field: Some(&f.name),
483 };
484 crate::field::render_field(ft.as_ref(), overrides, &scope, &cx).into_string()
485 }
486 None => String::new(),
487 };
488 FieldView {
489 label,
490 help: f.help.as_ref().map(|h| shell.tt(h)),
491 control,
492 }
493 })
494 .collect();
495 SettingsFormTemplate {
496 title: shell.tt(&item.label),
497 description: shell.tt(&item.description),
498 hint: item.hint.as_ref().map(|h| shell.tt(h)),
499 action: item.path(&shell.base),
500 error: error.map(|e| shell.tt(&e)),
501 fields,
502 shell: shell.clone(),
503 }
504}
505
506#[derive(Clone)]
508pub(crate) struct CategoryView {
509 pub(crate) name: String,
510 min_order: i32,
511 pub(crate) items: Vec<ItemView>,
512}
513
514#[derive(Clone)]
516pub(crate) struct ItemView {
517 pub(crate) label: String,
518 pub(crate) description: String,
519 pub(crate) path: String,
520 pub(crate) icon: String,
522 pub(crate) active: bool,
524}
525
526#[derive(Template)]
527#[template(path = "settings_index.html")]
528struct SettingsIndexTemplate {
529 shell: crate::Shell,
530}
531
532struct FieldView {
533 label: String,
534 help: Option<String>,
535 control: String,
537}
538
539#[derive(Template)]
540#[template(path = "settings_form.html")]
541struct SettingsFormTemplate {
542 shell: crate::Shell,
543 title: String,
544 description: String,
545 hint: Option<String>,
548 action: String,
549 error: Option<String>,
550 fields: Vec<FieldView>,
551}
552
553#[cfg(test)]
554mod field_system_tests {
555 use super::*;
556
557 #[test]
558 #[should_panic(expected = "over the 72")]
559 fn a_lecture_of_a_description_is_refused() {
560 SettingsItem::new("acme.test", "Test", Vec::new()).description(
563 "What search engines and other crawlers may visit. The admin panel \
564 is always excluded, whatever you put here.",
565 );
566 }
567
568 #[test]
569 fn a_label_sized_description_passes_and_a_hint_carries_the_rest() {
570 let item = SettingsItem::new("acme.test", "Test", Vec::new())
571 .description("Which crawlers may visit, and what they may not.")
572 .hint(
573 "The admin panel is always excluded, whatever you put here, and a \
574 crawler obeys only the block that names it.",
575 );
576 assert!(item.description.source().chars().count() <= MAX_DESCRIPTION);
577 assert!(item.hint.is_some());
579 }
580
581 fn item(fields: Vec<FormField>) -> SettingsItem {
582 SettingsItem {
583 code: "acme.test".to_string(),
584 label: Text::new(""),
585 description: Text::new(""),
586 category: Text::new(""),
587 hint: None,
588 order: 0,
589 icon: None,
590 permission: None,
591 link: None,
592 fields,
593 route: None,
594 }
595 }
596
597 fn submitted(pairs: &[(&str, &str)]) -> HashMap<String, String> {
598 pairs
599 .iter()
600 .map(|(k, v)| (k.to_string(), v.to_string()))
601 .collect()
602 }
603
604 #[test]
607 fn settings_store_what_the_field_type_says() {
608 let cfg = item(vec![
609 FormField::text("name", "Name"),
610 FormField::switch("enabled", "Enabled"),
611 FormField::select("freq", "Frequency", vec![("daily", "Daily")]),
612 FormField::date("expires", "Expires"),
613 ]);
614 let stored = collect(
615 &cfg,
616 &crate::field::builtin_registry(),
617 &submitted(&[
618 ("name", "Acme"),
619 ("enabled", "on"),
620 ("freq", "daily"),
621 ("expires", "2026-12-31"),
622 ]),
623 )
624 .unwrap();
625
626 assert_eq!(stored["name"], "Acme");
627 assert_eq!(stored["enabled"], serde_json::json!(true));
629 assert_eq!(stored["freq"], "daily");
630 assert_eq!(stored["expires"], "2026-12-31");
631 }
632
633 #[test]
636 fn an_unticked_switch_clears() {
637 let cfg = item(vec![FormField::switch("enabled", "Enabled")]);
638 let stored = collect(&cfg, &crate::field::builtin_registry(), &submitted(&[])).unwrap();
639 assert_eq!(stored["enabled"], serde_json::json!(false));
640 }
641
642 #[test]
645 fn a_repeater_works_in_settings() {
646 let cfg = item(vec![FormField::repeater(
647 "rules",
648 "Rules",
649 vec![
650 FormField::text("path", "Path"),
651 FormField::switch("allow", "Allow"),
652 ],
653 )]);
654 let stored = collect(
655 &cfg,
656 &crate::field::builtin_registry(),
657 &submitted(&[
658 ("rules[0][path]", "/private"),
659 ("rules[1][path]", "/public"),
660 ("rules[1][allow]", "on"),
661 ]),
662 )
663 .unwrap();
664
665 let rows = stored["rules"].as_array().unwrap();
666 assert_eq!(rows.len(), 2);
667 assert_eq!(rows[0]["path"], "/private");
668 assert_eq!(rows[0]["allow"], serde_json::json!(false));
669 assert_eq!(rows[1]["allow"], serde_json::json!(true));
670 }
671
672 #[test]
673 fn a_screen_naming_an_unregistered_type_refuses_rather_than_rendering_blank() {
674 let cfg = item(vec![FormField::of("x", "X", "acme.nope")]);
675 assert!(collect(&cfg, &crate::field::builtin_registry(), &submitted(&[])).is_err());
676 }
677
678 #[test]
679 fn the_form_renders_each_control_through_its_type() {
680 let cfg = item(vec![
681 FormField::switch("enabled", "Enabled"),
682 FormField::repeater("rules", "Rules", vec![FormField::text("path", "Path")]),
683 ]);
684 let html = build(
685 &cfg,
686 &crate::field::builtin_registry(),
687 &crate::field::NoOverrides,
688 None,
689 &serde_json::json!({ "enabled": true, "rules": [{ "path": "/a" }] }),
690 &crate::Shell::test(),
691 )
692 .render()
693 .unwrap();
694
695 assert!(html.contains(r#"type="checkbox""#));
696 assert!(html.contains(r#"name="rules[0][path]""#));
697 assert!(html.contains(r#"value="/a""#));
698 assert!(html.contains("lat-repeater__blank"));
699 }
700}
701
702#[cfg(test)]
703mod tests {
704 use super::*;
705 use laterite_core::Db;
706
707 #[test]
708 fn brand_form_prefills_app_name_from_config_when_unset() {
709 let brand = brand::settings_item();
710 let mut unset = Value::Object(Map::new());
712 prefill_from_config(&brand, &mut unset, "Configured Name");
713 assert_eq!(unset["app_name"], serde_json::json!("Configured Name"));
714 let mut set = serde_json::json!({ "app_name": "Acme" });
716 prefill_from_config(&brand, &mut set, "Configured Name");
717 assert_eq!(set["app_name"], serde_json::json!("Acme"));
718 let mut other = Value::Object(Map::new());
720 prefill_from_config(&item(), &mut other, "Configured Name");
721 assert!(other.get("app_name").is_none());
722 }
723
724 fn item() -> SettingsItem {
725 SettingsItem {
726 code: "test.log".to_string(),
727 label: "Log Settings".into(),
728 description: "What the log records.".into(),
729 category: "Logs".into(),
730 hint: None,
731 order: 10,
732 icon: None,
733 permission: None,
734 link: None,
735 fields: vec![
736 FormField::switch("log_events", "Log events"),
737 FormField::switch("log_requests", "Log requests"),
738 FormField::text("retention_days", "Retention (days)"),
739 ],
740 route: None,
741 }
742 }
743
744 fn state(db: Db) -> AdminState {
745 AdminState::new(
746 laterite_auth::AuthService::new(db.clone(), laterite_auth::AuthConfig::default()),
747 db,
748 )
749 }
750
751 async fn test_db() -> (Db, laterite_core::testing::TestGuard) {
754 laterite_core::testing::connect_test(&[migrations()]).await
755 }
756
757 fn data(pairs: &[(&str, &str)]) -> HashMap<String, String> {
758 pairs
759 .iter()
760 .map(|(k, v)| (k.to_string(), v.to_string()))
761 .collect()
762 }
763
764 #[test]
765 fn group_orders_categories_then_items() {
766 let items = vec![
767 SettingsItem {
768 code: "b".into(),
769 label: "Beta".into(),
770 description: String::new().into(),
771 category: "System".into(),
772 hint: None,
773 order: 20,
774 icon: None,
775 permission: None,
776 link: None,
777 fields: vec![],
778 route: None,
779 },
780 SettingsItem {
781 code: "a".into(),
782 label: "Alpha".into(),
783 description: String::new().into(),
784 category: "System".into(),
785 hint: None,
786 order: 10,
787 icon: None,
788 permission: None,
789 link: None,
790 fields: vec![],
791 route: None,
792 },
793 SettingsItem {
794 code: "l".into(),
795 label: "Logs".into(),
796 description: String::new().into(),
797 category: "Logs".into(),
798 hint: None,
799 order: 5,
800 icon: None,
801 permission: None,
802 link: None,
803 fields: vec![],
804 route: None,
805 },
806 ];
807 let groups = sidebar_groups(
808 &items,
809 "/admin",
810 None,
811 &Translator::new("en"),
812 crate::icons::Icons::new(&laterite_core::icons::IconSet::new(), "/s.svg"),
813 );
814 assert_eq!(groups[0].name, "Logs");
816 assert_eq!(groups[1].name, "System");
817 assert_eq!(groups[1].items[0].label, "Alpha");
819 assert_eq!(groups[1].items[1].label, "Beta");
820 assert!(groups.iter().flat_map(|g| &g.items).all(|i| !i.active));
822 }
823
824 #[test]
825 fn group_marks_only_the_active_item() {
826 let items = vec![item()];
827 let groups = sidebar_groups(
828 &items,
829 "/admin",
830 Some("test.log"),
831 &Translator::new("en"),
832 crate::icons::Icons::new(&laterite_core::icons::IconSet::new(), "/s.svg"),
833 );
834 let active: Vec<&str> = groups
835 .iter()
836 .flat_map(|g| &g.items)
837 .filter(|i| i.active)
838 .map(|i| i.label.as_str())
839 .collect();
840 assert_eq!(active, ["Log Settings"]);
841 }
842
843 #[test]
844 fn settings_model_item_path_is_its_form() {
845 assert_eq!(item().path("/admin"), "/admin/settings/test/log");
848 assert_eq!(item().path("/manage"), "/manage/settings/test/log");
850
851 let mut resolved = item();
853 resolved.mount_at("/acme/logging/log");
854 assert_eq!(resolved.path("/admin"), "/admin/acme/logging/log");
855 }
856
857 #[test]
858 fn link_item_path_follows_the_link() {
859 let admins = crate::builtin_settings()
860 .into_iter()
861 .find(|i| i.code == "backend.administrators")
862 .unwrap();
863 assert_eq!(admins.category.source(), "Users");
864 assert!(admins.link.is_some());
865 assert!(admins.fields.is_empty());
866 assert_eq!(admins.path("/admin"), "/admin/users");
868 assert!(crate::builtin_settings()
869 .iter()
870 .any(|i| i.code == "backend.roles"));
871 }
872
873 #[tokio::test]
874 async fn update_persists_typed_values() {
875 let (db, _guard) = test_db().await;
876 let st = state(db.clone());
877
878 let it = item();
879 let resp = update(
880 &st,
881 &it,
882 data(&[("log_events", "on"), ("retention_days", "30")]),
884 crate::Shell::test(),
885 &crate::session::SessionHandle::from_blob(None),
886 &crate::audit::test_actor(),
887 )
888 .await;
889 assert_eq!(resp.status(), axum::http::StatusCode::SEE_OTHER);
890
891 let stored = store::get(&db, "test.log").await.unwrap().unwrap();
892 assert_eq!(stored["log_events"], serde_json::json!(true));
893 assert_eq!(stored["log_requests"], serde_json::json!(false));
894 assert_eq!(stored["retention_days"], serde_json::json!("30"));
895 }
896
897 #[test]
898 fn index_renders() {
899 let resp = index(crate::Shell::test());
900 assert_eq!(resp.status(), axum::http::StatusCode::OK);
901 }
902
903 #[tokio::test]
904 async fn edit_form_renders_for_unset_item() {
905 let (db, _guard) = test_db().await;
906 let st = state(db);
907 let it = item();
909 let resp = edit_form(&st, &it, crate::Shell::test()).await;
910 assert_eq!(resp.status(), axum::http::StatusCode::OK);
911 }
912}