laterite-admin 0.4.0

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
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
//! Descriptor-driven create and edit forms.
//!
//! A [`FormConfig`] describes a table and its editable fields. Generic handlers
//! render an empty form (new), a populated form (edit), and persist through a
//! [`crate::persist::Persister`]: the descriptor-driven default (a parameterized
//! insert/update over the form's columns), or a named handler for a custom write.
//! A submission is checked by the framework validation engine
//! ([`laterite_core::validation`]); a failure re-renders the form with per-field
//! messages instead of writing.
//!
//! Field types resolve through the registry ([`crate::field`]); `text`,
//! `textarea`, `select`, and `reference` ship built-in. Fields needing a typed
//! stored value (a switch over a bool column, password hashing) arrive with the
//! typed-save contract.
//!
//! The primary key is a `bigint` auto-increment column the database assigns, so
//! create inserts only the descriptor's fields and never sets the id. An entity
//! with other required columns that lack defaults (for example audit timestamps)
//! is beyond this slice; those are filled by a later timestamp-aware widget.

use std::collections::HashMap;
use std::sync::Arc;

use askama::Template;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Redirect, Response};
use laterite_core::query::{bind_values, build as to_sql, text_cast};
use laterite_core::validation::{validate, FieldRules, Mode, Rule};
use laterite_core::{
    t, Actor, AnyRowExt, ErrorBag, ModelListener, ModelListenerReg, Op, Record, Text,
};
use sea_query::{Alias, Expr, Query};
use serde::{Deserialize, Serialize};

use crate::field::{render_field, FieldCx, FieldValue, OverrideScope, ResolvedOptions, Surface};
use crate::persist::{self, DefaultPersister, Persister, PersisterRegistry, SaveError};
use crate::sql::valid_ident;
use crate::{not_found, render, render_error, AdminState};

/// One editable field: the column, its label, its field-type key (resolved
/// through the field-type registry), typed options for that type, the validation
/// rules it carries, and whether it holds translatable content. A serde
/// descriptor, so it is authorable as data (later YAML) as well as by builder.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FormField {
    pub name: String,
    /// The field's label, localized at render. Serde stays a plain string.
    pub label: Text,
    /// The field-type registry key (`text`, `textarea`, or a plugin's
    /// `vendor.name`), resolved to behaviour at render time (see [`crate::field`]).
    #[serde(rename = "type")]
    pub field_type: String,
    /// Per-type options, typed by the field type. Absent (null) for scalar types.
    #[serde(default)]
    pub options: serde_json::Value,
    /// Validation rules run on submit (see [`laterite_core::validation`]).
    #[serde(default)]
    pub rules: Vec<Rule>,
    /// Marks a field whose value is translatable content. A reserved seam: the
    /// framework stores the value verbatim; a content-translation plugin reads
    /// the flag to manage per-locale values.
    #[serde(default)]
    pub translatable: bool,
}

impl FormField {
    /// A field of a registered type by key.
    pub fn of(name: &str, label: impl Into<Text>, field_type: &str) -> Self {
        Self {
            name: name.to_string(),
            label: label.into(),
            field_type: field_type.to_string(),
            options: serde_json::Value::Null,
            rules: Vec::new(),
            translatable: false,
        }
    }

    pub fn text(name: &str, label: impl Into<Text>) -> Self {
        Self::of(name, label, "text")
    }

    pub fn textarea(name: &str, label: impl Into<Text>) -> Self {
        Self::of(name, label, "textarea")
    }

    /// A reference field: a picker over a registered picker source (a `vendor.name`
    /// key), which the field searches and resolves against. Builds the `source`
    /// option so a descriptor needs no raw JSON.
    pub fn reference(name: &str, label: impl Into<Text>, source: &str) -> Self {
        Self::of(name, label, "reference").options(serde_json::json!({ "source": source }))
    }

    /// Sets the field type's typed options (the type validates them at render).
    pub fn options(mut self, options: serde_json::Value) -> Self {
        self.options = options;
        self
    }

    /// Requires a non-empty value in every mode.
    pub fn required(mut self) -> Self {
        self.rules.push(Rule::Required);
        self
    }

    /// Requires a non-empty value in one mode only (for example a password set on
    /// create but left unchanged on edit).
    pub fn required_on(mut self, mode: Mode) -> Self {
        self.rules.push(Rule::RequiredOn(mode));
        self
    }

    /// Requires the value to be unique in this field's column (a DB probe that
    /// ignores the edited row on update).
    pub fn unique(mut self) -> Self {
        self.rules.push(Rule::Unique);
        self
    }

    /// Caps the value's length.
    pub fn max_length(mut self, n: usize) -> Self {
        self.rules.push(Rule::MaxLength(n));
        self
    }

    /// Requires at least `n` characters when the value is non-empty.
    pub fn min_length(mut self, n: usize) -> Self {
        self.rules.push(Rule::MinLength(n));
        self
    }

    /// Requires a syntactically valid email address.
    pub fn email(mut self) -> Self {
        self.rules.push(Rule::Email);
        self
    }

    /// Marks this field as translatable content (see [`FormField::translatable`]).
    pub fn translatable(mut self) -> Self {
        self.translatable = true;
        self
    }
}

/// A form descriptor: which table, its editable fields, the id column, and the
/// base path the form lives under (`{base_path}/new`, `{base_path}/{id}/edit`).
#[derive(Debug, Clone, Serialize)]
pub struct FormConfig {
    pub entity: String,
    /// The screen title, localized at render. Serde stays a plain string.
    pub title: Text,
    pub base_path: String,
    pub id_field: String,
    pub fields: Vec<FormField>,
    /// The registered persister that writes this form (a dotted `vendor.name`),
    /// or `None` for the built-in descriptor insert/update. See [`crate::persist`].
    pub persist: Option<String>,
    /// Stamp `created_at` and `updated_at` on write. Opt in per form, because
    /// the columns have to exist on this entity's table.
    #[serde(default)]
    pub timestamps: bool,
}

impl FormConfig {
    fn idents_valid(&self) -> bool {
        valid_ident(&self.entity)
            && valid_ident(&self.id_field)
            && self.fields.iter().all(|f| valid_ident(&f.name))
    }
}

/// A [`FormConfig`] with each field's options resolved once, at router build.
/// Handlers carry this so option resolution and intrinsic-rule merging happen a
/// single time (not per render), and a malformed option or unregistered type
/// aborts boot rather than degrading silently to plain text.
pub(crate) struct PreparedForm {
    config: FormConfig,
    /// Parallel to `config.fields`.
    fields: Vec<PreparedField>,
    /// The write handler: the named persister, or the built-in default.
    persister: Arc<dyn Persister>,
    /// Listeners for this form's entity, in registration order.
    listeners: Vec<Arc<dyn ModelListener>>,
}

/// One field's boot-resolved state: its typed options and its merged rules (the
/// type's intrinsic rules ahead of the descriptor's own).
struct PreparedField {
    /// Resolved once at boot, so the save and load hooks need no lookup.
    field_type: Arc<dyn crate::field::FieldType>,
    opts: ResolvedOptions,
    rules: Vec<Rule>,
}

impl PreparedForm {
    /// Resolves every field against the registry. Returns the offending field
    /// and reason (for a boot abort) when a type is unregistered or rejects its
    /// options.
    pub(crate) fn prepare(
        config: FormConfig,
        field_types: &crate::field::FieldRegistry,
        persisters: &PersisterRegistry,
        listeners: &[ModelListenerReg],
    ) -> Result<Self, String> {
        let mut fields = Vec::with_capacity(config.fields.len());
        for f in &config.fields {
            let ft = field_types.get(&f.field_type).ok_or_else(|| {
                format!(
                    "field `{}` uses unregistered type `{}`",
                    f.name, f.field_type
                )
            })?;
            let opts = ft
                .resolve_options(&f.options)
                .map_err(|e| format!("field `{}` (`{}`): {e}", f.name, f.field_type))?;
            let mut rules = ft.intrinsic_rules(&opts);
            rules.extend(f.rules.clone());
            fields.push(PreparedField {
                field_type: ft.clone(),
                opts,
                rules,
            });
        }
        let persister: Arc<dyn Persister> = match &config.persist {
            Some(key) => persisters
                .get(key)
                .cloned()
                .ok_or_else(|| format!("form names unregistered persister `{key}`"))?,
            None => Arc::new(DefaultPersister::from_config(&config)),
        };
        // The framework's own listeners run first, so a contributed one can see
        // or override what they set.
        let mut resolved: Vec<Arc<dyn ModelListener>> = Vec::new();
        if config.timestamps {
            resolved.push(Arc::new(laterite_core::Timestamps));
        }
        resolved.extend(
            listeners
                .iter()
                .filter(|reg| reg.matches(&config.entity))
                .map(|reg| reg.listener.clone()),
        );
        let listeners = resolved;
        Ok(Self {
            config,
            fields,
            persister,
            listeners,
        })
    }
}

/// The submission as a record, carrying only the fields the descriptor declares.
/// A request cannot introduce an attribute this way, so the persister may widen
/// its write to whatever the record holds; only registered listeners add keys.
///
/// Each value passes through its field type, which decides what gets stored and
/// may leave the attribute out entirely (a blank password on an edit).
fn declared_record(
    form: &PreparedForm,
    data: &HashMap<String, String>,
    mode: Mode,
) -> Result<Record, String> {
    let mut rec = Record::new(&form.config.entity);
    for (field, prepared) in form.config.fields.iter().zip(&form.fields) {
        let raw = data.get(&field.name).map(String::as_str);
        if let Some(value) = prepared.field_type.to_attr(raw, &prepared.opts, mode)? {
            rec.set(field.name.clone(), value);
        }
    }
    Ok(rec)
}

/// The merged validation rules for every field, in order.
fn merged_field_rules(form: &PreparedForm) -> Vec<FieldRules> {
    form.config
        .fields
        .iter()
        .zip(&form.fields)
        // The rules carry the label's source string; the validation message re-wraps
        // it as a nested Text, so it localizes at render like any other label.
        .map(|(f, pf)| FieldRules::new(f.name.clone(), f.label.source(), pf.rules.clone()))
        .collect()
}

/// Whether any rule marks the field required.
fn has_required(rules: &[Rule]) -> bool {
    rules
        .iter()
        .any(|r| matches!(r, Rule::Required | Rule::RequiredOn(_)))
}

/// Renders an empty create form.
pub(crate) fn new_form(state: &AdminState, form: &PreparedForm, shell: crate::Shell) -> Response {
    render(build(
        state,
        form,
        &format!("{}/new", form.config.base_path),
        None,
        &HashMap::new(),
        &ErrorBag::default(),
        &shell,
    ))
}

/// Persists a new record, then redirects to the list. Re-renders with per-field
/// errors when validation fails.
pub(crate) async fn create(
    state: &AdminState,
    form: &PreparedForm,
    data: HashMap<String, String>,
    shell: crate::Shell,
    user: &laterite_auth::AuthenticatedUser,
) -> Response {
    if !form.config.idents_valid() {
        return render_error();
    }
    let action = format!("{}/new", form.config.base_path);

    let bag = match validate(
        &state.db,
        &form.config.entity,
        &form.config.id_field,
        &merged_field_rules(form),
        &data,
        Mode::Create,
        None,
    )
    .await
    {
        Ok(bag) => bag,
        Err(_) => return render_error(),
    };
    if !bag.is_empty() {
        // A failed submission re-renders the form with per-field errors as 422,
        // the cross-surface "validation failure" status.
        return (
            StatusCode::UNPROCESSABLE_ENTITY,
            render(build(state, form, &action, None, &data, &bag, &shell)),
        )
            .into_response();
    }

    let mut rec = match declared_record(form, &data, Mode::Create) {
        Ok(rec) => rec,
        Err(e) => {
            tracing::error!(entity = %form.config.entity, error = %e, "preparing the write failed");
            return render_error();
        }
    };
    let actor = Actor::from(user);
    match persist::save(
        persist::SaveRequest {
            db: &state.db,
            listeners: &form.listeners,
            persister: form.persister.as_ref(),
            actor: &actor,
            op: Op::Create,
            id: None,
        },
        &mut rec,
    )
    .await
    {
        // The audit entry is written by the framework's audit listener, which
        // runs on every entity after the commit.
        Ok(()) => Redirect::to(&form.config.base_path).into_response(),
        // A persist-time domain check re-renders 422 with its per-field messages.
        Err(SaveError::Invalid(bag)) => (
            StatusCode::UNPROCESSABLE_ENTITY,
            render(build(state, form, &action, None, &data, &bag, &shell)),
        )
            .into_response(),
        Err(SaveError::Failed(msg)) => {
            tracing::error!(error = %msg, "admin create failed");
            render(build(
                state,
                form,
                &action,
                Some(t!("Could not save. Check the values and try again.")),
                &data,
                &ErrorBag::default(),
                &shell,
            ))
        }
    }
}

/// Renders a form populated with an existing record.
pub(crate) async fn edit_form(
    state: &AdminState,
    form: &PreparedForm,
    id: String,
    shell: crate::Shell,
) -> Response {
    if !form.config.idents_valid() {
        return render_error();
    }
    // Scope the sea-query builder so it is dropped before the await below: its
    // identifiers are reference-counted (not `Send`), and a live builder across
    // the await would make this handler's future non-`Send`.
    let (sql, values) = {
        let cast = text_cast(state.db.backend);
        let mut select = Query::select();
        for field in &form.config.fields {
            select.expr_as(
                Expr::col(Alias::new(&field.name)).cast_as(Alias::new(cast)),
                Alias::new(&field.name),
            );
        }
        select.from(Alias::new(&form.config.entity)).and_where(
            Expr::col(Alias::new(&form.config.id_field))
                .cast_as(Alias::new(cast))
                .eq(id.clone()),
        );
        to_sql(state.db.backend, select)
    };
    let row = match bind_values(sqlx::query(&sql), values)
        .fetch_optional(&state.db.pool)
        .await
    {
        Ok(row) => row,
        Err(_) => return render_error(),
    };
    let Some(row) = row else {
        return not_found();
    };

    // Each stored value goes back through its field type: what a column holds and
    // what its control shows are not always the same string.
    let values = form
        .config
        .fields
        .iter()
        .zip(&form.fields)
        .map(|(f, prepared)| {
            let stored = row.get_text_opt(f.name.as_str()).ok().flatten();
            let value = prepared
                .field_type
                .to_control(stored.as_deref(), &prepared.opts);
            (f.name.clone(), value)
        })
        .collect();

    render(build(
        state,
        form,
        &format!("{}/{}/edit", form.config.base_path, id),
        None,
        &values,
        &ErrorBag::default(),
        &shell,
    ))
}

/// Persists an edited record, then redirects to the list. Re-renders with
/// per-field errors when validation fails.
pub(crate) async fn update(
    state: &AdminState,
    form: &PreparedForm,
    id: String,
    data: HashMap<String, String>,
    shell: crate::Shell,
    user: &laterite_auth::AuthenticatedUser,
) -> Response {
    if !form.config.idents_valid() {
        return render_error();
    }
    let action = format!("{}/{}/edit", form.config.base_path, id);

    let bag = match validate(
        &state.db,
        &form.config.entity,
        &form.config.id_field,
        &merged_field_rules(form),
        &data,
        Mode::Update,
        Some(&id),
    )
    .await
    {
        Ok(bag) => bag,
        Err(_) => return render_error(),
    };
    if !bag.is_empty() {
        // A failed submission re-renders the form with per-field errors as 422,
        // the cross-surface "validation failure" status.
        return (
            StatusCode::UNPROCESSABLE_ENTITY,
            render(build(state, form, &action, None, &data, &bag, &shell)),
        )
            .into_response();
    }

    let mut rec = match declared_record(form, &data, Mode::Update) {
        Ok(rec) => rec,
        Err(e) => {
            tracing::error!(entity = %form.config.entity, error = %e, "preparing the write failed");
            return render_error();
        }
    };
    if let Ok(n) = id.parse::<i64>() {
        rec.set_id(n);
    }
    let actor = Actor::from(user);
    match persist::save(
        persist::SaveRequest {
            db: &state.db,
            listeners: &form.listeners,
            persister: form.persister.as_ref(),
            actor: &actor,
            op: Op::Update,
            id: Some(&id),
        },
        &mut rec,
    )
    .await
    {
        Ok(()) => Redirect::to(&form.config.base_path).into_response(),
        Err(SaveError::Invalid(bag)) => (
            StatusCode::UNPROCESSABLE_ENTITY,
            render(build(state, form, &action, None, &data, &bag, &shell)),
        )
            .into_response(),
        Err(SaveError::Failed(msg)) => {
            tracing::error!(error = %msg, "admin update failed");
            render(build(
                state,
                form,
                &action,
                Some(t!("Could not save. Check the values and try again.")),
                &data,
                &ErrorBag::default(),
                &shell,
            ))
        }
    }
}

fn build(
    state: &AdminState,
    form: &PreparedForm,
    action: &str,
    error: Option<Text>,
    values: &HashMap<String, String>,
    bag: &ErrorBag,
    shell: &crate::Shell,
) -> FormTemplate {
    let fields = form
        .config
        .fields
        .iter()
        .zip(&form.fields)
        .map(|(f, pf)| {
            let value = FieldValue::Text(values.get(&f.name).cloned().unwrap_or_default());
            let required = has_required(&pf.rules);
            // Localize the label once: the field type sees it (aria/inline labels)
            // and the framework chrome renders it.
            let label = shell.tt(&f.label);
            let cx = FieldCx {
                name: &f.name,
                id: &f.name,
                label: &label,
                value: &value,
                required,
                opts: &pf.opts,
                base: &shell.base,
            };
            // The type is registered (prepare validated it); the lookup here is
            // only to render.
            let control = match state.field_types.get(&f.field_type) {
                Some(ft) => {
                    let scope = OverrideScope {
                        surface: Surface::Field,
                        view_key: &f.field_type,
                        resource: Some(&form.config.base_path),
                        field: Some(&f.name),
                    };
                    render_field(ft.as_ref(), state.overrides.as_ref(), &scope, &cx).into_string()
                }
                None => String::new(),
            };
            FieldView {
                id: f.name.clone(),
                label,
                control,
                required,
                // Localize each per-field message through the request translator.
                errors: bag.messages(&f.name).iter().map(|m| shell.tt(m)).collect(),
            }
        })
        .collect();
    // Collect the widget assets the rendered field types declare, deduped and
    // resolved to URLs for the head. Most declare none (their widgets ship in
    // core laterite.js).
    let keys: Vec<&str> = form
        .config
        .fields
        .iter()
        .zip(&form.fields)
        .filter_map(|(f, pf)| {
            state
                .field_types
                .get(&f.field_type)
                .map(|ft| ft.assets(&pf.opts))
        })
        .flatten()
        .collect();
    // Localize the title and banner before the shell is moved into the template.
    let shell_title = shell.tt(&form.config.title);
    let error = error.map(|m| shell.tt(&m));
    let mut shell = shell.clone();
    shell.assets = crate::page_assets(&keys, &shell.base, &state.assets);
    FormTemplate {
        shell,
        title: shell_title,
        action: action.to_string(),
        cancel_path: form.config.base_path.clone(),
        error,
        fields,
    }
}

struct FieldView {
    /// DOM id for the control and its label's `for`.
    id: String,
    label: String,
    /// The control HTML, rendered by the field-type registry (override-aware).
    /// The framework owns the surrounding chrome (label, required marker, errors).
    control: String,
    required: bool,
    errors: Vec<String>,
}

#[derive(Template)]
#[template(path = "form.html")]
struct FormTemplate {
    shell: crate::Shell,
    title: String,
    action: String,
    cancel_path: String,
    error: Option<String>,
    fields: Vec<FieldView>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::StatusCode;
    use laterite_core::strata::{
        async_trait, ColumnDef, CoreResult, Migration, MigrationSet, Schema, Table,
    };
    use laterite_core::testing::{connect_test, TestGuard};
    use laterite_core::Db;
    use laterite_core::SaveCx;

    /// A minimal table for exercising the generic insert/update path in isolation,
    /// defined as a portable migration so the test runs on any backend.
    struct CreateSamples;
    #[async_trait(?Send)]
    impl Migration for CreateSamples {
        fn name(&self) -> &str {
            "0001_create_samples"
        }
        async fn up(&self, s: &mut Schema<'_>) -> CoreResult<()> {
            s.exec(
                Table::create()
                    .table(Alias::new("samples"))
                    .if_not_exists()
                    .col(
                        ColumnDef::new(Alias::new("id"))
                            .big_integer()
                            .not_null()
                            .auto_increment()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(Alias::new("code")).text().not_null())
                    .col(ColumnDef::new(Alias::new("name")).text().not_null())
                    // Nullable, so a form that does not opt into timestamps
                    // still inserts.
                    .col(ColumnDef::new(Alias::new("created_at")).text())
                    .col(ColumnDef::new(Alias::new("updated_at")).text())
                    .to_owned(),
            )
            .await
        }
    }

    fn config() -> PreparedForm {
        let config = FormConfig {
            entity: "samples".to_string(),
            title: "Sample".into(),
            base_path: "/admin/samples".to_string(),
            id_field: "id".to_string(),
            fields: vec![
                FormField::text("code", "Code").required().unique(),
                FormField::text("name", "Name").required(),
            ],
            persist: None,
            timestamps: false,
        };
        PreparedForm::prepare(
            config,
            &crate::field::builtin_registry(),
            &PersisterRegistry::new(),
            &[],
        )
        .unwrap()
    }

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

    /// A fresh test database holding a minimal `samples` table, on whichever
    /// backend the run targets. Hold the returned guard for the test's lifetime.
    pub(super) async fn test_db() -> (Db, TestGuard) {
        let samples = MigrationSet::new("test.samples", vec![Box::new(CreateSamples)]);
        connect_test(&[samples]).await
    }

    /// Reads a single text column from the one row matching `code`, so a test can
    /// assert what was persisted without depending on the read path under test.
    pub(super) async fn fetch_text(db: &Db, column: &str, code: &str) -> Option<String> {
        let stmt = Query::select()
            .expr_as(
                Expr::col(Alias::new(column)).cast_as(Alias::new(text_cast(db.backend))),
                Alias::new("v"),
            )
            .from(Alias::new("samples"))
            .and_where(Expr::col(Alias::new("code")).eq(code))
            .to_owned();
        let (sql, values) = to_sql(db.backend, stmt);
        let row = bind_values(sqlx::query(&sql), values)
            .fetch_optional(&db.pool)
            .await
            .unwrap()?;
        row.get_text_opt("v").ok().flatten()
    }

    async fn body_of(resp: Response) -> String {
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        String::from_utf8(bytes.to_vec()).unwrap()
    }

    async fn count(db: &Db) -> i64 {
        sqlx::query_scalar("select count(*) from samples")
            .fetch_one(&db.pool)
            .await
            .unwrap()
    }

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

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

        let resp = create(
            &st,
            &cfg,
            data(&[("code", "editor"), ("name", "Content Editor")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);

        assert_eq!(
            fetch_text(&db, "name", "editor").await.as_deref(),
            Some("Content Editor")
        );
    }

    #[tokio::test]
    async fn update_changes_the_row() {
        let (db, _guard) = test_db().await;
        let cfg = config();
        let st = state(db.clone());
        create(
            &st,
            &cfg,
            data(&[("code", "editor"), ("name", "Editor")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
        )
        .await;

        let id = fetch_text(&db, "id", "editor")
            .await
            .expect("row should exist after create");

        // The code is unchanged, so its unique rule must ignore the edited row.
        let resp = update(
            &st,
            &cfg,
            id,
            data(&[("code", "editor"), ("name", "Senior Editor")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);

        assert_eq!(
            fetch_text(&db, "name", "editor").await.as_deref(),
            Some("Senior Editor")
        );
    }

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

        let resp = create(
            &st,
            &cfg,
            data(&[("code", ""), ("name", "No Code")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
        )
        .await;
        // Re-renders the form (200), does not redirect.
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        assert_eq!(count(&db).await, 0);
        // The per-field message is rendered.
        assert!(body_of(resp).await.contains("Code is required."));
    }

    #[tokio::test]
    async fn create_rejects_a_duplicate_unique_value() {
        let (db, _guard) = test_db().await;
        let cfg = config();
        let st = state(db.clone());
        create(
            &st,
            &cfg,
            data(&[("code", "editor"), ("name", "Editor")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
        )
        .await;

        // A second row with the same code is refused by the unique rule.
        let resp = create(
            &st,
            &cfg,
            data(&[("code", "editor"), ("name", "Other")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        assert_eq!(count(&db).await, 1);
        assert!(body_of(resp).await.contains("already taken"));
    }

    #[tokio::test]
    async fn text_email_input_rejects_a_bad_address_via_its_intrinsic_rule() {
        let (db, _guard) = test_db().await;
        let st = state(db.clone());
        // The `name` column is a text field with the `email` input, which
        // contributes Rule::Email without the descriptor listing it.
        let cfg = PreparedForm::prepare(
            FormConfig {
                entity: "samples".to_string(),
                title: "Sample".into(),
                base_path: "/admin/samples".to_string(),
                id_field: "id".to_string(),
                fields: vec![
                    FormField::text("code", "Code").required(),
                    FormField::of("name", "Email", "text")
                        .options(serde_json::json!({ "input": "email" }))
                        .required(),
                ],
                persist: None,
                timestamps: false,
            },
            &st.field_types,
            &PersisterRegistry::new(),
            &[],
        )
        .unwrap();

        let resp = create(
            &st,
            &cfg,
            data(&[("code", "c1"), ("name", "nope")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        assert_eq!(count(&db).await, 0);

        let resp = create(
            &st,
            &cfg,
            data(&[("code", "c1"), ("name", "a@b.test")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        assert_eq!(count(&db).await, 1);
    }

    #[test]
    fn prepare_rejects_an_unregistered_field_type() {
        let config = FormConfig {
            entity: "samples".to_string(),
            title: "Sample".into(),
            base_path: "/admin/samples".to_string(),
            id_field: "id".to_string(),
            fields: vec![FormField::of("place", "Place", "no.such.type")],
            persist: None,
            timestamps: false,
        };
        let Err(err) = PreparedForm::prepare(
            config,
            &crate::field::builtin_registry(),
            &PersisterRegistry::new(),
            &[],
        ) else {
            panic!("expected prepare to reject an unregistered type");
        };
        assert!(err.contains("no.such.type"), "{err}");
    }

    #[test]
    fn prepare_rejects_a_malformed_option() {
        // The text field's `input` option is a string; a wrong JSON type for it
        // aborts prepare naming the field.
        let config = FormConfig {
            entity: "samples".to_string(),
            title: "Sample".into(),
            base_path: "/admin/samples".to_string(),
            id_field: "id".to_string(),
            fields: vec![
                FormField::of("email", "Email", "text").options(serde_json::json!({ "input": 7 }))
            ],
            persist: None,
            timestamps: false,
        };
        let Err(err) = PreparedForm::prepare(
            config,
            &crate::field::builtin_registry(),
            &PersisterRegistry::new(),
            &[],
        ) else {
            panic!("expected prepare to reject a malformed option");
        };
        assert!(err.contains("`email`"), "{err}");
    }

    /// A persister that inserts a row then fails. The pipeline owns the
    /// transaction, so the insert must roll back with it.
    struct RollbackPersister;
    #[laterite_core::strata::async_trait]
    impl Persister for RollbackPersister {
        async fn create(&self, cx: &mut SaveCx<'_>, _rec: &Record) -> Result<i64, SaveError> {
            let backend = cx.backend();
            let insert = Query::insert()
                .into_table(Alias::new("samples"))
                .columns([Alias::new("code"), Alias::new("name")])
                .values_panic(["rolled".into(), "back".into()])
                .to_owned();
            let (sql, values) = to_sql(backend, insert);
            bind_values(sqlx::query(&sql), values)
                .execute(cx.conn())
                .await
                .map_err(|e| SaveError::Failed(e.to_string()))?;
            Err(SaveError::Failed("deliberate".to_string()))
        }
        async fn update(
            &self,
            _cx: &mut SaveCx<'_>,
            _id: &str,
            _rec: &Record,
        ) -> Result<(), SaveError> {
            Ok(())
        }
    }

    /// A persister that always rejects create with a per-field validation error.
    struct RejectingPersister;
    #[laterite_core::strata::async_trait]
    impl Persister for RejectingPersister {
        async fn create(&self, _cx: &mut SaveCx<'_>, _rec: &Record) -> Result<i64, SaveError> {
            let mut bag = ErrorBag::default();
            bag.add("code", t!("Code is not allowed here."));
            Err(SaveError::Invalid(bag))
        }
        async fn update(
            &self,
            _cx: &mut SaveCx<'_>,
            _id: &str,
            _rec: &Record,
        ) -> Result<(), SaveError> {
            Ok(())
        }
    }

    fn config_with(persister: &str) -> FormConfig {
        FormConfig {
            entity: "samples".to_string(),
            title: "Sample".into(),
            base_path: "/admin/samples".to_string(),
            id_field: "id".to_string(),
            fields: vec![
                FormField::text("code", "Code").required(),
                FormField::text("name", "Name").required(),
            ],
            persist: Some(persister.to_string()),
            timestamps: false,
        }
    }

    #[test]
    fn prepare_rejects_an_unregistered_persister() {
        let Err(err) = PreparedForm::prepare(
            config_with("no.such.persister"),
            &crate::field::builtin_registry(),
            &PersisterRegistry::new(),
            &[],
        ) else {
            panic!("expected prepare to reject an unregistered persister");
        };
        assert!(err.contains("no.such.persister"), "{err}");
    }

    #[tokio::test]
    async fn a_persister_transaction_rolls_back_on_error() {
        let (db, _guard) = test_db().await;
        let st = state(db.clone());
        let mut persisters = PersisterRegistry::new();
        persisters.insert("test.rollback".to_string(), Arc::new(RollbackPersister));
        let form = PreparedForm::prepare(
            config_with("test.rollback"),
            &st.field_types,
            &persisters,
            &[],
        )
        .unwrap();

        let resp = create(
            &st,
            &form,
            data(&[("code", "rolled"), ("name", "back")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
        )
        .await;
        // The persister failed, so the form re-renders (200) and its in-tx insert
        // rolled back: no row landed.
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(count(&db).await, 0);
    }

    #[tokio::test]
    async fn a_persister_invalid_error_re_renders_422() {
        let (db, _guard) = test_db().await;
        let st = state(db.clone());
        let mut persisters = PersisterRegistry::new();
        persisters.insert("test.reject".to_string(), Arc::new(RejectingPersister));
        let form = PreparedForm::prepare(
            config_with("test.reject"),
            &st.field_types,
            &persisters,
            &[],
        )
        .unwrap();

        let resp = create(
            &st,
            &form,
            data(&[("code", "editor"), ("name", "Editor")]),
            crate::Shell::test(),
            &crate::audit::test_actor(),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        assert!(body_of(resp).await.contains("Code is not allowed here."));
    }
}

#[cfg(test)]
mod timestamp_tests {
    use super::tests::*;
    use super::*;
    use laterite_core::listeners::{CREATED_AT, UPDATED_AT};
    use laterite_core::Actor;

    fn timestamped(on: bool) -> FormConfig {
        FormConfig {
            entity: "samples".to_string(),
            title: "Sample".into(),
            base_path: "/admin/samples".to_string(),
            id_field: "id".to_string(),
            fields: vec![
                FormField::text("code", "Code").required(),
                FormField::text("name", "Name").required(),
            ],
            persist: None,
            timestamps: on,
        }
    }

    async fn create_through_pipeline(db: &laterite_core::Db, on: bool) -> Record {
        let form = PreparedForm::prepare(
            timestamped(on),
            &crate::field::builtin_registry(),
            &PersisterRegistry::new(),
            &[],
        )
        .unwrap();
        let mut data = HashMap::new();
        data.insert("code".to_string(), "c1".to_string());
        data.insert("name".to_string(), "Chair".to_string());
        let mut rec = declared_record(&form, &data, Mode::Create).unwrap();
        let actor = Actor::system("test");
        persist::save(
            persist::SaveRequest {
                db,
                listeners: &form.listeners,
                persister: form.persister.as_ref(),
                actor: &actor,
                op: Op::Create,
                id: None,
            },
            &mut rec,
        )
        .await
        .expect("the insert should succeed");
        rec
    }

    #[tokio::test]
    async fn opting_in_stamps_the_row() {
        let (db, _guard) = test_db().await;
        let rec = create_through_pipeline(&db, true).await;
        assert!(rec.datetime(CREATED_AT).is_some());
        assert!(rec.datetime(UPDATED_AT).is_some());
        // The stamp reached the table, not just the record.
        assert!(fetch_text(&db, CREATED_AT, "c1").await.is_some());
    }

    #[tokio::test]
    async fn leaving_it_off_writes_no_timestamps() {
        let (db, _guard) = test_db().await;
        let rec = create_through_pipeline(&db, false).await;
        assert!(rec.get(CREATED_AT).is_none());
        assert_eq!(fetch_text(&db, CREATED_AT, "c1").await, None);
    }
}