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 confirm_leave: bool,
78 pub order: i32,
80 pub icon: Option<String>,
83 pub permission: Option<String>,
86 pub link: Option<String>,
90 pub fields: Vec<FormField>,
91 pub(crate) route: Option<String>,
94}
95
96pub(crate) const MAX_DESCRIPTION: usize = 72;
101
102impl SettingsItem {
103 pub fn new(code: impl Into<String>, label: impl Into<Text>, fields: Vec<FormField>) -> Self {
109 Self {
110 code: code.into(),
111 label: label.into(),
112 description: Text::from(""),
113 category: Text::from(""),
114 hint: None,
115 confirm_leave: true,
116 order: 0,
117 icon: None,
118 permission: None,
119 link: None,
120 fields,
121 route: None,
122 }
123 }
124
125 pub fn description(mut self, text: impl Into<Text>) -> Self {
132 let text = text.into();
133 debug_assert!(
134 text.source().chars().count() <= MAX_DESCRIPTION,
135 "settings description is {} characters, over the {MAX_DESCRIPTION} that \
136 fit two sidebar lines; shorten it or move the detail to `hint`: {:?}",
137 text.source().chars().count(),
138 text.source(),
139 );
140 self.description = text;
141 self
142 }
143
144 pub fn hint(mut self, text: impl Into<Text>) -> Self {
147 self.hint = Some(text.into());
148 self
149 }
150
151 pub fn confirm_leave(mut self, ask: bool) -> Self {
154 self.confirm_leave = ask;
155 self
156 }
157
158 pub fn category(mut self, text: impl Into<Text>) -> Self {
160 self.category = text.into();
161 self
162 }
163
164 pub fn order(mut self, order: i32) -> Self {
166 self.order = order;
167 self
168 }
169
170 pub fn icon(mut self, icon: impl Into<String>) -> Self {
172 self.icon = Some(icon.into());
173 self
174 }
175
176 pub fn permission(mut self, permission: impl Into<String>) -> Self {
178 self.permission = Some(permission.into());
179 self
180 }
181
182 pub fn link(mut self, link: impl Into<String>) -> Self {
185 self.link = Some(link.into());
186 self
187 }
188
189 pub(crate) fn mount_at(&mut self, route: impl Into<String>) {
192 self.route = Some(route.into());
193 }
194
195 pub(crate) fn at(mut self, route: impl Into<String>) -> Self {
202 self.route = Some(route.into());
203 self
204 }
205
206 pub(crate) fn route(&self) -> String {
213 match &self.route {
214 Some(route) => route.clone(),
215 None => format!("/settings/{}", self.code.replace('.', "/")),
216 }
217 }
218
219 pub fn path(&self, admin_path: &str) -> String {
223 match &self.link {
224 Some(link) => format!("{admin_path}{link}"),
225 None => format!("{admin_path}{}", self.route()),
226 }
227 }
228}
229
230pub(crate) fn index(shell: crate::Shell) -> Response {
233 render(SettingsIndexTemplate { shell })
234}
235
236pub(crate) async fn edit_form(
239 state: &AdminState,
240 item: &SettingsItem,
241 shell: crate::Shell,
242) -> Response {
243 let mut stored = match store::get(&state.db, &item.code).await {
244 Ok(value) => value.unwrap_or_else(|| Value::Object(Map::new())),
245 Err(_) => return render_error(),
246 };
247 prefill_from_config(item, &mut stored, &state.app_name);
250 render(build(
251 item,
252 &state.field_types,
253 state.overrides.as_ref(),
254 None,
255 &stored,
256 &shell,
257 ))
258}
259
260pub(crate) async fn update(
262 state: &AdminState,
263 item: &SettingsItem,
264 data: HashMap<String, String>,
265 shell: crate::Shell,
266 session: &crate::session::SessionHandle,
267 user: &laterite_auth::AuthenticatedUser,
268) -> Response {
269 let value = match collect(item, &state.field_types, &data) {
272 Ok(value) => value,
273 Err(message) => {
274 let stored = store::get(&state.db, &item.code)
275 .await
276 .ok()
277 .flatten()
278 .unwrap_or(Value::Null);
279 return render(build(
280 item,
281 &state.field_types,
282 state.overrides.as_ref(),
283 Some(message),
284 &stored,
285 &shell,
286 ));
287 }
288 };
289 match store::set(&state.db, &item.code, &value).await {
290 Ok(()) => {
291 if item.code == brand::BrandSetting::CODE {
294 state.invalidate_brand();
295 }
296 crate::audit::record(
299 state,
300 user,
301 "backend.settings.update",
302 Some("settings"),
303 Some(item.code.as_str()),
304 None,
305 None,
306 )
307 .await;
308 session.push_flash(crate::session::FlashLevel::Success, t!("Settings saved."));
309 Redirect::to(&item.path(&state.admin_path)).into_response()
313 }
314 Err(_) => render(build(
315 item,
316 &state.field_types,
317 state.overrides.as_ref(),
318 Some(t!("Could not save. Please try again.")),
319 &value,
320 &shell,
321 )),
322 }
323}
324
325fn collect(
333 item: &SettingsItem,
334 types: &crate::field::FieldRegistry,
335 data: &HashMap<String, String>,
336) -> Result<Value, Text> {
337 let mut object = Map::new();
338 for field in &item.fields {
339 let Some(field_type) = types.get(&field.field_type) else {
340 return Err(t!("This screen uses a field type that is not registered."));
341 };
342 let opts = field_type
343 .resolve_options(&field.options, types)
344 .map_err(|_| t!("This screen has a malformed field."))?;
345 let submitted = crate::field::SubmittedField::new(&field.name, data);
346 let value = match field_type.to_attr(&submitted, &opts, Mode::Update) {
349 Ok(Some(value)) => attr_to_json(value),
350 Ok(None) => Value::String(String::new()),
351 Err(_) => return Err(t!("Check the values and try again.")),
352 };
353 object.insert(field.name.clone(), value);
354 }
355 Ok(Value::Object(object))
356}
357
358fn attr_to_json(value: laterite_core::AttrValue) -> Value {
360 use laterite_core::AttrValue;
361 match value {
362 AttrValue::Null => Value::String(String::new()),
363 AttrValue::Bool(b) => Value::Bool(b),
364 AttrValue::Int(i) => Value::from(i),
365 AttrValue::Float(f) => Value::from(f),
366 AttrValue::Json(j) => j,
367 other => Value::String(other.to_text().unwrap_or_default()),
368 }
369}
370
371pub(crate) fn sidebar_groups(
377 items: &[SettingsItem],
378 admin_path: &str,
379 active_code: Option<&str>,
380 tr: &Translator,
381 icons: crate::icons::Icons<'_>,
382) -> Vec<CategoryView> {
383 let mut by_category: HashMap<String, Vec<&SettingsItem>> = HashMap::new();
385 for item in items {
386 by_category
387 .entry(tr.t(&item.category))
388 .or_default()
389 .push(item);
390 }
391 let mut groups: Vec<CategoryView> = by_category
392 .into_iter()
393 .map(|(category, mut items)| {
394 items.sort_by(|a, b| {
396 a.order
397 .cmp(&b.order)
398 .then_with(|| a.label.source().cmp(b.label.source()))
399 });
400 CategoryView {
401 min_order: items.iter().map(|i| i.order).min().unwrap_or(0),
402 name: category,
403 items: items
404 .iter()
405 .map(|i| ItemView {
406 label: tr.t(&i.label),
407 description: tr.t(&i.description),
408 path: i.path(admin_path),
409 icon: icons.render(i.icon.as_deref()),
410 active: active_code == Some(i.code.as_str()),
411 })
412 .collect(),
413 }
414 })
415 .collect();
416 groups.sort_by(|a, b| {
417 a.min_order
418 .cmp(&b.min_order)
419 .then_with(|| a.name.cmp(&b.name))
420 });
421 groups
422}
423
424fn prefill_from_config(item: &SettingsItem, stored: &mut Value, app_name: &str) {
431 if item.code != brand::BrandSetting::CODE {
432 return;
433 }
434 if let Value::Object(map) = stored {
435 let blank = map
436 .get("app_name")
437 .and_then(Value::as_str)
438 .unwrap_or("")
439 .trim()
440 .is_empty();
441 if blank {
442 map.insert("app_name".to_string(), Value::String(app_name.to_string()));
443 }
444 }
445}
446
447fn build(
448 item: &SettingsItem,
449 types: &crate::field::FieldRegistry,
450 overrides: &dyn crate::field::OverrideResolver,
451 error: Option<Text>,
452 stored: &Value,
453 shell: &crate::Shell,
454) -> SettingsFormTemplate {
455 let fields = item
456 .fields
457 .iter()
458 .map(|f| {
459 let label = shell.tt(&f.label);
460 let control = match types.get(&f.field_type) {
461 Some(ft) => {
462 let opts = ft
463 .resolve_options(&f.options, types)
464 .unwrap_or_else(|_| crate::field::ResolvedOptions::none());
465 let value = match stored.get(&f.name) {
466 Some(Value::Array(rows)) => {
467 crate::field::FieldValue::Json(Value::Array(rows.clone()))
468 }
469 Some(Value::String(text)) => {
470 crate::field::FieldValue::Text(ft.to_control(Some(text), &opts))
471 }
472 Some(Value::Null) | None => {
473 crate::field::FieldValue::Text(ft.to_control(None, &opts))
474 }
475 Some(other) => crate::field::FieldValue::Text(
476 ft.to_control(Some(&other.to_string()), &opts),
477 ),
478 };
479 let cx = crate::field::FieldCx {
480 name: &f.name,
481 id: &f.name,
482 label: &label,
483 value: &value,
484 required: false,
485 max_length: crate::form::max_length(&f.rules),
486 opts: &opts,
487 base: &shell.base,
488 i18n: shell.i18n(),
489 };
490 let scope = crate::field::OverrideScope {
491 surface: crate::field::Surface::Field,
492 view_key: &f.field_type,
493 resource: Some(&item.code),
494 field: Some(&f.name),
495 };
496 crate::field::render_field(ft.as_ref(), overrides, &scope, &cx).into_string()
497 }
498 None => String::new(),
499 };
500 FieldView {
501 label,
502 help: f.help.as_ref().map(|h| shell.tt(h)),
503 control,
504 layout: crate::form::layout_classes(f.span, f.break_row),
505 }
506 })
507 .collect();
508 SettingsFormTemplate {
509 title: shell.tt(&item.label),
510 description: shell.tt(&item.description),
511 hint: item.hint.as_ref().map(|h| shell.tt(h)),
512 action: item.path(&shell.base),
513 error: error.map(|e| shell.tt(&e)),
514 fields,
515 leave_off: !item.confirm_leave,
516 shell: shell.clone(),
517 }
518}
519
520#[derive(Clone)]
522pub(crate) struct CategoryView {
523 pub(crate) name: String,
524 min_order: i32,
525 pub(crate) items: Vec<ItemView>,
526}
527
528#[derive(Clone)]
530pub(crate) struct ItemView {
531 pub(crate) label: String,
532 pub(crate) description: String,
533 pub(crate) path: String,
534 pub(crate) icon: String,
536 pub(crate) active: bool,
538}
539
540#[derive(Template)]
541#[template(path = "settings_index.html")]
542struct SettingsIndexTemplate {
543 shell: crate::Shell,
544}
545
546struct FieldView {
547 label: String,
548 help: Option<String>,
549 control: String,
551 layout: String,
553}
554
555#[derive(Template)]
556#[template(path = "settings_form.html")]
557struct SettingsFormTemplate {
558 shell: crate::Shell,
559 title: String,
560 description: String,
561 hint: Option<String>,
564 action: String,
565 error: Option<String>,
566 fields: Vec<FieldView>,
567 leave_off: bool,
569}
570
571#[cfg(test)]
572mod field_system_tests {
573 use super::*;
574
575 #[test]
576 #[should_panic(expected = "over the 72")]
577 fn a_lecture_of_a_description_is_refused() {
578 SettingsItem::new("acme.test", "Test", Vec::new()).description(
581 "What search engines and other crawlers may visit. The admin panel \
582 is always excluded, whatever you put here.",
583 );
584 }
585
586 #[test]
587 fn a_label_sized_description_passes_and_a_hint_carries_the_rest() {
588 let item = SettingsItem::new("acme.test", "Test", Vec::new())
589 .description("Which crawlers may visit, and what they may not.")
590 .hint(
591 "The admin panel is always excluded, whatever you put here, and a \
592 crawler obeys only the block that names it.",
593 );
594 assert!(item.description.source().chars().count() <= MAX_DESCRIPTION);
595 assert!(item.hint.is_some());
597 }
598
599 fn item(fields: Vec<FormField>) -> SettingsItem {
600 SettingsItem {
601 code: "acme.test".to_string(),
602 label: Text::new(""),
603 description: Text::new(""),
604 category: Text::new(""),
605 hint: None,
606 confirm_leave: true,
607 order: 0,
608 icon: None,
609 permission: None,
610 link: None,
611 fields,
612 route: None,
613 }
614 }
615
616 fn submitted(pairs: &[(&str, &str)]) -> HashMap<String, String> {
617 pairs
618 .iter()
619 .map(|(k, v)| (k.to_string(), v.to_string()))
620 .collect()
621 }
622
623 #[test]
626 fn settings_store_what_the_field_type_says() {
627 let cfg = item(vec![
628 FormField::text("name", "Name"),
629 FormField::switch("enabled", "Enabled"),
630 FormField::select("freq", "Frequency", vec![("daily", "Daily")]),
631 FormField::date("expires", "Expires"),
632 ]);
633 let stored = collect(
634 &cfg,
635 &crate::field::builtin_registry(),
636 &submitted(&[
637 ("name", "Acme"),
638 ("enabled", "on"),
639 ("freq", "daily"),
640 ("expires", "2026-12-31"),
641 ]),
642 )
643 .unwrap();
644
645 assert_eq!(stored["name"], "Acme");
646 assert_eq!(stored["enabled"], serde_json::json!(true));
648 assert_eq!(stored["freq"], "daily");
649 assert_eq!(stored["expires"], "2026-12-31");
650 }
651
652 #[test]
655 fn an_unticked_switch_clears() {
656 let cfg = item(vec![FormField::switch("enabled", "Enabled")]);
657 let stored = collect(&cfg, &crate::field::builtin_registry(), &submitted(&[])).unwrap();
658 assert_eq!(stored["enabled"], serde_json::json!(false));
659 }
660
661 #[test]
664 fn a_repeater_works_in_settings() {
665 let cfg = item(vec![FormField::repeater(
666 "rules",
667 "Rules",
668 vec![
669 FormField::text("path", "Path"),
670 FormField::switch("allow", "Allow"),
671 ],
672 )]);
673 let stored = collect(
674 &cfg,
675 &crate::field::builtin_registry(),
676 &submitted(&[
677 ("rules[0][path]", "/private"),
678 ("rules[1][path]", "/public"),
679 ("rules[1][allow]", "on"),
680 ]),
681 )
682 .unwrap();
683
684 let rows = stored["rules"].as_array().unwrap();
685 assert_eq!(rows.len(), 2);
686 assert_eq!(rows[0]["path"], "/private");
687 assert_eq!(rows[0]["allow"], serde_json::json!(false));
688 assert_eq!(rows[1]["allow"], serde_json::json!(true));
689 }
690
691 #[test]
692 fn a_screen_naming_an_unregistered_type_refuses_rather_than_rendering_blank() {
693 let cfg = item(vec![FormField::of("x", "X", "acme.nope")]);
694 assert!(collect(&cfg, &crate::field::builtin_registry(), &submitted(&[])).is_err());
695 }
696
697 #[test]
698 fn the_form_renders_each_control_through_its_type() {
699 let cfg = item(vec![
700 FormField::switch("enabled", "Enabled"),
701 FormField::repeater("rules", "Rules", vec![FormField::text("path", "Path")]),
702 ]);
703 let html = build(
704 &cfg,
705 &crate::field::builtin_registry(),
706 &crate::field::NoOverrides,
707 None,
708 &serde_json::json!({ "enabled": true, "rules": [{ "path": "/a" }] }),
709 &crate::Shell::test(),
710 )
711 .render()
712 .unwrap();
713
714 assert!(html.contains(r#"type="checkbox""#));
715 assert!(html.contains(r#"name="rules[0][path]""#));
716 assert!(html.contains(r#"value="/a""#));
717 assert!(html.contains("lat-repeater__blank"));
718 }
719}
720
721#[cfg(test)]
722mod tests {
723 use super::*;
724 use laterite_core::Db;
725
726 #[test]
727 fn brand_form_prefills_app_name_from_config_when_unset() {
728 let brand = brand::settings_item();
729 let mut unset = Value::Object(Map::new());
731 prefill_from_config(&brand, &mut unset, "Configured Name");
732 assert_eq!(unset["app_name"], serde_json::json!("Configured Name"));
733 let mut set = serde_json::json!({ "app_name": "Acme" });
735 prefill_from_config(&brand, &mut set, "Configured Name");
736 assert_eq!(set["app_name"], serde_json::json!("Acme"));
737 let mut other = Value::Object(Map::new());
739 prefill_from_config(&item(), &mut other, "Configured Name");
740 assert!(other.get("app_name").is_none());
741 }
742
743 fn item() -> SettingsItem {
744 SettingsItem {
745 code: "test.log".to_string(),
746 label: "Log Settings".into(),
747 description: "What the log records.".into(),
748 category: "Logs".into(),
749 hint: None,
750 confirm_leave: true,
751 order: 10,
752 icon: None,
753 permission: None,
754 link: None,
755 fields: vec![
756 FormField::switch("log_events", "Log events"),
757 FormField::switch("log_requests", "Log requests"),
758 FormField::text("retention_days", "Retention (days)"),
759 ],
760 route: None,
761 }
762 }
763
764 fn state(db: Db) -> AdminState {
765 AdminState::new(
766 laterite_auth::AuthService::new(db.clone(), laterite_auth::AuthConfig::default()),
767 db,
768 )
769 }
770
771 async fn test_db() -> (Db, laterite_core::testing::TestGuard) {
774 laterite_core::testing::connect_test(&[migrations()]).await
775 }
776
777 fn data(pairs: &[(&str, &str)]) -> HashMap<String, String> {
778 pairs
779 .iter()
780 .map(|(k, v)| (k.to_string(), v.to_string()))
781 .collect()
782 }
783
784 #[test]
785 fn group_orders_categories_then_items() {
786 let items = vec![
787 SettingsItem {
788 code: "b".into(),
789 label: "Beta".into(),
790 description: String::new().into(),
791 category: "System".into(),
792 hint: None,
793 confirm_leave: true,
794 order: 20,
795 icon: None,
796 permission: None,
797 link: None,
798 fields: vec![],
799 route: None,
800 },
801 SettingsItem {
802 code: "a".into(),
803 label: "Alpha".into(),
804 description: String::new().into(),
805 category: "System".into(),
806 hint: None,
807 confirm_leave: true,
808 order: 10,
809 icon: None,
810 permission: None,
811 link: None,
812 fields: vec![],
813 route: None,
814 },
815 SettingsItem {
816 code: "l".into(),
817 label: "Logs".into(),
818 description: String::new().into(),
819 category: "Logs".into(),
820 hint: None,
821 confirm_leave: true,
822 order: 5,
823 icon: None,
824 permission: None,
825 link: None,
826 fields: vec![],
827 route: None,
828 },
829 ];
830 let groups = sidebar_groups(
831 &items,
832 "/admin",
833 None,
834 &Translator::new("en"),
835 crate::icons::Icons::new(&laterite_core::icons::IconSet::new(), "/s.svg"),
836 );
837 assert_eq!(groups[0].name, "Logs");
839 assert_eq!(groups[1].name, "System");
840 assert_eq!(groups[1].items[0].label, "Alpha");
842 assert_eq!(groups[1].items[1].label, "Beta");
843 assert!(groups.iter().flat_map(|g| &g.items).all(|i| !i.active));
845 }
846
847 #[test]
848 fn group_marks_only_the_active_item() {
849 let items = vec![item()];
850 let groups = sidebar_groups(
851 &items,
852 "/admin",
853 Some("test.log"),
854 &Translator::new("en"),
855 crate::icons::Icons::new(&laterite_core::icons::IconSet::new(), "/s.svg"),
856 );
857 let active: Vec<&str> = groups
858 .iter()
859 .flat_map(|g| &g.items)
860 .filter(|i| i.active)
861 .map(|i| i.label.as_str())
862 .collect();
863 assert_eq!(active, ["Log Settings"]);
864 }
865
866 #[test]
867 fn settings_model_item_path_is_its_form() {
868 assert_eq!(item().path("/admin"), "/admin/settings/test/log");
871 assert_eq!(item().path("/manage"), "/manage/settings/test/log");
873
874 let mut resolved = item();
876 resolved.mount_at("/acme/logging/log");
877 assert_eq!(resolved.path("/admin"), "/admin/acme/logging/log");
878 }
879
880 #[test]
881 fn link_item_path_follows_the_link() {
882 let admins = crate::builtin_settings()
883 .into_iter()
884 .find(|i| i.code == "backend.administrators")
885 .unwrap();
886 assert_eq!(admins.category.source(), "Users");
887 assert!(admins.link.is_some());
888 assert!(admins.fields.is_empty());
889 assert_eq!(admins.path("/admin"), "/admin/users");
891 assert!(crate::builtin_settings()
892 .iter()
893 .any(|i| i.code == "backend.roles"));
894 }
895
896 #[tokio::test]
897 async fn update_persists_typed_values() {
898 let (db, _guard) = test_db().await;
899 let st = state(db.clone());
900
901 let it = item();
902 let resp = update(
903 &st,
904 &it,
905 data(&[("log_events", "on"), ("retention_days", "30")]),
907 crate::Shell::test(),
908 &crate::session::SessionHandle::from_blob(None),
909 &crate::audit::test_actor(),
910 )
911 .await;
912 assert_eq!(resp.status(), axum::http::StatusCode::SEE_OTHER);
913
914 let stored = store::get(&db, "test.log").await.unwrap().unwrap();
915 assert_eq!(stored["log_events"], serde_json::json!(true));
916 assert_eq!(stored["log_requests"], serde_json::json!(false));
917 assert_eq!(stored["retention_days"], serde_json::json!("30"));
918 }
919
920 #[test]
921 fn index_renders() {
922 let resp = index(crate::Shell::test());
923 assert_eq!(resp.status(), axum::http::StatusCode::OK);
924 }
925
926 #[tokio::test]
927 async fn edit_form_renders_for_unset_item() {
928 let (db, _guard) = test_db().await;
929 let st = state(db);
930 let it = item();
932 let resp = edit_form(&st, &it, crate::Shell::test()).await;
933 assert_eq!(resp.status(), axum::http::StatusCode::OK);
934 }
935}