laterite-admin 0.9.12

Laterite CMF admin surface: the Axum router, session middleware, and login shell
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
//! Descriptor-driven settings screens, and the settings store behind them.
//!
//! A module registers a [`SettingsItem`] for each settings model it wants an
//! operator to edit: its storage `code` (the [`store::SettingsModel`] `CODE`), a
//! `category` it groups under, and the fields to render. The framework mounts one
//! index that lists every registered item grouped by category, and one generic
//! form per item that reads and writes the model's JSON value through the
//! [`store`]. No per-model controller is needed, exactly as a single settings
//! controller serves every settings model.
//!
//! Values are stored as one JSON object per code. Field names are JSON keys, not
//! SQL identifiers, and the value is written through a parameterized upsert, so
//! nothing here builds SQL from user input.

pub mod brand;
pub mod migrations;
pub mod store;

pub use brand::BrandSetting;
pub use migrations::{migrations, MODULE_ID};
pub use store::{
    get, get_for, load, load_for, save, save_for, set, set_for, PreferencesError, PreferencesModel,
    SettingsError, SettingsModel,
};

/// The `laterite.settings` module: the framework's settings store table.
pub struct SettingsModule;

impl laterite_core::Module for SettingsModule {
    fn id(&self) -> laterite_core::ModuleId {
        laterite_core::ModuleId::new(MODULE_ID)
    }
    fn migrations(&self) -> laterite_core::MigrationSet {
        migrations()
    }
}

use std::collections::HashMap;

use askama::Template;
use axum::response::{IntoResponse, Redirect, Response};
use laterite_core::validation::Mode;
use laterite_core::{t, Text, Translator};
use serde::Serialize;
use serde_json::{Map, Value};

use crate::{render, render_error, AdminState};

/// One editable field of a settings model.
///
/// A settings screen renders [`FormField`](crate::form::FormField)s, the same
/// descriptors a list or form screen uses: the module declares which fields its
/// settings model has, and the framework renders and stores them through the
/// field-type registry. There is no settings-specific field vocabulary.
pub use crate::form::FormField;

/// A settings model surfaced in the admin: a storage `code`, a `category` and
/// `order` that place it in the index, and the fields to edit.
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct SettingsItem {
    /// Storage key. Matches the model's `SettingsModel::CODE`.
    ///
    /// This is a storage key and never a URL. It is dotted, like the module
    /// identity it derives from, and a dotted identifier in a path is how these
    /// screens spent months at `/settings/rainmill.discovery.robots`. Where the
    /// screen mounts is [`SettingsItem::route`], resolved at boot through the
    /// module's namespace like every other contributed screen.
    pub code: String,
    /// The item's label, description, and category heading, localized at render.
    pub label: Text,
    pub description: Text,
    /// Group heading in the index.
    pub category: Text,
    /// A fuller explanation, shown as a note at the top of this screen and
    /// nowhere else. Where [`SettingsItem::description`] must stay short enough
    /// to read in a sidebar, this has room to say why the screen exists.
    pub hint: Option<Text>,
    /// Ask before leaving this screen with changes unsaved. Default `true`.
    pub confirm_leave: bool,
    /// Weight within the category (lower sorts first).
    pub order: i32,
    /// Icon name shown beside the item in the context sidebar (a Lucide name
    /// such as `users` or `shield`). `None` falls back to a generic glyph.
    pub icon: Option<String>,
    /// Permission required to edit, enforced by middleware. `None` means any
    /// authenticated operator.
    pub permission: Option<String>,
    /// When set, the item links to this route (e.g. a resource list) instead of
    /// its settings form. Used to place list/form screens (like Administrators)
    /// in the settings menu rather than the main menu.
    pub link: Option<String>,
    pub fields: Vec<FormField>,
    /// Where this screen mounts, relative to the admin root, resolved at boot
    /// from the contributing module's namespace. `None` until then.
    pub(crate) route: Option<String>,
    /// Stored once per operator, among their preferences, and edited from
    /// the Preferences page rather than Settings. See [`store::PreferencesModel`].
    pub per_operator: bool,
}

/// The longest a settings description may be: two lines of the context sidebar,
/// which renders at 211 pixels and 12px type, so roughly 38 characters a line.
/// The reference system's own descriptions run 27 to 90 characters with a median
/// of 53, so this sits inside the range a mature panel actually uses.
pub(crate) const MAX_DESCRIPTION: usize = 72;

impl SettingsItem {
    /// A settings screen for `code` (the model's `SettingsModel::CODE`), titled
    /// `label`, editing `fields`.
    ///
    /// Everything else takes a default and is opted into through a builder
    /// method, so a field added later costs existing callers nothing.
    pub fn new(code: impl Into<String>, label: impl Into<Text>, fields: Vec<FormField>) -> Self {
        Self {
            code: code.into(),
            label: label.into(),
            description: Text::from(""),
            category: Text::from(""),
            hint: None,
            confirm_leave: true,
            order: 0,
            icon: None,
            permission: None,
            link: None,
            fields,
            route: None,
            per_operator: false,
        }
    }

    /// Keeps a value per operator, edited from their Preferences page. The
    /// permission still applies; the category is not used.
    pub fn per_operator(mut self) -> Self {
        self.per_operator = true;
        self
    }

    /// The sentence under the item's name in the index and sidebar.
    ///
    /// Keep it to two lines in the sidebar, which is 72 characters at the
    /// panel's width. A description longer than that stops being a label and
    /// starts being a lecture in a column 211 pixels wide; put the explanation
    /// in [`SettingsItem::hint`], where the reader has already chosen to look.
    pub fn description(mut self, text: impl Into<Text>) -> Self {
        let text = text.into();
        debug_assert!(
            text.source().chars().count() <= MAX_DESCRIPTION,
            "settings description is {} characters, over the {MAX_DESCRIPTION} that \
             fit two sidebar lines; shorten it or move the detail to `hint`: {:?}",
            text.source().chars().count(),
            text.source(),
        );
        self.description = text;
        self
    }

    /// A fuller explanation for the top of this screen. Unlike the description,
    /// it has no length limit: the reader has opened the screen.
    pub fn hint(mut self, text: impl Into<Text>) -> Self {
        self.hint = Some(text.into());
        self
    }

    /// Whether leaving this screen with changes unsaved asks first. Default
    /// `true`.
    pub fn confirm_leave(mut self, ask: bool) -> Self {
        self.confirm_leave = ask;
        self
    }

    /// The group heading this item sorts under.
    pub fn category(mut self, text: impl Into<Text>) -> Self {
        self.category = text.into();
        self
    }

    /// Weight within the category; lower sorts first.
    pub fn order(mut self, order: i32) -> Self {
        self.order = order;
        self
    }

    /// A Lucide icon name shown beside the item.
    pub fn icon(mut self, icon: impl Into<String>) -> Self {
        self.icon = Some(icon.into());
        self
    }

    /// The permission required to edit, enforced by middleware.
    pub fn permission(mut self, permission: impl Into<String>) -> Self {
        self.permission = Some(permission.into());
        self
    }

    /// Point the item at an existing route instead of its own settings form, so
    /// a list screen can sit in the settings menu.
    pub fn link(mut self, link: impl Into<String>) -> Self {
        self.link = Some(link.into());
        self
    }

    /// Records where this screen mounts. Called once at boot, after the
    /// contributing module's namespace has been resolved.
    pub(crate) fn mount_at(&mut self, route: impl Into<String>) {
        self.route = Some(route.into());
    }

    /// Mounts this screen at a fixed path rather than a module namespace.
    ///
    /// For the panel's own settings, which belong to no vendor: they configure
    /// the admin itself, so they sit under `/settings` with a plain name
    /// (`/settings/branding`) rather than carrying `laterite` through a URL an
    /// operator reads. A module's settings live in the module's namespace.
    pub(crate) fn at(mut self, route: impl Into<String>) -> Self {
        self.route = Some(route.into());
        self
    }

    /// The item's own screen, relative to the admin root, ignoring any `link`.
    ///
    /// Before boot resolves it, this falls back to a path under `/settings`
    /// built from the code's segments rather than the dotted code itself, so
    /// even the fallback is a URL rather than an identifier. See
    /// [`SettingsItem::at`] for why the panel's own settings pin theirs.
    pub(crate) fn route(&self) -> String {
        match &self.route {
            Some(route) => route.clone(),
            None if self.per_operator => format!("/preferences/{}", self.code.replace('.', "/")),
            None => format!("/settings/{}", self.code.replace('.', "/")),
        }
    }

    /// Where this item leads, resolved under the admin mount (`admin_path`): its
    /// `link` target if set, else its own settings screen. Both are authored
    /// relative to the admin root, so this prepends the mount.
    pub fn path(&self, admin_path: &str) -> String {
        match &self.link {
            Some(link) => format!("{admin_path}{link}"),
            None => format!("{admin_path}{}", self.route()),
        }
    }
}

/// Renders the settings index: a prompt to pick a section. The context sidebar
/// itself is resolved by the auth guard and rendered by the shell.
pub(crate) fn index(shell: crate::Shell) -> Response {
    render(SettingsIndexTemplate { shell })
}

/// Renders the edit form for one item, populated from its stored value. The
/// context sidebar (with this item active) comes from the shell.
pub(crate) async fn edit_form(
    state: &AdminState,
    item: &SettingsItem,
    shell: crate::Shell,
    user: &laterite_auth::AuthenticatedUser,
) -> Response {
    let mut stored = match stored_value(state, item, user).await {
        Some(value) => value.unwrap_or_else(|| Value::Object(Map::new())),
        None => return render_error(),
    };
    // Prefill unset fields from config so they show the current effective value
    // rather than opening blank. Display only; nothing is written.
    prefill_from_config(item, &mut stored, &state.app_name);
    render(build(
        item,
        &state.field_types,
        state.overrides.as_ref(),
        None,
        &stored,
        &shell,
    ))
}

/// Persists submitted values as the item's JSON object, then returns to the index.
pub(crate) async fn update(
    state: &AdminState,
    item: &SettingsItem,
    data: HashMap<String, String>,
    shell: crate::Shell,
    session: &crate::session::SessionHandle,
    user: &laterite_auth::AuthenticatedUser,
) -> Response {
    // A field type that refuses its input refuses the save: the screen says so
    // rather than storing a value every later read has to defend against.
    let value = match collect(item, &state.field_types, &data) {
        Ok(value) => value,
        Err(message) => {
            let stored = stored_value(state, item, user)
                .await
                .flatten()
                .unwrap_or(Value::Null);
            return render(build(
                item,
                &state.field_types,
                state.overrides.as_ref(),
                Some(message),
                &stored,
                &shell,
            ));
        }
    };
    let written = if item.per_operator {
        store::set_for(&state.db, user.user.id, &item.code, &value)
            .await
            .is_ok()
    } else {
        store::set(&state.db, &item.code, &value).await.is_ok()
    };
    match written {
        true => {
            // The brand is cached for display; a save to it must invalidate the
            // cache so the next page reflects the new name.
            if item.code == brand::BrandSetting::CODE {
                state.invalidate_brand();
            }
            // The stored value can hold secrets, so the audit records which
            // settings model changed, not the new contents. An operator's own
            // preference is theirs alone and goes unrecorded, like their timezone.
            if !item.per_operator {
                crate::audit::record(
                    state,
                    user,
                    "backend.settings.update",
                    Some("settings"),
                    Some(item.code.as_str()),
                    None,
                    None,
                )
                .await;
            }
            session.push_flash(
                crate::session::FlashLevel::Success,
                if item.per_operator {
                    t!("Preferences saved.")
                } else {
                    t!("Settings saved.")
                },
            );
            // Back to the screen that was saved, not the index. Saving is not
            // leaving: an operator adjusting one setting usually adjusts the
            // next, and being thrown back to the menu loses their place.
            Redirect::to(&item.path(&state.admin_path)).into_response()
        }
        false => render(build(
            item,
            &state.field_types,
            state.overrides.as_ref(),
            Some(t!("Could not save. Please try again.")),
            &value,
            &shell,
        )),
    }
}

/// The item's stored value: the deployment's, or this operator's own for a
/// per-operator item. `None` when the read failed.
async fn stored_value(
    state: &AdminState,
    item: &SettingsItem,
    user: &laterite_auth::AuthenticatedUser,
) -> Option<Option<Value>> {
    if item.per_operator {
        store::get_for(&state.db, user.user.id, &item.code)
            .await
            .ok()
    } else {
        store::get(&state.db, &item.code).await.ok()
    }
}

/// Builds the JSON object to store from the submitted form data, typing each
/// field through its field type.
///
/// The same `to_attr` a descriptor form writes through, so a switch stores a
/// bool, a repeater stores an array of objects, and a module's own field type
/// behaves identically here and on a form. A type that refuses its input refuses
/// the save, naming the field.
fn collect(
    item: &SettingsItem,
    types: &crate::field::FieldRegistry,
    data: &HashMap<String, String>,
) -> Result<Value, Text> {
    let mut object = Map::new();
    for field in &item.fields {
        let Some(field_type) = types.get(&field.field_type) else {
            return Err(t!("This screen uses a field type that is not registered."));
        };
        let opts = field_type
            .resolve_options(&field.options, types)
            .map_err(|_| t!("This screen has a malformed field."))?;
        let submitted = crate::field::SubmittedField::new(&field.name, data);
        // Settings always write every declared key: a settings blob has no
        // previous row to fall back to the way a table column does.
        let value = match field_type.to_attr(&submitted, &opts, Mode::Update) {
            Ok(Some(value)) => attr_to_json(value),
            Ok(None) => Value::String(String::new()),
            Err(_) => return Err(t!("Check the values and try again.")),
        };
        object.insert(field.name.clone(), value);
    }
    Ok(Value::Object(object))
}

/// A stored attribute as the JSON a settings blob holds.
fn attr_to_json(value: laterite_core::AttrValue) -> Value {
    use laterite_core::AttrValue;
    match value {
        AttrValue::Null => Value::String(String::new()),
        AttrValue::Bool(b) => Value::Bool(b),
        AttrValue::Int(i) => Value::from(i),
        AttrValue::Float(f) => Value::from(f),
        AttrValue::Json(j) => j,
        other => Value::String(other.to_text().unwrap_or_default()),
    }
}

/// Builds the context-sidebar groups: items grouped by category and ordered
/// deterministically, with `active_code` (if any) marked. Categories sort by
/// their lowest item `order`, then name; items by `order`, then label. This is
/// the simple-weight stage; relative-anchor ordering with an operator override
/// is a later refinement.
pub(crate) fn sidebar_groups(
    items: &[SettingsItem],
    admin_path: &str,
    active_code: Option<&str>,
    tr: &Translator,
    icons: crate::icons::Icons<'_>,
) -> Vec<CategoryView> {
    // Group by the localized category heading (a shared source localizes identically).
    let mut by_category: HashMap<String, Vec<&SettingsItem>> = HashMap::new();
    for item in items {
        by_category
            .entry(tr.t(&item.category))
            .or_default()
            .push(item);
    }
    let mut groups: Vec<CategoryView> = by_category
        .into_iter()
        .map(|(category, mut items)| {
            // Order by weight, then the label's source for a stable tie-break.
            items.sort_by(|a, b| {
                a.order
                    .cmp(&b.order)
                    .then_with(|| a.label.source().cmp(b.label.source()))
            });
            CategoryView {
                min_order: items.iter().map(|i| i.order).min().unwrap_or(0),
                name: category,
                items: items
                    .iter()
                    .map(|i| ItemView {
                        label: tr.t(&i.label),
                        description: tr.t(&i.description),
                        path: i.path(admin_path),
                        icon: icons.render(i.icon.as_deref()),
                        active: active_code == Some(i.code.as_str()),
                    })
                    .collect(),
            }
        })
        .collect();
    groups.sort_by(|a, b| {
        a.min_order
            .cmp(&b.min_order)
            .then_with(|| a.name.cmp(&b.name))
    });
    groups
}

/// Prefills unset display fields from configuration before the form renders, so
/// a field shows the current effective value rather than opening blank. The
/// brand's application name prefills from the configured `app.name` when no brand
/// setting is saved. This is display only: it writes nothing, so a later config
/// change still propagates (persisting it would freeze the value). It is not a
/// database seeder; that is a separate, deferred capability.
fn prefill_from_config(item: &SettingsItem, stored: &mut Value, app_name: &str) {
    if item.code != brand::BrandSetting::CODE {
        return;
    }
    if let Value::Object(map) = stored {
        let blank = map
            .get("app_name")
            .and_then(Value::as_str)
            .unwrap_or("")
            .trim()
            .is_empty();
        if blank {
            map.insert("app_name".to_string(), Value::String(app_name.to_string()));
        }
    }
}

fn build(
    item: &SettingsItem,
    types: &crate::field::FieldRegistry,
    overrides: &dyn crate::field::OverrideResolver,
    error: Option<Text>,
    stored: &Value,
    shell: &crate::Shell,
) -> SettingsFormTemplate {
    let fields = item
        .fields
        .iter()
        .map(|f| {
            let label = shell.tt(&f.label);
            let control = match types.get(&f.field_type) {
                Some(ft) => {
                    let opts = ft
                        .resolve_options(&f.options, types)
                        .unwrap_or_else(|_| crate::field::ResolvedOptions::none());
                    let value = match stored.get(&f.name) {
                        Some(Value::Array(rows)) => {
                            crate::field::FieldValue::Json(Value::Array(rows.clone()))
                        }
                        Some(Value::String(text)) => {
                            crate::field::FieldValue::Text(ft.to_control(Some(text), &opts))
                        }
                        Some(Value::Null) | None => {
                            crate::field::FieldValue::Text(ft.to_control(None, &opts))
                        }
                        Some(other) => crate::field::FieldValue::Text(
                            ft.to_control(Some(&other.to_string()), &opts),
                        ),
                    };
                    let cx = crate::field::FieldCx {
                        name: &f.name,
                        id: &f.name,
                        label: &label,
                        value: &value,
                        required: false,
                        max_length: crate::form::max_length(&f.rules),
                        opts: &opts,
                        base: &shell.base,
                        i18n: shell.i18n(),
                    };
                    let scope = crate::field::OverrideScope {
                        surface: crate::field::Surface::Field,
                        view_key: &f.field_type,
                        resource: Some(&item.code),
                        field: Some(&f.name),
                    };
                    crate::field::render_field(ft.as_ref(), overrides, &scope, &cx).into_string()
                }
                None => String::new(),
            };
            FieldView {
                label,
                help: f.help.as_ref().map(|h| shell.tt(h)),
                control,
                layout: crate::form::layout_classes(f.span, f.break_row),
                attrs: crate::form::behaviour_attrs(f),
            }
        })
        .collect();
    SettingsFormTemplate {
        title: shell.tt(&item.label),
        description: shell.tt(&item.description),
        hint: item.hint.as_ref().map(|h| shell.tt(h)),
        action: item.path(&shell.base),
        error: error.map(|e| shell.tt(&e)),
        fields,
        leave_off: !item.confirm_leave,
        shell: shell.clone(),
    }
}

/// One category block in the context sidebar. Rendered by the shell.
#[derive(Clone)]
pub(crate) struct CategoryView {
    pub(crate) name: String,
    min_order: i32,
    pub(crate) items: Vec<ItemView>,
}

impl CategoryView {
    /// One group of entries, as a menu section renders in the sidebar.
    pub(crate) fn new(name: String, items: Vec<ItemView>) -> Self {
        Self {
            name,
            min_order: 0,
            items,
        }
    }
}

/// One item in the context sidebar.
#[derive(Clone)]
pub(crate) struct ItemView {
    pub(crate) label: String,
    pub(crate) description: String,
    pub(crate) path: String,
    /// Inline SVG markup for the item's icon, rendered raw in the template.
    pub(crate) icon: String,
    /// Whether this is the item currently open, so the sidebar highlights it.
    pub(crate) active: bool,
}

#[derive(Template)]
#[template(path = "settings_index.html")]
struct SettingsIndexTemplate {
    shell: crate::Shell,
}

struct FieldView {
    label: String,
    help: Option<String>,
    /// The control, rendered by the field's own type.
    control: String,
    /// Wrapper classes for the span and a row break, each led by a space.
    layout: String,
    /// The wrapper's preset and trigger attributes, each led by a space.
    attrs: String,
}

#[derive(Template)]
#[template(path = "settings_form.html")]
struct SettingsFormTemplate {
    shell: crate::Shell,
    title: String,
    description: String,
    /// The item's fuller explanation, localized. Supersedes `description` on
    /// this screen, which is written for a sidebar.
    hint: Option<String>,
    action: String,
    error: Option<String>,
    fields: Vec<FieldView>,
    /// Leaving with changes unsaved does not ask.
    leave_off: bool,
}

#[cfg(test)]
mod field_system_tests {
    use super::*;

    #[test]
    #[should_panic(expected = "over the 72")]
    fn a_lecture_of_a_description_is_refused() {
        // The shape the discovery plugin shipped with: 108 characters, four
        // lines in a 211-pixel sidebar.
        SettingsItem::new("acme.test", "Test", Vec::new()).description(
            "What search engines and other crawlers may visit. The admin panel \
             is always excluded, whatever you put here.",
        );
    }

    #[test]
    fn a_label_sized_description_passes_and_a_hint_carries_the_rest() {
        let item = SettingsItem::new("acme.test", "Test", Vec::new())
            .description("Which crawlers may visit, and what they may not.")
            .hint(
                "The admin panel is always excluded, whatever you put here, and a \
                   crawler obeys only the block that names it.",
            );
        assert!(item.description.source().chars().count() <= MAX_DESCRIPTION);
        // The hint has no ceiling: the reader has opened the screen.
        assert!(item.hint.is_some());
    }

    fn item(fields: Vec<FormField>) -> SettingsItem {
        SettingsItem {
            code: "acme.test".to_string(),
            label: Text::new(""),
            description: Text::new(""),
            category: Text::new(""),
            hint: None,
            confirm_leave: true,
            order: 0,
            icon: None,
            permission: None,
            link: None,
            fields,
            route: None,
            per_operator: false,
        }
    }

    fn submitted(pairs: &[(&str, &str)]) -> HashMap<String, String> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    /// Settings and forms now share one field system, so a settings screen gets
    /// every registered type and stores what that type says it stores.
    #[test]
    fn settings_store_what_the_field_type_says() {
        let cfg = item(vec![
            FormField::text("name", "Name"),
            FormField::switch("enabled", "Enabled"),
            FormField::select("freq", "Frequency", vec![("daily", "Daily")]),
            FormField::date("expires", "Expires"),
        ]);
        let stored = collect(
            &cfg,
            &crate::field::builtin_registry(),
            &submitted(&[
                ("name", "Acme"),
                ("enabled", "on"),
                ("freq", "daily"),
                ("expires", "2026-12-31"),
            ]),
        )
        .unwrap();

        assert_eq!(stored["name"], "Acme");
        // A bool, not the string "on": the switch field type decided that.
        assert_eq!(stored["enabled"], serde_json::json!(true));
        assert_eq!(stored["freq"], "daily");
        assert_eq!(stored["expires"], "2026-12-31");
    }

    /// An unticked switch is absent from the submission and must store false,
    /// or the box could never be cleared.
    #[test]
    fn an_unticked_switch_clears() {
        let cfg = item(vec![FormField::switch("enabled", "Enabled")]);
        let stored = collect(&cfg, &crate::field::builtin_registry(), &submitted(&[])).unwrap();
        assert_eq!(stored["enabled"], serde_json::json!(false));
    }

    /// The repeater works in settings because it is a field type, not a
    /// settings-only widget: this is the whole point of the unification.
    #[test]
    fn a_repeater_works_in_settings() {
        let cfg = item(vec![FormField::repeater(
            "rules",
            "Rules",
            vec![
                FormField::text("path", "Path"),
                FormField::switch("allow", "Allow"),
            ],
        )]);
        let stored = collect(
            &cfg,
            &crate::field::builtin_registry(),
            &submitted(&[
                ("rules[0][path]", "/private"),
                ("rules[1][path]", "/public"),
                ("rules[1][allow]", "on"),
            ]),
        )
        .unwrap();

        let rows = stored["rules"].as_array().unwrap();
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0]["path"], "/private");
        assert_eq!(rows[0]["allow"], serde_json::json!(false));
        assert_eq!(rows[1]["allow"], serde_json::json!(true));
    }

    #[test]
    fn a_screen_naming_an_unregistered_type_refuses_rather_than_rendering_blank() {
        let cfg = item(vec![FormField::of("x", "X", "acme.nope")]);
        assert!(collect(&cfg, &crate::field::builtin_registry(), &submitted(&[])).is_err());
    }

    #[test]
    fn the_form_renders_each_control_through_its_type() {
        let cfg = item(vec![
            FormField::switch("enabled", "Enabled"),
            FormField::repeater("rules", "Rules", vec![FormField::text("path", "Path")]),
        ]);
        let html = build(
            &cfg,
            &crate::field::builtin_registry(),
            &crate::field::NoOverrides,
            None,
            &serde_json::json!({ "enabled": true, "rules": [{ "path": "/a" }] }),
            &crate::Shell::test(),
        )
        .render()
        .unwrap();

        assert!(html.contains(r#"type="checkbox""#));
        assert!(html.contains(r#"name="rules[0][path]""#));
        assert!(html.contains(r#"value="/a""#));
        assert!(html.contains("lat-repeater__blank"));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use laterite_core::Db;

    #[test]
    fn brand_form_prefills_app_name_from_config_when_unset() {
        let brand = brand::settings_item();
        // Unset: the field prefills from the configured application name.
        let mut unset = Value::Object(Map::new());
        prefill_from_config(&brand, &mut unset, "Configured Name");
        assert_eq!(unset["app_name"], serde_json::json!("Configured Name"));
        // Already set: the stored value is left untouched.
        let mut set = serde_json::json!({ "app_name": "Acme" });
        prefill_from_config(&brand, &mut set, "Configured Name");
        assert_eq!(set["app_name"], serde_json::json!("Acme"));
        // A non-brand item is not prefilled.
        let mut other = Value::Object(Map::new());
        prefill_from_config(&item(), &mut other, "Configured Name");
        assert!(other.get("app_name").is_none());
    }

    fn item() -> SettingsItem {
        SettingsItem {
            code: "test.log".to_string(),
            label: "Log Settings".into(),
            description: "What the log records.".into(),
            category: "Logs".into(),
            hint: None,
            confirm_leave: true,
            order: 10,
            icon: None,
            permission: None,
            link: None,
            fields: vec![
                FormField::switch("log_events", "Log events"),
                FormField::switch("log_requests", "Log requests"),
                FormField::text("retention_days", "Retention (days)"),
            ],
            route: None,
            per_operator: false,
        }
    }

    fn state(db: Db) -> AdminState {
        AdminState::new(
            laterite_auth::AuthService::new(db.clone(), laterite_auth::AuthConfig::default()),
            db,
        )
    }

    /// A fresh test database with the settings table migrated in, on whichever
    /// backend the run targets. Hold the returned guard for the test's lifetime.
    async fn test_db() -> (Db, laterite_core::testing::TestGuard) {
        laterite_core::testing::connect_test(&[migrations()]).await
    }

    fn data(pairs: &[(&str, &str)]) -> HashMap<String, String> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    #[test]
    fn group_orders_categories_then_items() {
        let items = vec![
            SettingsItem {
                code: "b".into(),
                label: "Beta".into(),
                description: String::new().into(),
                category: "System".into(),
                hint: None,
                confirm_leave: true,
                order: 20,
                icon: None,
                permission: None,
                link: None,
                fields: vec![],
                route: None,
                per_operator: false,
            },
            SettingsItem {
                code: "a".into(),
                label: "Alpha".into(),
                description: String::new().into(),
                category: "System".into(),
                hint: None,
                confirm_leave: true,
                order: 10,
                icon: None,
                permission: None,
                link: None,
                fields: vec![],
                route: None,
                per_operator: false,
            },
            SettingsItem {
                code: "l".into(),
                label: "Logs".into(),
                description: String::new().into(),
                category: "Logs".into(),
                hint: None,
                confirm_leave: true,
                order: 5,
                icon: None,
                permission: None,
                link: None,
                fields: vec![],
                route: None,
                per_operator: false,
            },
        ];
        let groups = sidebar_groups(
            &items,
            "/admin",
            None,
            &Translator::new("en"),
            crate::icons::Icons::new(&laterite_core::icons::IconSet::new(), "/s.svg"),
        );
        // "Logs" (min order 5) comes before "System" (min order 10).
        assert_eq!(groups[0].name, "Logs");
        assert_eq!(groups[1].name, "System");
        // Within "System", Alpha (10) before Beta (20).
        assert_eq!(groups[1].items[0].label, "Alpha");
        assert_eq!(groups[1].items[1].label, "Beta");
        // Nothing is active when no code is given.
        assert!(groups.iter().flat_map(|g| &g.items).all(|i| !i.active));
    }

    #[test]
    fn group_marks_only_the_active_item() {
        let items = vec![item()];
        let groups = sidebar_groups(
            &items,
            "/admin",
            Some("test.log"),
            &Translator::new("en"),
            crate::icons::Icons::new(&laterite_core::icons::IconSet::new(), "/s.svg"),
        );
        let active: Vec<&str> = groups
            .iter()
            .flat_map(|g| &g.items)
            .filter(|i| i.active)
            .map(|i| i.label.as_str())
            .collect();
        assert_eq!(active, ["Log Settings"]);
    }

    #[test]
    fn settings_model_item_path_is_its_form() {
        // Unresolved (no module namespace yet), the fallback still builds a
        // path from the code's segments rather than using the dotted key.
        assert_eq!(item().path("/admin"), "/admin/settings/test/log");
        // The mount is honoured, so a relocated panel keeps consistent links.
        assert_eq!(item().path("/manage"), "/manage/settings/test/log");

        // Once boot resolves it into the module's namespace, that wins.
        let mut resolved = item();
        resolved.mount_at("/acme/logging/log");
        assert_eq!(resolved.path("/admin"), "/admin/acme/logging/log");
    }

    #[test]
    fn link_item_path_follows_the_link() {
        let admins = crate::builtin_settings()
            .into_iter()
            .find(|i| i.code == "backend.administrators")
            .unwrap();
        assert_eq!(admins.category.source(), "Users");
        assert!(admins.link.is_some());
        assert!(admins.fields.is_empty());
        // links to the resource list, not a settings form
        assert_eq!(admins.path("/admin"), "/admin/users");
        assert!(crate::builtin_settings()
            .iter()
            .any(|i| i.code == "backend.roles"));
    }

    #[tokio::test]
    async fn update_persists_typed_values() {
        let (db, _guard) = test_db().await;
        let st = state(db.clone());

        let it = item();
        let resp = update(
            &st,
            &it,
            // log_requests is absent, as an unchecked checkbox would be.
            data(&[("log_events", "on"), ("retention_days", "30")]),
            crate::Shell::test(),
            &crate::session::SessionHandle::from_blob(None),
            &crate::audit::test_actor(),
        )
        .await;
        assert_eq!(resp.status(), axum::http::StatusCode::SEE_OTHER);

        let stored = store::get(&db, "test.log").await.unwrap().unwrap();
        assert_eq!(stored["log_events"], serde_json::json!(true));
        assert_eq!(stored["log_requests"], serde_json::json!(false));
        assert_eq!(stored["retention_days"], serde_json::json!("30"));
    }

    #[test]
    fn index_renders() {
        let resp = index(crate::Shell::test());
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
    }

    #[tokio::test]
    async fn edit_form_renders_for_unset_item() {
        let (db, _guard) = test_db().await;
        let st = state(db);
        // No stored value yet: the form still renders (fields fall back to defaults).
        let it = item();
        let resp = edit_form(&st, &it, crate::Shell::test(), &crate::audit::test_actor()).await;
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
    }
}