Skip to main content

laterite_admin/settings/
mod.rs

1//! Descriptor-driven settings screens, and the settings store behind them.
2//!
3//! A module registers a [`SettingsItem`] for each settings model it wants an
4//! operator to edit: its storage `code` (the [`store::SettingsModel`] `CODE`), a
5//! `category` it groups under, and the fields to render. The framework mounts one
6//! index that lists every registered item grouped by category, and one generic
7//! form per item that reads and writes the model's JSON value through the
8//! [`store`]. No per-model controller is needed, exactly as a single settings
9//! controller serves every settings model.
10//!
11//! Values are stored as one JSON object per code. Field names are JSON keys, not
12//! SQL identifiers, and the value is written through a parameterized upsert, so
13//! nothing here builds SQL from user input.
14
15pub 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
23/// The `laterite.settings` module: the framework's settings store table.
24pub 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
46/// One editable field of a settings model.
47///
48/// A settings screen renders [`FormField`](crate::form::FormField)s, the same
49/// descriptors a list or form screen uses: the module declares which fields its
50/// settings model has, and the framework renders and stores them through the
51/// field-type registry. There is no settings-specific field vocabulary.
52pub use crate::form::FormField;
53
54/// A settings model surfaced in the admin: a storage `code`, a `category` and
55/// `order` that place it in the index, and the fields to edit.
56#[derive(Debug, Clone, Serialize)]
57#[non_exhaustive]
58pub struct SettingsItem {
59    /// Storage key. Matches the model's `SettingsModel::CODE`.
60    ///
61    /// This is a storage key and never a URL. It is dotted, like the module
62    /// identity it derives from, and a dotted identifier in a path is how these
63    /// screens spent months at `/settings/rainmill.discovery.robots`. Where the
64    /// screen mounts is [`SettingsItem::route`], resolved at boot through the
65    /// module's namespace like every other contributed screen.
66    pub code: String,
67    /// The item's label, description, and category heading, localized at render.
68    pub label: Text,
69    pub description: Text,
70    /// Group heading in the index.
71    pub category: Text,
72    /// A fuller explanation, shown as a note at the top of this screen and
73    /// nowhere else. Where [`SettingsItem::description`] must stay short enough
74    /// to read in a sidebar, this has room to say why the screen exists.
75    pub hint: Option<Text>,
76    /// Weight within the category (lower sorts first).
77    pub order: i32,
78    /// Icon name shown beside the item in the context sidebar (a Lucide name
79    /// such as `users` or `shield`). `None` falls back to a generic glyph.
80    pub icon: Option<String>,
81    /// Permission required to edit, enforced by middleware. `None` means any
82    /// authenticated operator.
83    pub permission: Option<String>,
84    /// When set, the item links to this route (e.g. a resource list) instead of
85    /// its settings form. Used to place list/form screens (like Administrators)
86    /// in the settings menu rather than the main menu.
87    pub link: Option<String>,
88    pub fields: Vec<FormField>,
89    /// Where this screen mounts, relative to the admin root, resolved at boot
90    /// from the contributing module's namespace. `None` until then.
91    pub(crate) route: Option<String>,
92}
93
94/// The longest a settings description may be: two lines of the context sidebar,
95/// which renders at 211 pixels and 12px type, so roughly 38 characters a line.
96/// The reference system's own descriptions run 27 to 90 characters with a median
97/// of 53, so this sits inside the range a mature panel actually uses.
98pub(crate) const MAX_DESCRIPTION: usize = 72;
99
100impl SettingsItem {
101    /// A settings screen for `code` (the model's `SettingsModel::CODE`), titled
102    /// `label`, editing `fields`.
103    ///
104    /// Everything else takes a default and is opted into through a builder
105    /// method, so a field added later costs existing callers nothing.
106    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    /// The sentence under the item's name in the index and sidebar.
123    ///
124    /// Keep it to two lines in the sidebar, which is 72 characters at the
125    /// panel's width. A description longer than that stops being a label and
126    /// starts being a lecture in a column 211 pixels wide; put the explanation
127    /// in [`SettingsItem::hint`], where the reader has already chosen to look.
128    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    /// A fuller explanation for the top of this screen. Unlike the description,
142    /// it has no length limit: the reader has opened the screen.
143    pub fn hint(mut self, text: impl Into<Text>) -> Self {
144        self.hint = Some(text.into());
145        self
146    }
147
148    /// The group heading this item sorts under.
149    pub fn category(mut self, text: impl Into<Text>) -> Self {
150        self.category = text.into();
151        self
152    }
153
154    /// Weight within the category; lower sorts first.
155    pub fn order(mut self, order: i32) -> Self {
156        self.order = order;
157        self
158    }
159
160    /// A Lucide icon name shown beside the item.
161    pub fn icon(mut self, icon: impl Into<String>) -> Self {
162        self.icon = Some(icon.into());
163        self
164    }
165
166    /// The permission required to edit, enforced by middleware.
167    pub fn permission(mut self, permission: impl Into<String>) -> Self {
168        self.permission = Some(permission.into());
169        self
170    }
171
172    /// Point the item at an existing route instead of its own settings form, so
173    /// a list screen can sit in the settings menu.
174    pub fn link(mut self, link: impl Into<String>) -> Self {
175        self.link = Some(link.into());
176        self
177    }
178
179    /// Records where this screen mounts. Called once at boot, after the
180    /// contributing module's namespace has been resolved.
181    pub(crate) fn mount_at(&mut self, route: impl Into<String>) {
182        self.route = Some(route.into());
183    }
184
185    /// Mounts this screen at a fixed path rather than a module namespace.
186    ///
187    /// For the panel's own settings, which belong to no vendor: they configure
188    /// the admin itself, so they sit under `/settings` with a plain name
189    /// (`/settings/branding`) rather than carrying `laterite` through a URL an
190    /// operator reads. A module's settings live in the module's namespace.
191    pub(crate) fn at(mut self, route: impl Into<String>) -> Self {
192        self.route = Some(route.into());
193        self
194    }
195
196    /// The item's own screen, relative to the admin root, ignoring any `link`.
197    ///
198    /// Before boot resolves it, this falls back to a path under `/settings`
199    /// built from the code's segments rather than the dotted code itself, so
200    /// even the fallback is a URL rather than an identifier. See
201    /// [`SettingsItem::at`] for why the panel's own settings pin theirs.
202    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    /// Where this item leads, resolved under the admin mount (`admin_path`): its
210    /// `link` target if set, else its own settings screen. Both are authored
211    /// relative to the admin root, so this prepends the mount.
212    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
220/// Renders the settings index: a prompt to pick a section. The context sidebar
221/// itself is resolved by the auth guard and rendered by the shell.
222pub(crate) fn index(shell: crate::Shell) -> Response {
223    render(SettingsIndexTemplate { shell })
224}
225
226/// Renders the edit form for one item, populated from its stored value. The
227/// context sidebar (with this item active) comes from the shell.
228pub(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 unset fields from config so they show the current effective value
238    // rather than opening blank. Display only; nothing is written.
239    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
250/// Persists submitted values as the item's JSON object, then returns to the index.
251pub(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    // A field type that refuses its input refuses the save: the screen says so
260    // rather than storing a value every later read has to defend against.
261    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            // The brand is cached for display; a save to it must invalidate the
282            // cache so the next page reflects the new name.
283            if item.code == brand::BrandSetting::CODE {
284                state.invalidate_brand();
285            }
286            // The stored value can hold secrets, so the audit records which
287            // settings model changed, not the new contents.
288            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            // Back to the screen that was saved, not the index. Saving is not
299            // leaving: an operator adjusting one setting usually adjusts the
300            // next, and being thrown back to the menu loses their place.
301            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
314/// Builds the JSON object to store from the submitted form data, typing each
315/// field through its field type.
316///
317/// The same `to_attr` a descriptor form writes through, so a switch stores a
318/// bool, a repeater stores an array of objects, and a module's own field type
319/// behaves identically here and on a form. A type that refuses its input refuses
320/// the save, naming the field.
321fn 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        // Settings always write every declared key: a settings blob has no
336        // previous row to fall back to the way a table column does.
337        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
347/// A stored attribute as the JSON a settings blob holds.
348fn 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
360/// Builds the context-sidebar groups: items grouped by category and ordered
361/// deterministically, with `active_code` (if any) marked. Categories sort by
362/// their lowest item `order`, then name; items by `order`, then label. This is
363/// the simple-weight stage; relative-anchor ordering with an operator override
364/// is a later refinement.
365pub(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    // Group by the localized category heading (a shared source localizes identically).
373    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            // Order by weight, then the label's source for a stable tie-break.
384            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
413/// Prefills unset display fields from configuration before the form renders, so
414/// a field shows the current effective value rather than opening blank. The
415/// brand's application name prefills from the configured `app.name` when no brand
416/// setting is saved. This is display only: it writes nothing, so a later config
417/// change still propagates (persisting it would freeze the value). It is not a
418/// database seeder; that is a separate, deferred capability.
419fn 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/// One category block in the context sidebar. Rendered by the shell.
507#[derive(Clone)]
508pub(crate) struct CategoryView {
509    pub(crate) name: String,
510    min_order: i32,
511    pub(crate) items: Vec<ItemView>,
512}
513
514/// One item in the context sidebar.
515#[derive(Clone)]
516pub(crate) struct ItemView {
517    pub(crate) label: String,
518    pub(crate) description: String,
519    pub(crate) path: String,
520    /// Inline SVG markup for the item's icon, rendered raw in the template.
521    pub(crate) icon: String,
522    /// Whether this is the item currently open, so the sidebar highlights it.
523    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    /// The control, rendered by the field's own type.
536    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    /// The item's fuller explanation, localized. Supersedes `description` on
546    /// this screen, which is written for a sidebar.
547    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        // The shape the discovery plugin shipped with: 108 characters, four
561        // lines in a 211-pixel sidebar.
562        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        // The hint has no ceiling: the reader has opened the screen.
578        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    /// Settings and forms now share one field system, so a settings screen gets
605    /// every registered type and stores what that type says it stores.
606    #[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        // A bool, not the string "on": the switch field type decided that.
628        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    /// An unticked switch is absent from the submission and must store false,
634    /// or the box could never be cleared.
635    #[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    /// The repeater works in settings because it is a field type, not a
643    /// settings-only widget: this is the whole point of the unification.
644    #[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        // Unset: the field prefills from the configured application name.
711        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        // Already set: the stored value is left untouched.
715        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        // A non-brand item is not prefilled.
719        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    /// A fresh test database with the settings table migrated in, on whichever
752    /// backend the run targets. Hold the returned guard for the test's lifetime.
753    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        // "Logs" (min order 5) comes before "System" (min order 10).
815        assert_eq!(groups[0].name, "Logs");
816        assert_eq!(groups[1].name, "System");
817        // Within "System", Alpha (10) before Beta (20).
818        assert_eq!(groups[1].items[0].label, "Alpha");
819        assert_eq!(groups[1].items[1].label, "Beta");
820        // Nothing is active when no code is given.
821        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        // Unresolved (no module namespace yet), the fallback still builds a
846        // path from the code's segments rather than using the dotted key.
847        assert_eq!(item().path("/admin"), "/admin/settings/test/log");
848        // The mount is honoured, so a relocated panel keeps consistent links.
849        assert_eq!(item().path("/manage"), "/manage/settings/test/log");
850
851        // Once boot resolves it into the module's namespace, that wins.
852        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        // links to the resource list, not a settings form
867        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            // log_requests is absent, as an unchecked checkbox would be.
883            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        // No stored value yet: the form still renders (fields fall back to defaults).
908        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}