laterite-admin 0.8.2

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
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
//! 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)]
#[serde(deny_unknown_fields, default)]
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,
    /// Help text shown beneath the control, localized at render.
    #[serde(default)]
    pub help: Option<Text>,
}

impl Default for FormConfig {
    /// Everything a descriptor file leaves to the resource level: the entity,
    /// the path and the id column are filled in when the file is read.
    fn default() -> Self {
        Self {
            entity: String::new(),
            title: Text::new(""),
            base_path: String::new(),
            id_field: "id".to_string(),
            fields: Vec::new(),
            persist: None,
            timestamps: false,
        }
    }
}

impl Default for FormField {
    /// A text field, named by the key it is written under.
    fn default() -> Self {
        Self::of("", Text::new(""), "text")
    }
}

impl crate::keyed::Keyed for FormField {
    fn key(&self) -> &str {
        &self.name
    }
    fn set_key(&mut self, key: String) {
        self.name = key;
    }
}

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,
            help: None,
        }
    }

    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 }))
    }

    /// A dropdown over a fixed set of `(value, label)` choices.
    pub fn select(name: &str, label: impl Into<Text>, options: Vec<(&str, &str)>) -> Self {
        Self::of(name, label, "select").options(Self::choices(options))
    }

    /// The same choices rendered as radio buttons.
    pub fn radio(name: &str, label: impl Into<Text>, options: Vec<(&str, &str)>) -> Self {
        Self::of(name, label, "radio").options(Self::choices(options))
    }

    /// A checkbox over a boolean column.
    pub fn switch(name: &str, label: impl Into<Text>) -> Self {
        Self::of(name, label, "switch")
    }

    /// A calendar date, stored as `YYYY-MM-DD`.
    pub fn date(name: &str, label: impl Into<Text>) -> Self {
        Self::of(name, label, "date")
    }

    /// A password: hashed on save, never rendered back, and left alone when the
    /// field is submitted blank on an edit.
    pub fn password(name: &str, label: impl Into<Text>) -> Self {
        Self::of(name, label, "password")
    }

    /// A list of rows, each holding `fields`, stored as an array of objects.
    pub fn repeater(name: &str, label: impl Into<Text>, fields: Vec<FormField>) -> Self {
        Self::of(name, label, "repeater").options(serde_json::json!({ "fields": fields }))
    }

    /// A repeater whose rows collapse to the line that names them, opening one
    /// at a time. `summary_field` names the sub-field that titles a row; unset,
    /// the first one does.
    ///
    /// Use it when a row holds more than one or two fields: rendered inline
    /// those become columns, and a row of four is already unreadable. A single
    /// narrow column is better left inline, where collapsing would hide the one
    /// thing worth seeing.
    pub fn repeater_list(
        name: &str,
        label: impl Into<Text>,
        fields: Vec<FormField>,
        summary_field: Option<&str>,
    ) -> Self {
        Self::of(name, label, "repeater").options(serde_json::json!({
            "fields": fields,
            "display": "list",
            "summary_field": summary_field,
        }))
    }

    /// The options blob the choice-shaped types read.
    fn choices(options: Vec<(&str, &str)>) -> serde_json::Value {
        let options: Vec<serde_json::Value> = options
            .into_iter()
            .map(|(value, label)| serde_json::json!({ "value": value, "label": label }))
            .collect();
        serde_json::json!({ "options": options })
    }

    /// 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
    }

    /// Help text shown beneath the control.
    pub fn help(mut self, text: impl Into<Text>) -> Self {
        self.help = Some(text.into());
        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`).
///
/// Built with [`FormConfig::new`] plus its builder methods. Non-exhaustive so the
/// framework can learn something new about a form after 1.0 without a major bump.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
#[non_exhaustive]
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,
    #[serde(
        deserialize_with = "crate::keyed::deserialize",
        serialize_with = "crate::keyed::serialize"
    )]
    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 {
    /// A form over `entity`, mounted under `base_path`, keyed by `id_field`.
    ///
    /// The four arguments are the ones with no sensible default; everything else
    /// is opt-in through a builder method, so a later field costs nothing.
    pub fn new(
        entity: impl Into<String>,
        title: impl Into<Text>,
        base_path: impl Into<String>,
        id_field: impl Into<String>,
        fields: Vec<FormField>,
    ) -> Self {
        Self {
            entity: entity.into(),
            title: title.into(),
            base_path: base_path.into(),
            id_field: id_field.into(),
            fields,
            persist: None,
            timestamps: false,
        }
    }

    /// Writes this form through a registered persister instead of the built-in
    /// descriptor insert/update.
    pub fn persist(mut self, name: impl Into<String>) -> Self {
        self.persist = Some(name.into());
        self
    }

    /// Stamps `created_at` and `updated_at` on write. Opt in, because the
    /// columns have to exist on this entity's table.
    pub fn timestamps(mut self) -> Self {
        self.timestamps = true;
        self
    }

    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, field_types)
                .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 submitted = crate::field::SubmittedField::new(&field.name, data);
        if let Some(value) = prepared
            .field_type
            .to_attr(&submitted, &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,
    session: &crate::session::SessionHandle,
    headers: &axum::http::HeaderMap,
) -> Response {
    if !form.config.idents_valid() {
        return render_error();
    }
    let htmx = is_htmx(headers);
    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 invalid_response(htmx, state, form, &action, None, &data, &bag, &shell);
    }

    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(()) => {
            session.push_flash(crate::session::FlashLevel::Success, t!("Saved."));
            saved_response(htmx, &form.config.base_path)
        }
        // A persist-time domain check re-renders 422 with its per-field messages.
        Err(SaveError::Invalid(bag)) => {
            invalid_response(htmx, state, form, &action, None, &data, &bag, &shell)
        }
        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.
// The generic handlers thread the request's pieces explicitly rather than through
// a context struct; the list is long but each argument is named at the call site.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn update(
    state: &AdminState,
    form: &PreparedForm,
    id: String,
    data: HashMap<String, String>,
    shell: crate::Shell,
    user: &laterite_auth::AuthenticatedUser,
    session: &crate::session::SessionHandle,
    headers: &axum::http::HeaderMap,
) -> Response {
    if !form.config.idents_valid() {
        return render_error();
    }
    let htmx = is_htmx(headers);
    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 invalid_response(htmx, state, form, &action, None, &data, &bag, &shell);
    }

    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(()) => {
            session.push_flash(crate::session::FlashLevel::Success, t!("Saved."));
            saved_response(htmx, &form.config.base_path)
        }
        Err(SaveError::Invalid(bag)) => {
            invalid_response(htmx, state, form, &action, None, &data, &bag, &shell)
        }
        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,
            ))
        }
    }
}

/// The 422 response for a failed save. An HTMX submit gets the form alone, which
/// replaces the form in place; anything else gets the whole page, so the admin
/// still works with scripting off.
#[allow(clippy::too_many_arguments)]
fn invalid_response(
    htmx: bool,
    state: &AdminState,
    form: &PreparedForm,
    action: &str,
    error: Option<Text>,
    values: &HashMap<String, String>,
    bag: &ErrorBag,
    shell: &crate::Shell,
) -> Response {
    let page = build(state, form, action, error, values, bag, shell);
    let body = if htmx {
        render(FormFragment {
            shell: page.shell,
            action: page.action,
            cancel_path: page.cancel_path,
            error: page.error,
            fields: page.fields,
        })
    } else {
        render(page)
    };
    (StatusCode::UNPROCESSABLE_ENTITY, body).into_response()
}

/// Where to send the browser after a successful save. HTMX will not follow a
/// 303 usefully (it would swap the redirected page into the form), so it gets
/// the header it understands instead.
pub(crate) fn saved_response(htmx: bool, to: &str) -> Response {
    if htmx {
        ([("HX-Redirect", to)], StatusCode::NO_CONTENT).into_response()
    } else {
        Redirect::to(to).into_response()
    }
}

/// Whether this request came from HTMX rather than a plain form post.
pub(crate) fn is_htmx(headers: &axum::http::HeaderMap) -> bool {
    headers.contains_key("hx-request")
}

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,
                i18n: shell.i18n(),
            };
            // 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, &state.asset_urls);
    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>,
}

/// Just the form element, for an HTMX submit that failed validation: the
/// response replaces the form in place rather than reloading the page.
#[derive(Template)]
#[template(path = "_form_fields.html")]
struct FormFragment {
    shell: crate::Shell,
    action: String,
    cancel_path: String,
    error: Option<String>,
    fields: Vec<FieldView>,
}

#[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()
    }

    /// The whole delete path against a real table: the row is read, the
    /// listeners run, the row goes, and the after-stage sees what went.
    #[tokio::test]
    async fn a_delete_removes_the_row_through_the_pipeline() {
        use crate::persist::{delete, DefaultPersister, DeleteRequest};

        let (db, _guard) = test_db().await;
        let st = state(db.clone());
        let form = config();

        let mut data = HashMap::new();
        data.insert("code".to_string(), "c1".to_string());
        data.insert("name".to_string(), "Chair".to_string());
        create(
            &st,
            &form,
            data,
            crate::Shell::test(),
            &crate::audit::test_actor(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .await;
        assert_eq!(
            fetch_text(&db, "name", "c1").await.as_deref(),
            Some("Chair")
        );

        let id = row_id(&db, "c1").await;
        let persister = DefaultPersister::from_config(&form.config);
        let rec = delete(DeleteRequest {
            db: &db,
            listeners: &[],
            persister: &persister,
            actor: &laterite_core::Actor::system("test"),
            entity: "samples",
            id: &id,
        })
        .await
        .expect("deleted");

        // Gone from the table, and the caller learns what it removed.
        assert_eq!(fetch_text(&db, "name", "c1").await, None);
        assert_eq!(rec.text("code"), Some("c1"));
    }

    /// The stored id for a row, as text, the shape the delete path takes.
    async fn row_id(db: &Db, code: &str) -> String {
        let stmt = Query::select()
            .expr_as(
                Expr::col(Alias::new("id")).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) = laterite_core::query::build(db.backend, stmt);
        let row = bind_values(sqlx::query(&sql), values)
            .fetch_one(&db.pool)
            .await
            .unwrap();
        row.get_text("v").unwrap()
    }

    pub(super) 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()
    }

    /// The header htmx sets on every request it makes.
    pub(super) fn htmx_headers() -> axum::http::HeaderMap {
        let mut h = axum::http::HeaderMap::new();
        h.insert("hx-request", "true".parse().unwrap());
        h
    }

    #[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(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .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(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .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(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .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(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .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(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .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(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .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(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .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(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .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(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .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(),
            &crate::session::SessionHandle::from_blob(None),
            &axum::http::HeaderMap::new(),
        )
        .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);
    }
}

#[cfg(test)]
mod htmx_tests {
    use super::tests::*;
    use super::*;
    use axum::http::StatusCode;

    /// A submission missing a required field, so validation refuses it.
    fn invalid() -> HashMap<String, String> {
        let mut d = HashMap::new();
        d.insert("code".to_string(), String::new());
        d.insert("name".to_string(), "No code".to_string());
        d
    }

    fn valid() -> HashMap<String, String> {
        let mut d = HashMap::new();
        d.insert("code".to_string(), "c1".to_string());
        d.insert("name".to_string(), "Chair".to_string());
        d
    }

    async fn post(data: HashMap<String, String>, headers: axum::http::HeaderMap) -> Response {
        let (db, _guard) = test_db().await;
        let st = state(db);
        let form = 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::text("name", "Name").required(),
                ],
                persist: None,
                timestamps: false,
            },
            &st.field_types,
            &PersisterRegistry::new(),
            &[],
        )
        .unwrap();
        create(
            &st,
            &form,
            data,
            crate::Shell::test(),
            &crate::audit::test_actor(),
            &crate::session::SessionHandle::from_blob(None),
            &headers,
        )
        .await
    }

    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()
    }

    #[tokio::test]
    async fn an_htmx_submit_that_fails_returns_the_form_alone() {
        let resp = post(invalid(), htmx_headers()).await;
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let html = body_of(resp).await;
        assert!(html.contains("<form"), "the form comes back");
        assert!(html.contains("lat-field__error"), "with its errors");
        // A fragment, not a page: swapping a whole document into the form would
        // nest the admin inside itself.
        assert!(!html.contains("<body"), "no page chrome");
    }

    #[tokio::test]
    async fn a_plain_submit_that_fails_returns_the_whole_page() {
        let resp = post(invalid(), axum::http::HeaderMap::new()).await;
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let html = body_of(resp).await;
        assert!(html.contains("<body"), "the admin still works without htmx");
        assert!(html.contains("lat-field__error"));
    }

    #[tokio::test]
    async fn an_htmx_submit_that_succeeds_redirects_by_header() {
        let resp = post(valid(), htmx_headers()).await;
        // htmx cannot follow a 303 usefully; it reads this header instead.
        assert_eq!(resp.status(), StatusCode::NO_CONTENT);
        assert_eq!(resp.headers().get("HX-Redirect").unwrap(), "/admin/samples");
    }

    #[tokio::test]
    async fn a_plain_submit_that_succeeds_still_redirects() {
        let resp = post(valid(), axum::http::HeaderMap::new()).await;
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
    }
}