Skip to main content

laterite_admin/
form.rs

1//! Descriptor-driven create and edit forms.
2//!
3//! A [`FormConfig`] describes a table and its editable fields. Generic handlers
4//! render an empty form (new), a populated form (edit), and persist through a
5//! [`crate::persist::Persister`]: the descriptor-driven default (a parameterized
6//! insert/update over the form's columns), or a named handler for a custom write.
7//! A submission is checked by the framework validation engine
8//! ([`laterite_core::validation`]); a failure re-renders the form with per-field
9//! messages instead of writing.
10//!
11//! Field types resolve through the registry ([`crate::field`]); `text`,
12//! `textarea`, `select`, and `reference` ship built-in. Fields needing a typed
13//! stored value (a switch over a bool column, password hashing) arrive with the
14//! typed-save contract.
15//!
16//! The primary key is a `bigint` auto-increment column the database assigns, so
17//! create inserts only the descriptor's fields and never sets the id. An entity
18//! with other required columns that lack defaults (for example audit timestamps)
19//! is beyond this slice; those are filled by a later timestamp-aware widget.
20
21use std::collections::HashMap;
22use std::sync::Arc;
23
24use askama::Template;
25use axum::http::StatusCode;
26use axum::response::{IntoResponse, Redirect, Response};
27use laterite_core::query::{bind_values, build as to_sql, text_cast};
28use laterite_core::validation::{validate, FieldRules, Mode, Rule};
29use laterite_core::{
30    t, Actor, AnyRowExt, Db, ErrorBag, ModelListener, ModelListenerReg, Op, Record, Text,
31};
32use sea_query::{Alias, Expr, Query};
33use serde::{Deserialize, Serialize};
34
35use crate::field::{render_field, FieldCx, FieldValue, OverrideScope, ResolvedOptions, Surface};
36use crate::persist::{self, DefaultPersister, Persister, PersisterRegistry, SaveError};
37use crate::sql::valid_ident;
38use crate::{not_found, render, render_error, AdminState};
39
40/// One editable field: the column, its label, its field-type key (resolved
41/// through the field-type registry), typed options for that type, the validation
42/// rules it carries, and whether it holds translatable content. A serde
43/// descriptor, so it is authorable as data (later YAML) as well as by builder.
44#[derive(Debug, Clone)]
45#[non_exhaustive]
46pub struct FormField {
47    pub name: String,
48    /// The field's label, localized at render. Serde stays a plain string.
49    pub label: Text,
50    /// The field-type registry key (`text`, `textarea`, or a plugin's
51    /// `vendor.name`), resolved to behaviour at render time (see [`crate::field`]).
52    pub field_type: String,
53    /// The keys that belong to the field's type, as an object: in a file they
54    /// are written on the field itself, beside its own. Null when there are none.
55    pub options: serde_json::Value,
56    /// Validation rules run on submit (see [`laterite_core::validation`]).
57    pub rules: Vec<Rule>,
58    /// Marks a field whose value is translatable content. A reserved seam: the
59    /// framework stores the value verbatim; a content-translation plugin reads
60    /// the flag to manage per-locale values.
61    pub translatable: bool,
62    /// Help text shown beneath the control, localized at render.
63    pub help: Option<Text>,
64    /// What Enter does in this field: `submit` (the form's rule), `off`, or
65    /// `next` (moves to the next field).
66    pub enter: FieldEnter,
67    /// The share of the row the field takes, on a twelve-column grid.
68    pub span: Span,
69    /// Starts a new row, whatever room the current one has left.
70    pub break_row: bool,
71    /// Follows another field as it is typed, until this one is edited.
72    pub preset: Option<Preset>,
73    /// Submitted but never shown: a plain hidden input carrying its value. The
74    /// foreign key of a related record's form is one.
75    pub hidden: bool,
76    /// Changes when another field's state meets a condition.
77    pub trigger: Option<Trigger>,
78}
79
80/// How a preset shapes the text it copies.
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
82#[serde(rename_all = "lowercase")]
83pub enum PresetShape {
84    /// As typed.
85    Exact,
86    /// Lowercase words joined by hyphens: `hello-world`.
87    #[default]
88    Slug,
89    /// A slug with a leading slash: `/hello-world`.
90    Url,
91    /// A file name: spaces to hyphens, the rest kept.
92    File,
93}
94
95impl PresetShape {
96    /// The word the page carries, for the island.
97    pub fn as_str(self) -> &'static str {
98        match self {
99            PresetShape::Exact => "exact",
100            PresetShape::Slug => "slug",
101            PresetShape::Url => "url",
102            PresetShape::File => "file",
103        }
104    }
105}
106
107/// Fills a field from another as it is typed, until the field is edited.
108///
109/// In YAML, the followed field's name alone (`preset: title`, a slug), or a
110/// map: `preset: { field: title, type: url }`.
111#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
112pub struct Preset {
113    pub field: String,
114    pub shape: PresetShape,
115}
116
117impl Preset {
118    pub fn new(field: impl Into<String>, shape: PresetShape) -> Self {
119        Self {
120            field: field.into(),
121            shape,
122        }
123    }
124}
125
126impl<'de> Deserialize<'de> for Preset {
127    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
128        #[derive(Deserialize)]
129        #[serde(deny_unknown_fields)]
130        struct Full {
131            field: String,
132            #[serde(rename = "type", default)]
133            shape: PresetShape,
134        }
135        #[derive(Deserialize)]
136        #[serde(untagged)]
137        enum Raw {
138            Field(String),
139            Full(Full),
140        }
141        Ok(match Raw::deserialize(de)? {
142            Raw::Field(field) => Preset::new(field, PresetShape::Slug),
143            Raw::Full(full) => Preset::new(full.field, full.shape),
144        })
145    }
146}
147
148/// Changes a field when another field's state meets a condition.
149///
150/// ```yaml
151/// send_at:
152///   type: date
153///   trigger: { action: show, field: is_delayed, condition: checked }
154/// ```
155#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
156#[serde(deny_unknown_fields)]
157pub struct Trigger {
158    /// What happens when the condition holds: `show`, `hide`, `enable`,
159    /// `disable`, `empty`, `fill[value]`, or several joined by `|`.
160    pub action: String,
161    /// The field watched. `name[]` watches every value of a checklist.
162    pub field: String,
163    /// `checked`, `unchecked`, `value[x]`, `value[x][y]` (either), `value[]`
164    /// (empty), `value[*]` (anything), `value[foo*]` (a prefix).
165    pub condition: String,
166}
167
168impl Trigger {
169    pub fn new(
170        action: impl Into<String>,
171        field: impl Into<String>,
172        condition: impl Into<String>,
173    ) -> Self {
174        Self {
175            action: action.into(),
176            field: field.into(),
177            condition: condition.into(),
178        }
179    }
180
181    /// Refuses an action or condition the island does not know.
182    pub fn check(&self) -> Result<(), String> {
183        for action in self.action.split('|') {
184            let known = matches!(action, "show" | "hide" | "enable" | "disable" | "empty")
185                || (action.starts_with("fill[") && action.ends_with(']'));
186            if !known {
187                return Err(format!(
188                    "unknown trigger action `{action}`: show, hide, enable, disable, empty or fill[value]"
189                ));
190            }
191        }
192        let known = matches!(self.condition.as_str(), "checked" | "unchecked")
193            || (self.condition.starts_with("value[") && self.condition.ends_with(']'));
194        if !known {
195            return Err(format!(
196                "unknown trigger condition `{}`: checked, unchecked or value[..]",
197                self.condition
198            ));
199        }
200        Ok(())
201    }
202
203    /// The name of the field watched, without a `[]` suffix.
204    pub fn watched(&self) -> &str {
205        self.field.trim_end_matches("[]")
206    }
207}
208
209/// The attributes a field's wrapper carries for its preset and trigger, each
210/// led by a space, empty when it has neither.
211pub(crate) fn behaviour_attrs(field: &FormField) -> String {
212    fn escaped(text: &str) -> String {
213        text.replace('&', "&amp;")
214            .replace('<', "&lt;")
215            .replace('>', "&gt;")
216            .replace('"', "&quot;")
217    }
218    let mut attrs = String::new();
219    if let Some(preset) = &field.preset {
220        attrs.push_str(&format!(
221            r#" data-lat-preset="{}" data-lat-preset-type="{}""#,
222            escaped(&preset.field),
223            preset.shape.as_str()
224        ));
225    }
226    if let Some(trigger) = &field.trigger {
227        attrs.push_str(&format!(
228            r#" data-lat-trigger-action="{}" data-lat-trigger-field="{}" data-lat-trigger-condition="{}""#,
229            escaped(&trigger.action),
230            escaped(&trigger.field),
231            escaped(&trigger.condition)
232        ));
233    }
234    attrs
235}
236
237/// The share of a row a field takes, in twelfths. Written in YAML as a
238/// fraction (`1/2`, `1/3`, `2/3`, `1/4`, `3/4`), `full`, a count of columns
239/// (`1` to `12`), or the words `half`, `third`, `quarter`, `left`, `right` and
240/// `auto` (each a half). Fields flow left to right and wrap when a row is full.
241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
242pub struct Span(u8);
243
244impl Span {
245    /// The whole row.
246    pub const FULL: Span = Span(12);
247
248    /// `columns` twelfths of the row, clamped to 1 to 12.
249    pub fn columns(columns: u8) -> Self {
250        Span(columns.clamp(1, 12))
251    }
252
253    /// The twelfths this span covers.
254    pub fn width(self) -> u8 {
255        self.0
256    }
257
258    /// Reads the YAML spellings.
259    pub fn parse(text: &str) -> Result<Self, String> {
260        let columns = match text.trim() {
261            "full" | "12/12" => 12,
262            "1/2" | "half" | "left" | "right" | "auto" => 6,
263            "1/3" | "third" => 4,
264            "2/3" => 8,
265            "1/4" | "quarter" => 3,
266            "3/4" => 9,
267            other => match other.parse::<u8>() {
268                Ok(n) if (1..=12).contains(&n) => n,
269                _ => {
270                    return Err(format!(
271                        "unknown span `{other}`, expected full, 1/2, 1/3, 2/3, 1/4, 3/4 or 1 to 12"
272                    ))
273                }
274            },
275        };
276        Ok(Span(columns))
277    }
278
279    /// The CSS class the field wrapper carries; none for a full row.
280    fn class(self) -> String {
281        if self.0 == 12 {
282            String::new()
283        } else {
284            format!(" lat-field--{}", self.0)
285        }
286    }
287}
288
289impl Default for Span {
290    fn default() -> Self {
291        Span::FULL
292    }
293}
294
295impl Serialize for Span {
296    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
297        match self.0 {
298            12 => serializer.serialize_str("full"),
299            6 => serializer.serialize_str("1/2"),
300            4 => serializer.serialize_str("1/3"),
301            8 => serializer.serialize_str("2/3"),
302            3 => serializer.serialize_str("1/4"),
303            9 => serializer.serialize_str("3/4"),
304            n => serializer.serialize_u8(n),
305        }
306    }
307}
308
309impl<'de> Deserialize<'de> for Span {
310    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
311        #[derive(Deserialize)]
312        #[serde(untagged)]
313        enum Raw {
314            Columns(u8),
315            Text(String),
316        }
317        match Raw::deserialize(deserializer)? {
318            Raw::Columns(n) if (1..=12).contains(&n) => Ok(Span(n)),
319            Raw::Columns(n) => Err(serde::de::Error::custom(format!(
320                "unknown span `{n}`, expected 1 to 12"
321            ))),
322            Raw::Text(text) => Span::parse(&text).map_err(serde::de::Error::custom),
323        }
324    }
325}
326
327/// The wrapper classes a field's layout adds: its span, and a row break.
328pub(crate) fn layout_classes(span: Span, break_row: bool) -> String {
329    let mut classes = span.class();
330    if break_row {
331        classes.push_str(" lat-field--break");
332    }
333    classes
334}
335
336/// What Enter does in a form's single-line fields.
337#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
338#[serde(rename_all = "lowercase")]
339pub enum EnterPolicy {
340    /// Submits the form. Cmd/Ctrl+Enter submits from a textarea as well.
341    #[default]
342    Submit,
343    /// Enter never submits; Cmd/Ctrl+Enter still does.
344    Off,
345}
346
347/// Where the cursor goes when a form opens.
348#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
349#[serde(rename_all = "lowercase")]
350pub enum FormFocus {
351    /// A new record opens with the cursor in its first field. A refused save
352    /// comes back with the cursor in the first field it refused.
353    #[default]
354    Auto,
355    /// The cursor is left where the browser puts it.
356    Off,
357}
358
359/// What Enter does in one field, over the form's [`EnterPolicy`].
360#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
361#[serde(rename_all = "lowercase")]
362pub enum FieldEnter {
363    /// The form's rule.
364    #[default]
365    Submit,
366    /// Nothing.
367    Off,
368    /// Focus moves to the next field.
369    Next,
370}
371
372impl FieldEnter {
373    /// The `data-lat-enter` value the field wrapper carries; empty for the
374    /// form's rule.
375    fn attribute(self) -> &'static str {
376        match self {
377            FieldEnter::Submit => "",
378            FieldEnter::Off => "off",
379            FieldEnter::Next => "next",
380        }
381    }
382}
383
384impl Default for FormConfig {
385    /// Everything a descriptor file leaves to the resource level: the entity,
386    /// the path and the id column are filled in when the file is read.
387    fn default() -> Self {
388        Self {
389            entity: String::new(),
390            title: Text::new(""),
391            base_path: String::new(),
392            id_field: "id".to_string(),
393            fields: Vec::new(),
394            enter: EnterPolicy::default(),
395            confirm_leave: true,
396            focus: FormFocus::default(),
397            persist: None,
398            timestamps: false,
399            done_path: None,
400        }
401    }
402}
403
404impl Default for FormField {
405    /// A text field, named by the key it is written under.
406    fn default() -> Self {
407        Self::of("", Text::new(""), "text")
408    }
409}
410
411impl<'de> Deserialize<'de> for FormField {
412    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
413        struct Entry;
414        impl<'de> serde::de::Visitor<'de> for Entry {
415            type Value = FormField;
416
417            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
418                f.write_str("a field: its own keys and its type's")
419            }
420
421            fn visit_map<A: serde::de::MapAccess<'de>>(
422                self,
423                map: A,
424            ) -> Result<FormField, A::Error> {
425                let mut field = FormField::default();
426                let theirs = crate::keyed::split_entry(map, |key, map| {
427                    match key {
428                        "name" => field.name = map.next_value()?,
429                        "label" => field.label = map.next_value()?,
430                        "type" => field.field_type = map.next_value()?,
431                        "rules" => field.rules = map.next_value()?,
432                        "translatable" => field.translatable = map.next_value()?,
433                        "help" => field.help = map.next_value()?,
434                        "enter" => field.enter = map.next_value()?,
435                        "span" => field.span = map.next_value()?,
436                        "break" => field.break_row = map.next_value()?,
437                        "preset" => field.preset = map.next_value()?,
438                        "trigger" => field.trigger = map.next_value()?,
439                        "hidden" => field.hidden = map.next_value()?,
440                        _ => return Ok(false),
441                    }
442                    Ok(true)
443                })?;
444                field.options = theirs;
445                if let Some(trigger) = &field.trigger {
446                    trigger.check().map_err(serde::de::Error::custom)?;
447                }
448                Ok(field)
449            }
450
451            /// A key written bare (`title:`) is a field with every default.
452            fn visit_unit<E: serde::de::Error>(self) -> Result<FormField, E> {
453                Ok(FormField::default())
454            }
455        }
456        de.deserialize_map(Entry)
457    }
458}
459
460impl Serialize for FormField {
461    fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
462        use serde::ser::SerializeMap;
463        let mut map = ser.serialize_map(None)?;
464        map.serialize_entry("name", &self.name)?;
465        map.serialize_entry("label", &self.label)?;
466        map.serialize_entry("type", &self.field_type)?;
467        map.serialize_entry("rules", &self.rules)?;
468        map.serialize_entry("translatable", &self.translatable)?;
469        map.serialize_entry("help", &self.help)?;
470        map.serialize_entry("enter", &self.enter)?;
471        map.serialize_entry("span", &self.span)?;
472        map.serialize_entry("break", &self.break_row)?;
473        if let Some(preset) = &self.preset {
474            map.serialize_entry("preset", preset)?;
475        }
476        if self.hidden {
477            map.serialize_entry("hidden", &true)?;
478        }
479        if let Some(trigger) = &self.trigger {
480            map.serialize_entry("trigger", trigger)?;
481        }
482        crate::keyed::serialize_theirs(&mut map, &self.options)?;
483        map.end()
484    }
485}
486
487impl crate::keyed::Keyed for FormField {
488    fn key(&self) -> &str {
489        &self.name
490    }
491    fn set_key(&mut self, key: String) {
492        self.name = key;
493    }
494}
495
496impl FormField {
497    /// A field of a registered type by key.
498    pub fn of(name: &str, label: impl Into<Text>, field_type: &str) -> Self {
499        Self {
500            name: name.to_string(),
501            label: label.into(),
502            field_type: field_type.to_string(),
503            options: serde_json::Value::Null,
504            rules: Vec::new(),
505            translatable: false,
506            help: None,
507            enter: FieldEnter::default(),
508            span: Span::default(),
509            break_row: false,
510            preset: None,
511            trigger: None,
512            hidden: false,
513        }
514    }
515
516    /// Follows `field` as it is typed, shaped as `shape`, until this field is
517    /// edited.
518    pub fn preset(mut self, field: &str, shape: PresetShape) -> Self {
519        self.preset = Some(Preset::new(field, shape));
520        self
521    }
522
523    /// Changes when `trigger`'s condition holds on the field it watches.
524    pub fn trigger(mut self, trigger: Trigger) -> Self {
525        self.trigger = Some(trigger);
526        self
527    }
528
529    pub fn text(name: &str, label: impl Into<Text>) -> Self {
530        Self::of(name, label, "text")
531    }
532
533    pub fn textarea(name: &str, label: impl Into<Text>) -> Self {
534        Self::of(name, label, "textarea")
535    }
536
537    /// A reference field: a picker over a registered picker source (a `vendor.name`
538    /// key), which the field searches and resolves against. Builds the `source`
539    /// option so a descriptor needs no raw JSON.
540    pub fn reference(name: &str, label: impl Into<Text>, source: &str) -> Self {
541        Self::of(name, label, "reference").options(serde_json::json!({ "source": source }))
542    }
543
544    /// A dropdown over a fixed set of `(value, label)` choices.
545    pub fn select(name: &str, label: impl Into<Text>, options: Vec<(&str, &str)>) -> Self {
546        Self::of(name, label, "select").options(Self::choices(options))
547    }
548
549    /// The same choices rendered as radio buttons.
550    pub fn radio(name: &str, label: impl Into<Text>, options: Vec<(&str, &str)>) -> Self {
551        Self::of(name, label, "radio").options(Self::choices(options))
552    }
553
554    /// A checkbox over a boolean column.
555    pub fn switch(name: &str, label: impl Into<Text>) -> Self {
556        Self::of(name, label, "switch")
557    }
558
559    /// A calendar date, stored as `YYYY-MM-DD`.
560    pub fn date(name: &str, label: impl Into<Text>) -> Self {
561        Self::of(name, label, "date")
562    }
563
564    /// A password: hashed on save, never rendered back, and left alone when the
565    /// field is submitted blank on an edit.
566    pub fn password(name: &str, label: impl Into<Text>) -> Self {
567        Self::of(name, label, "password")
568    }
569
570    /// A list of rows, each holding `fields`, stored as an array of objects.
571    pub fn repeater(name: &str, label: impl Into<Text>, fields: Vec<FormField>) -> Self {
572        Self::of(name, label, "repeater").options(serde_json::json!({ "fields": fields }))
573    }
574
575    /// A repeater whose rows collapse to the line that names them, opening one
576    /// at a time. `summary_field` names the sub-field that titles a row; unset,
577    /// the first one does.
578    ///
579    /// Use it when a row holds more than one or two fields: rendered inline
580    /// those become columns, and a row of four is already unreadable. A single
581    /// narrow column is better left inline, where collapsing would hide the one
582    /// thing worth seeing.
583    pub fn repeater_list(
584        name: &str,
585        label: impl Into<Text>,
586        fields: Vec<FormField>,
587        summary_field: Option<&str>,
588    ) -> Self {
589        Self::of(name, label, "repeater").options(serde_json::json!({
590            "fields": fields,
591            "display": "list",
592            "summary_field": summary_field,
593        }))
594    }
595
596    /// The options blob the choice-shaped types read.
597    fn choices(options: Vec<(&str, &str)>) -> serde_json::Value {
598        let options: Vec<serde_json::Value> = options
599            .into_iter()
600            .map(|(value, label)| serde_json::json!({ "value": value, "label": label }))
601            .collect();
602        serde_json::json!({ "options": options })
603    }
604
605    /// Sets the field type's typed options (the type validates them at render).
606    pub fn options(mut self, options: serde_json::Value) -> Self {
607        self.options = options;
608        self
609    }
610
611    /// Requires a non-empty value in every mode.
612    pub fn required(mut self) -> Self {
613        self.rules.push(Rule::Required);
614        self
615    }
616
617    /// Requires a non-empty value in one mode only (for example a password set on
618    /// create but left unchanged on edit).
619    pub fn required_on(mut self, mode: Mode) -> Self {
620        self.rules.push(Rule::RequiredOn(mode));
621        self
622    }
623
624    /// Requires the value to be unique in this field's column (a DB probe that
625    /// ignores the edited row on update).
626    pub fn unique(mut self) -> Self {
627        self.rules.push(Rule::Unique);
628        self
629    }
630
631    /// Caps the value's length.
632    pub fn max_length(mut self, n: usize) -> Self {
633        self.rules.push(Rule::MaxLength(n));
634        self
635    }
636
637    /// Requires at least `n` characters when the value is non-empty.
638    pub fn min_length(mut self, n: usize) -> Self {
639        self.rules.push(Rule::MinLength(n));
640        self
641    }
642
643    /// Requires a syntactically valid email address.
644    pub fn email(mut self) -> Self {
645        self.rules.push(Rule::Email);
646        self
647    }
648
649    /// Marks this field as translatable content (see [`FormField::translatable`]).
650    pub fn translatable(mut self) -> Self {
651        self.translatable = true;
652        self
653    }
654
655    /// Help text shown beneath the control.
656    pub fn help(mut self, text: impl Into<Text>) -> Self {
657        self.help = Some(text.into());
658        self
659    }
660
661    /// The share of the row this field takes.
662    pub fn span(mut self, span: Span) -> Self {
663        self.span = span;
664        self
665    }
666
667    /// Starts a new row.
668    pub fn break_row(mut self) -> Self {
669        self.break_row = true;
670        self
671    }
672}
673
674/// A form descriptor: which table, its editable fields, the id column, and the
675/// base path the form lives under (`{base_path}/new`, `{base_path}/{id}/edit`).
676///
677/// Built with [`FormConfig::new`] plus its builder methods. Non-exhaustive so the
678/// framework can learn something new about a form after 1.0 without a major bump.
679#[derive(Debug, Clone, Serialize, Deserialize)]
680#[serde(deny_unknown_fields, default)]
681#[non_exhaustive]
682pub struct FormConfig {
683    pub entity: String,
684    /// The screen title, localized at render. Serde stays a plain string.
685    pub title: Text,
686    pub base_path: String,
687    pub id_field: String,
688    #[serde(
689        deserialize_with = "crate::keyed::deserialize",
690        serialize_with = "crate::keyed::serialize"
691    )]
692    pub fields: Vec<FormField>,
693    /// What Enter does in the form's single-line fields. Default `submit`.
694    #[serde(default)]
695    pub enter: EnterPolicy,
696    /// Ask before leaving the form with changes unsaved. Default `true`.
697    pub confirm_leave: bool,
698    /// Where the cursor goes when the form opens. Default `auto`.
699    pub focus: FormFocus,
700    /// The registered persister that writes this form (a dotted `vendor.name`),
701    /// or `None` for the built-in descriptor insert/update. See [`crate::persist`].
702    pub persist: Option<String>,
703    /// Stamp `created_at` and `updated_at` on write. Opt in per form, because
704    /// the columns have to exist on this entity's table.
705    #[serde(default)]
706    pub timestamps: bool,
707    /// Where a save and a cancel return to, when it is not the list under
708    /// `base_path`: a related record's form returns to its parent. Set by the
709    /// router, never by a descriptor.
710    #[serde(skip)]
711    pub(crate) done_path: Option<String>,
712}
713
714impl FormConfig {
715    /// A form over `entity`, mounted under `base_path`, keyed by `id_field`.
716    ///
717    /// The four arguments are the ones with no sensible default; everything else
718    /// is opt-in through a builder method, so a later field costs nothing.
719    pub fn new(
720        entity: impl Into<String>,
721        title: impl Into<Text>,
722        base_path: impl Into<String>,
723        id_field: impl Into<String>,
724        fields: Vec<FormField>,
725    ) -> Self {
726        Self {
727            enter: Default::default(),
728            confirm_leave: true,
729            focus: FormFocus::default(),
730            entity: entity.into(),
731            title: title.into(),
732            base_path: base_path.into(),
733            id_field: id_field.into(),
734            fields,
735            persist: None,
736            timestamps: false,
737            done_path: None,
738        }
739    }
740
741    /// Writes this form through a registered persister instead of the built-in
742    /// descriptor insert/update.
743    pub fn persist(mut self, name: impl Into<String>) -> Self {
744        self.persist = Some(name.into());
745        self
746    }
747
748    /// Whether leaving the form with changes unsaved asks first. Default `true`.
749    pub fn confirm_leave(mut self, ask: bool) -> Self {
750        self.confirm_leave = ask;
751        self
752    }
753
754    /// Where the cursor goes when the form opens.
755    pub fn focus(mut self, focus: FormFocus) -> Self {
756        self.focus = focus;
757        self
758    }
759
760    /// Stamps `created_at` and `updated_at` on write. Opt in, because the
761    /// columns have to exist on this entity's table.
762    pub fn timestamps(mut self) -> Self {
763        self.timestamps = true;
764        self
765    }
766
767    fn idents_valid(&self) -> bool {
768        valid_ident(&self.entity)
769            && valid_ident(&self.id_field)
770            && self.fields.iter().all(|f| valid_ident(&f.name))
771    }
772}
773
774/// A [`FormConfig`] with each field's options resolved once, at router build.
775/// Handlers carry this so option resolution and intrinsic-rule merging happen a
776/// single time (not per render), and a malformed option or unregistered type
777/// aborts boot rather than degrading silently to plain text.
778#[derive(Clone)]
779pub(crate) struct PreparedForm {
780    pub(crate) config: FormConfig,
781    /// Parallel to `config.fields`.
782    fields: Vec<PreparedField>,
783    /// The write handler: the named persister, or the built-in default.
784    persister: Arc<dyn Persister>,
785    /// Listeners for this form's entity, in registration order.
786    listeners: Vec<Arc<dyn ModelListener>>,
787    /// Offer "Save and continue editing" beside Save: a resource with relation
788    /// sections wants to land on the edit page, where the sections are.
789    pub(crate) stay: bool,
790}
791
792/// One field's boot-resolved state: its typed options and its merged rules (the
793/// type's intrinsic rules ahead of the descriptor's own).
794#[derive(Clone)]
795struct PreparedField {
796    /// Resolved once at boot, so the save and load hooks need no lookup.
797    field_type: Arc<dyn crate::field::FieldType>,
798    opts: ResolvedOptions,
799    rules: Vec<Rule>,
800}
801
802impl PreparedForm {
803    /// The write handler this form resolved to.
804    pub(crate) fn persister(&self) -> Arc<dyn Persister> {
805        self.persister.clone()
806    }
807
808    /// Whether the form declares `field`.
809    pub(crate) fn has_field(&self, field: &str) -> bool {
810        self.config.fields.iter().any(|f| f.name == field)
811    }
812
813    /// The widget assets `field`'s type declares.
814    pub(crate) fn field_assets(&self, field: &str) -> Vec<&'static str> {
815        self.config
816            .fields
817            .iter()
818            .zip(&self.fields)
819            .find(|(f, _)| f.name == field)
820            .map(|(_, pf)| pf.field_type.assets(&pf.opts))
821            .unwrap_or_default()
822    }
823
824    /// One field's bare control holding `value`, as the form would render it,
825    /// for a place outside the form such as an editable cell. `None` when the
826    /// form has no such field.
827    pub(crate) fn control(
828        &self,
829        state: &AdminState,
830        field: &str,
831        dom_id: &str,
832        value: &str,
833        shell: &crate::Shell,
834    ) -> Option<String> {
835        let (f, pf) = self
836            .config
837            .fields
838            .iter()
839            .zip(&self.fields)
840            .find(|(f, _)| f.name == field)?;
841        let value = FieldValue::Text(value.to_string());
842        let label = shell.tt(&f.label);
843        let cx = FieldCx {
844            name: &f.name,
845            id: dom_id,
846            label: &label,
847            value: &value,
848            required: has_required(&pf.rules),
849            max_length: max_length(&pf.rules),
850            opts: &pf.opts,
851            base: &shell.base,
852            i18n: shell.i18n(),
853            icons: crate::icons::Icons::new(&shell.icon_set, &shell.sprite_url),
854        };
855        let ft = state.field_types.get(&f.field_type)?;
856        let scope = OverrideScope {
857            surface: Surface::Field,
858            view_key: &f.field_type,
859            resource: Some(&self.config.base_path),
860            field: Some(&f.name),
861        };
862        Some(render_field(ft.as_ref(), state.overrides.as_ref(), &scope, &cx).into_string())
863    }
864
865    /// Resolves every field against the registry. Returns the offending field
866    /// and reason (for a boot abort) when a type is unregistered or rejects its
867    /// options.
868    pub(crate) fn prepare(
869        config: FormConfig,
870        field_types: &crate::field::FieldRegistry,
871        persisters: &PersisterRegistry,
872        listeners: &[ModelListenerReg],
873    ) -> Result<Self, String> {
874        let mut fields = Vec::with_capacity(config.fields.len());
875        for f in &config.fields {
876            let names = || config.fields.iter().map(|other| other.name.as_str());
877            if let Some(preset) = &f.preset {
878                if !names().any(|n| n == preset.field) {
879                    return Err(format!(
880                        "field `{}` presets from `{}`, which is not in this form",
881                        f.name, preset.field
882                    ));
883                }
884            }
885            if let Some(trigger) = &f.trigger {
886                trigger
887                    .check()
888                    .map_err(|e| format!("field `{}`: {e}", f.name))?;
889                if !names().any(|n| n == trigger.watched()) {
890                    return Err(format!(
891                        "field `{}` watches `{}`, which is not in this form",
892                        f.name,
893                        trigger.watched()
894                    ));
895                }
896            }
897            let ft = field_types.get(&f.field_type).ok_or_else(|| {
898                format!(
899                    "field `{}` uses unregistered type `{}`",
900                    f.name, f.field_type
901                )
902            })?;
903            crate::field::check_field_keys(f, ft.as_ref())
904                .map_err(|e| format!("field `{}` (`{}`): {e}", f.name, f.field_type))?;
905            let opts = ft
906                .resolve_options(&f.options, field_types)
907                .map_err(|e| format!("field `{}` (`{}`): {e}", f.name, f.field_type))?;
908            let mut rules = ft.intrinsic_rules(&opts);
909            rules.extend(f.rules.clone());
910            fields.push(PreparedField {
911                field_type: ft.clone(),
912                opts,
913                rules,
914            });
915        }
916        let persister: Arc<dyn Persister> = match &config.persist {
917            Some(key) => persisters
918                .get(key)
919                .cloned()
920                .ok_or_else(|| format!("form names unregistered persister `{key}`"))?,
921            None => Arc::new(DefaultPersister::from_config(&config)),
922        };
923        // The framework's own listeners run first, so a contributed one can see
924        // or override what they set.
925        let mut resolved: Vec<Arc<dyn ModelListener>> = Vec::new();
926        if config.timestamps {
927            resolved.push(Arc::new(laterite_core::Timestamps));
928        }
929        resolved.extend(
930            listeners
931                .iter()
932                .filter(|reg| reg.matches(&config.entity))
933                .map(|reg| reg.listener.clone()),
934        );
935        let listeners = resolved;
936        Ok(Self {
937            config,
938            fields,
939            persister,
940            listeners,
941            stay: false,
942        })
943    }
944}
945
946/// The submission as a record, carrying only the fields the descriptor declares.
947/// A request cannot introduce an attribute this way, so the persister may widen
948/// its write to whatever the record holds; only registered listeners add keys.
949///
950/// Each value passes through its field type, which decides what gets stored and
951/// may leave the attribute out entirely (a blank password on an edit).
952fn declared_record(
953    form: &PreparedForm,
954    data: &HashMap<String, String>,
955    mode: Mode,
956) -> Result<Record, String> {
957    let mut rec = Record::new(&form.config.entity);
958    for (field, prepared) in form.config.fields.iter().zip(&form.fields) {
959        let submitted = crate::field::SubmittedField::new(&field.name, data);
960        if let Some(value) = prepared
961            .field_type
962            .to_attr(&submitted, &prepared.opts, mode)?
963        {
964            rec.set(field.name.clone(), value);
965        }
966    }
967    Ok(rec)
968}
969
970/// The submission with every field present under its own name.
971///
972/// A field of several controls submits keys of its own and none under its name.
973/// Its type gathers them into one value, so the rules see the field and a
974/// refused save is re-rendered from what the operator entered. A key already
975/// present is left as submitted.
976pub(crate) fn gathered(
977    form: &PreparedForm,
978    mut data: HashMap<String, String>,
979) -> HashMap<String, String> {
980    for (field, prepared) in form.config.fields.iter().zip(&form.fields) {
981        if data.contains_key(&field.name) {
982            continue;
983        }
984        let value = prepared.field_type.submitted(
985            &crate::field::SubmittedField::new(&field.name, &data),
986            &prepared.opts,
987        );
988        if let Some(value) = value {
989            data.insert(field.name.clone(), value);
990        }
991    }
992    data
993}
994
995/// The merged validation rules for every field, in order.
996fn merged_field_rules(form: &PreparedForm) -> Vec<FieldRules> {
997    form.config
998        .fields
999        .iter()
1000        .zip(&form.fields)
1001        // The rules carry the label's source string; the validation message re-wraps
1002        // it as a nested Text, so it localizes at render like any other label.
1003        .map(|(f, pf)| FieldRules::new(f.name.clone(), f.label.source(), pf.rules.clone()))
1004        .collect()
1005}
1006
1007/// The write a submit and a [`FormHandle`] share: `data` (already gathered)
1008/// validated against the merged rules, shaped into the declared record and saved
1009/// through the listeners and the persister. `id` names the row an edit updates;
1010/// `None` creates. Returns the record as saved, its id set on a create.
1011pub(crate) async fn write(
1012    db: &Db,
1013    form: &PreparedForm,
1014    data: &HashMap<String, String>,
1015    id: Option<&str>,
1016    actor: &Actor,
1017) -> Result<Record, SaveError> {
1018    let (mut rec, op) = prepare(db, form, data, id).await?;
1019    persist::save(
1020        persist::SaveRequest {
1021            db,
1022            listeners: &form.listeners,
1023            persister: form.persister.as_ref(),
1024            actor,
1025            op,
1026            id,
1027        },
1028        &mut rec,
1029    )
1030    .await?;
1031    link_media(
1032        db,
1033        form,
1034        data,
1035        rec.id()
1036            .map(|i| i.to_string())
1037            .or_else(|| id.map(str::to_string)),
1038    )
1039    .await;
1040    Ok(rec)
1041}
1042
1043/// Writes the links a saved record's media fields hold, under each field's
1044/// name, so the library knows who uses a file. A type that holds no media
1045/// says so and is skipped; a failure is logged, never a failed save.
1046async fn link_media(
1047    db: &Db,
1048    form: &PreparedForm,
1049    data: &HashMap<String, String>,
1050    owner_id: Option<String>,
1051) {
1052    let Some(owner_id) = owner_id else {
1053        return;
1054    };
1055    for (field, prepared) in form.config.fields.iter().zip(&form.fields) {
1056        let submitted = data.get(&field.name).map(String::as_str);
1057        let Some(ids) = prepared.field_type.linked_media(submitted, &prepared.opts) else {
1058            continue;
1059        };
1060        let owner = laterite_media::Owner {
1061            owner_type: &form.config.entity,
1062            owner_id: &owner_id,
1063            field: &field.name,
1064        };
1065        if let Err(e) = laterite_media::link::set(db, owner, &ids).await {
1066            tracing::warn!(error = %e, entity = %form.config.entity, field = %field.name, "media links could not be written");
1067        }
1068    }
1069}
1070
1071/// The write up to the point of writing: the data validated and shaped into
1072/// the record, with the operation it would be. What a check runs, and what a
1073/// write runs first.
1074async fn prepare(
1075    db: &Db,
1076    form: &PreparedForm,
1077    data: &HashMap<String, String>,
1078    id: Option<&str>,
1079) -> Result<(Record, Op), SaveError> {
1080    if !form.config.idents_valid() {
1081        return Err(SaveError::Failed(format!(
1082            "form `{}` names an invalid entity or field identifier",
1083            form.config.entity
1084        )));
1085    }
1086    let (mode, op) = match id {
1087        None => (Mode::Create, Op::Create),
1088        Some(_) => (Mode::Update, Op::Update),
1089    };
1090    let bag = validate(
1091        db,
1092        &form.config.entity,
1093        &form.config.id_field,
1094        &merged_field_rules(form),
1095        data,
1096        mode,
1097        id,
1098    )
1099    .await
1100    .map_err(|e| SaveError::Failed(e.to_string()))?;
1101    if !bag.is_empty() {
1102        return Err(SaveError::Invalid(bag));
1103    }
1104    let mut rec = declared_record(form, data, mode).map_err(|e| {
1105        tracing::error!(entity = %form.config.entity, error = %e, "preparing the write failed");
1106        SaveError::Failed(e)
1107    })?;
1108    if let Some(n) = id.and_then(|id| id.parse::<i64>().ok()) {
1109        rec.set_id(n);
1110    }
1111    Ok((rec, op))
1112}
1113
1114/// The forms the resources mounted, keyed by each resource's path as its
1115/// descriptor declares it, relative to the admin root.
1116pub(crate) type Forms = Arc<HashMap<String, Arc<PreparedForm>>>;
1117
1118/// A resource's form, written through from code.
1119///
1120/// Runs what the form's own submit runs, with no request in hand: the values
1121/// are validated against the form's rules, shaped by its field types and saved
1122/// through its listeners and persister, so an importer or a sync writes exactly
1123/// what an operator could have typed, audited the same way. A screen reaches one
1124/// through [`crate::routes::RouteCtx::form`].
1125#[derive(Clone)]
1126pub struct FormHandle {
1127    db: Db,
1128    form: Arc<PreparedForm>,
1129}
1130
1131impl FormHandle {
1132    pub(crate) fn new(db: Db, form: Arc<PreparedForm>) -> Self {
1133        Self { db, form }
1134    }
1135
1136    /// The table the form writes.
1137    pub fn entity(&self) -> &str {
1138        &self.form.config.entity
1139    }
1140
1141    /// The primary key column.
1142    pub fn id_field(&self) -> &str {
1143        &self.form.config.id_field
1144    }
1145
1146    /// The fields the form declares, in order. `data` is keyed by their names.
1147    pub fn fields(&self) -> &[FormField] {
1148        &self.form.config.fields
1149    }
1150
1151    /// Validates `data` as a submission and saves a new record, returning its id.
1152    ///
1153    /// `data` holds each field's value under the field's name, as the form's
1154    /// control submits it; a field left out is blank. `Invalid` carries the
1155    /// per-field messages a refused submit would show.
1156    pub async fn create(
1157        &self,
1158        data: HashMap<String, String>,
1159        actor: &Actor,
1160    ) -> Result<i64, SaveError> {
1161        let data = gathered(&self.form, data);
1162        let rec = write(&self.db, &self.form, &data, None, actor).await?;
1163        rec.id()
1164            .ok_or_else(|| SaveError::Failed("the persister returned no id".to_string()))
1165    }
1166
1167    /// The record `id` as the edit form shows it: each stored value back through
1168    /// its field type, keyed by field name. `None` when no record has that id.
1169    /// Lay a partial `data` over it before [`update`](Self::update) to change
1170    /// some fields and keep the rest.
1171    pub async fn load(&self, id: i64) -> Result<Option<HashMap<String, String>>, SaveError> {
1172        load_values(&self.db, &self.form, &id.to_string())
1173            .await
1174            .map_err(|e| SaveError::Failed(e.to_string()))
1175    }
1176
1177    /// What [`create`](Self::create) or [`update`](Self::update) would do with
1178    /// `data`, with nothing written: the rules and the field conversions run,
1179    /// the listeners and the persister do not. `id` names the record an edit
1180    /// would change; `None` checks as a create.
1181    pub async fn check(
1182        &self,
1183        id: Option<i64>,
1184        data: HashMap<String, String>,
1185    ) -> Result<(), SaveError> {
1186        let data = gathered(&self.form, data);
1187        let id = id.map(|id| id.to_string());
1188        prepare(&self.db, &self.form, &data, id.as_deref())
1189            .await
1190            .map(|_| ())
1191    }
1192
1193    /// Validates `data` as an edit of the record `id` and saves it. Every field
1194    /// is written, so a field left out of `data` is stored blank.
1195    pub async fn update(
1196        &self,
1197        id: i64,
1198        data: HashMap<String, String>,
1199        actor: &Actor,
1200    ) -> Result<(), SaveError> {
1201        let data = gathered(&self.form, data);
1202        write(&self.db, &self.form, &data, Some(&id.to_string()), actor)
1203            .await
1204            .map(|_| ())
1205    }
1206}
1207
1208/// The longest value the rules accept, when they set one.
1209pub(crate) fn max_length(rules: &[Rule]) -> Option<usize> {
1210    rules
1211        .iter()
1212        .filter_map(|r| match r {
1213            Rule::MaxLength(n) => Some(*n),
1214            _ => None,
1215        })
1216        .min()
1217}
1218
1219/// Whether any rule marks the field required.
1220fn has_required(rules: &[Rule]) -> bool {
1221    rules
1222        .iter()
1223        .any(|r| matches!(r, Rule::Required | Rule::RequiredOn(_)))
1224}
1225
1226/// Renders an empty create form.
1227pub(crate) fn new_form(
1228    state: &AdminState,
1229    form: &PreparedForm,
1230    shell: crate::Shell,
1231    pending: Vec<String>,
1232) -> Response {
1233    let mut page = build(
1234        state,
1235        form,
1236        &format!("{}/new", form.config.base_path),
1237        None,
1238        &HashMap::new(),
1239        &ErrorBag::default(),
1240        &shell,
1241    );
1242    page.pending = pending;
1243    render(page)
1244}
1245
1246/// Where a save goes: the edit page when the operator asked to stay, else the
1247/// form's done path or its list.
1248fn after_save(form: &PreparedForm, data: &HashMap<String, String>, id: Option<i64>) -> String {
1249    let stay = data.get("then").map(String::as_str) == Some("stay");
1250    match (stay, id) {
1251        (true, Some(id)) => format!("{}/{}/edit", form.config.base_path, id),
1252        _ => form
1253            .config
1254            .done_path
1255            .clone()
1256            .unwrap_or_else(|| form.config.base_path.clone()),
1257    }
1258}
1259
1260/// Persists a new record, then redirects to the list. Re-renders with per-field
1261/// errors when validation fails.
1262pub(crate) async fn create(
1263    state: &AdminState,
1264    form: &PreparedForm,
1265    data: HashMap<String, String>,
1266    shell: crate::Shell,
1267    user: &laterite_auth::AuthenticatedUser,
1268    session: &crate::session::SessionHandle,
1269    headers: &axum::http::HeaderMap,
1270) -> Response {
1271    if !form.config.idents_valid() {
1272        return render_error();
1273    }
1274    let htmx = is_htmx(headers);
1275    let action = format!("{}/new", form.config.base_path);
1276    let mut data = gathered(form, data);
1277    let then = data.remove("then");
1278    let actor = Actor::from(user);
1279    match write(&state.db, form, &data, None, &actor).await {
1280        // The audit entry is written by the framework's audit listener, which
1281        // runs on every entity after the commit.
1282        Ok(rec) => {
1283            session.push_flash(crate::session::FlashLevel::Success, t!("Saved."));
1284            let mut choice = HashMap::new();
1285            if let Some(then) = then {
1286                choice.insert("then".to_string(), then);
1287            }
1288            saved_response(htmx, &after_save(form, &choice, rec.id()))
1289        }
1290        // A refused submission re-renders the form with per-field errors as 422,
1291        // the cross-surface "validation failure" status.
1292        Err(SaveError::Invalid(bag)) => {
1293            invalid_response(htmx, state, form, &action, None, &data, &bag, &shell)
1294        }
1295        Err(SaveError::Failed(msg)) => {
1296            tracing::error!(error = %msg, "admin create failed");
1297            render(build(
1298                state,
1299                form,
1300                &action,
1301                Some(t!("Could not save. Check the values and try again.")),
1302                &data,
1303                &ErrorBag::default(),
1304                &shell,
1305            ))
1306        }
1307    }
1308}
1309
1310/// Renders a form populated with an existing record.
1311pub(crate) async fn edit_form(
1312    state: &AdminState,
1313    form: &PreparedForm,
1314    id: String,
1315    shell: crate::Shell,
1316    sections: Vec<RelationSection>,
1317) -> Response {
1318    if !form.config.idents_valid() {
1319        return render_error();
1320    }
1321    let values = match load_values(&state.db, form, &id).await {
1322        Ok(Some(values)) => values,
1323        Ok(None) => return not_found(),
1324        Err(_) => return render_error(),
1325    };
1326
1327    let mut page = build(
1328        state,
1329        form,
1330        &format!("{}/{}/edit", form.config.base_path, id),
1331        None,
1332        &values,
1333        &ErrorBag::default(),
1334        &shell,
1335    );
1336    page.sections = sections;
1337    render(page)
1338}
1339
1340/// The stored record `id` as control values: each column back through its
1341/// field type, since what a column holds and what its control shows are not
1342/// always the same string. `None` when no record has that id.
1343/// `GET {base}/{id}/reveal/{field}`: the stored value of a sensitive field,
1344/// opened, as plain text for the field's Reveal button. Recorded in the audit
1345/// log as `<entity>.reveal` with the field as the detail.
1346pub(crate) async fn reveal(
1347    state: &AdminState,
1348    form: &PreparedForm,
1349    id: &str,
1350    field: &str,
1351    user: &laterite_auth::AuthenticatedUser,
1352) -> Response {
1353    if !form
1354        .config
1355        .fields
1356        .iter()
1357        .any(|f| f.name == field && f.field_type == "sensitive")
1358    {
1359        return crate::AdminError::NotFound.into_response();
1360    }
1361    // The column as stored, not as the control shows it (`load_values` masks it).
1362    let (sql, values) = {
1363        let cast = text_cast(state.db.backend);
1364        let mut select = Query::select();
1365        select
1366            .expr_as(
1367                Expr::col(Alias::new(field)).cast_as(Alias::new(cast)),
1368                Alias::new("sealed"),
1369            )
1370            .from(Alias::new(&form.config.entity))
1371            .and_where(
1372                Expr::col(Alias::new(&form.config.id_field))
1373                    .cast_as(Alias::new(cast))
1374                    .eq(id.to_string()),
1375            );
1376        to_sql(state.db.backend, select)
1377    };
1378    let sealed = match bind_values(sqlx::query(&sql), values)
1379        .fetch_optional(&state.db.pool)
1380        .await
1381    {
1382        Ok(Some(row)) => row
1383            .get_text_opt("sealed")
1384            .unwrap_or_default()
1385            .unwrap_or_default(),
1386        Ok(None) => return crate::AdminError::NotFound.into_response(),
1387        Err(e) => return crate::AdminError::Internal(anyhow::anyhow!(e)).into_response(),
1388    };
1389    let Some(plain) = crate::field::SensitiveField::open(&state.crypt, field, &sealed) else {
1390        return crate::AdminError::Internal(anyhow::anyhow!(
1391            "the value does not open under the application key"
1392        ))
1393        .into_response();
1394    };
1395    crate::audit::record(
1396        state,
1397        user,
1398        &format!("{}.reveal", form.config.entity),
1399        Some(&form.config.entity),
1400        Some(id),
1401        None,
1402        Some(field),
1403    )
1404    .await;
1405    (
1406        StatusCode::OK,
1407        [
1408            (
1409                axum::http::header::CONTENT_TYPE,
1410                "text/plain; charset=utf-8",
1411            ),
1412            (axum::http::header::CACHE_CONTROL, "private, no-store"),
1413        ],
1414        plain,
1415    )
1416        .into_response()
1417}
1418
1419pub(crate) async fn load_values(
1420    db: &Db,
1421    form: &PreparedForm,
1422    id: &str,
1423) -> Result<Option<HashMap<String, String>>, sqlx::Error> {
1424    // Scope the sea-query builder so it is dropped before the await below: its
1425    // identifiers are reference-counted (not `Send`), and a live builder across
1426    // the await would make the caller's future non-`Send`.
1427    let (sql, values) = {
1428        let cast = text_cast(db.backend);
1429        let mut select = Query::select();
1430        for field in &form.config.fields {
1431            select.expr_as(
1432                Expr::col(Alias::new(&field.name)).cast_as(Alias::new(cast)),
1433                Alias::new(&field.name),
1434            );
1435        }
1436        select.from(Alias::new(&form.config.entity)).and_where(
1437            Expr::col(Alias::new(&form.config.id_field))
1438                .cast_as(Alias::new(cast))
1439                .eq(id.to_string()),
1440        );
1441        to_sql(db.backend, select)
1442    };
1443    let Some(row) = bind_values(sqlx::query(&sql), values)
1444        .fetch_optional(&db.pool)
1445        .await?
1446    else {
1447        return Ok(None);
1448    };
1449    Ok(Some(
1450        form.config
1451            .fields
1452            .iter()
1453            .zip(&form.fields)
1454            .map(|(f, prepared)| {
1455                let stored = row.get_text_opt(f.name.as_str()).ok().flatten();
1456                let value = prepared
1457                    .field_type
1458                    .to_control(stored.as_deref(), &prepared.opts);
1459                (f.name.clone(), value)
1460            })
1461            .collect(),
1462    ))
1463}
1464
1465/// Persists an edited record, then redirects to the list. Re-renders with
1466/// per-field errors when validation fails.
1467// The generic handlers thread the request's pieces explicitly rather than through
1468// a context struct; the list is long but each argument is named at the call site.
1469#[allow(clippy::too_many_arguments)]
1470pub(crate) async fn update(
1471    state: &AdminState,
1472    form: &PreparedForm,
1473    id: String,
1474    data: HashMap<String, String>,
1475    shell: crate::Shell,
1476    user: &laterite_auth::AuthenticatedUser,
1477    session: &crate::session::SessionHandle,
1478    headers: &axum::http::HeaderMap,
1479) -> Response {
1480    if !form.config.idents_valid() {
1481        return render_error();
1482    }
1483    let htmx = is_htmx(headers);
1484    let action = format!("{}/{}/edit", form.config.base_path, id);
1485    let mut data = gathered(form, data);
1486    let then = data.remove("then");
1487    let actor = Actor::from(user);
1488    match write(&state.db, form, &data, Some(&id), &actor).await {
1489        Ok(_) => {
1490            session.push_flash(crate::session::FlashLevel::Success, t!("Saved."));
1491            let mut choice = HashMap::new();
1492            if let Some(then) = then {
1493                choice.insert("then".to_string(), then);
1494            }
1495            saved_response(htmx, &after_save(form, &choice, id.parse().ok()))
1496        }
1497        // A refused submission re-renders the form with per-field errors as 422,
1498        // the cross-surface "validation failure" status.
1499        Err(SaveError::Invalid(bag)) => {
1500            invalid_response(htmx, state, form, &action, None, &data, &bag, &shell)
1501        }
1502        Err(SaveError::Failed(msg)) => {
1503            tracing::error!(error = %msg, "admin update failed");
1504            render(build(
1505                state,
1506                form,
1507                &action,
1508                Some(t!("Could not save. Check the values and try again.")),
1509                &data,
1510                &ErrorBag::default(),
1511                &shell,
1512            ))
1513        }
1514    }
1515}
1516
1517/// The 422 response for a failed save. An HTMX submit gets the form alone, which
1518/// replaces the form in place; anything else gets the whole page, so the admin
1519/// still works with scripting off.
1520#[allow(clippy::too_many_arguments)]
1521/// A form page posting to `action`, holding `values`: the shape another screen
1522/// borrows when it edits one thing a record owns, such as its tree parent.
1523pub(crate) fn page(
1524    state: &AdminState,
1525    form: &PreparedForm,
1526    action: &str,
1527    values: &HashMap<String, String>,
1528    shell: &crate::Shell,
1529) -> Response {
1530    render(build(
1531        state,
1532        form,
1533        action,
1534        None,
1535        values,
1536        &ErrorBag::default(),
1537        shell,
1538    ))
1539}
1540
1541/// The 422 for a submission the list's own checks refused, shaped like a
1542/// failed save: the form again with the messages against their fields.
1543#[allow(clippy::too_many_arguments)]
1544pub(crate) fn refused(
1545    htmx: bool,
1546    state: &AdminState,
1547    form: &PreparedForm,
1548    action: &str,
1549    error: Option<Text>,
1550    values: &HashMap<String, String>,
1551    bag: &ErrorBag,
1552    shell: &crate::Shell,
1553) -> Response {
1554    invalid_response(htmx, state, form, action, error, values, bag, shell)
1555}
1556
1557#[allow(clippy::too_many_arguments)]
1558fn invalid_response(
1559    htmx: bool,
1560    state: &AdminState,
1561    form: &PreparedForm,
1562    action: &str,
1563    error: Option<Text>,
1564    values: &HashMap<String, String>,
1565    bag: &ErrorBag,
1566    shell: &crate::Shell,
1567) -> Response {
1568    let page = build(state, form, action, error, values, bag, shell);
1569    let body = if htmx {
1570        render(FormFragment {
1571            shell: page.shell,
1572            action: page.action,
1573            cancel_path: page.cancel_path,
1574            error: page.error,
1575            fields: page.fields,
1576            stay: page.stay,
1577            enter_off: page.enter_off,
1578            refused: page.refused,
1579            leave_off: page.leave_off,
1580            focus: page.focus,
1581        })
1582    } else {
1583        render(page)
1584    };
1585    (StatusCode::UNPROCESSABLE_ENTITY, body).into_response()
1586}
1587
1588/// Where to send the browser after a successful save. HTMX will not follow a
1589/// 303 usefully (it would swap the redirected page into the form), so it gets
1590/// the header it understands instead.
1591pub(crate) fn saved_response(htmx: bool, to: &str) -> Response {
1592    if htmx {
1593        ([("HX-Redirect", to)], StatusCode::NO_CONTENT).into_response()
1594    } else {
1595        Redirect::to(to).into_response()
1596    }
1597}
1598
1599/// Whether this request came from HTMX rather than a plain form post.
1600pub(crate) fn is_htmx(headers: &axum::http::HeaderMap) -> bool {
1601    headers.contains_key("hx-request")
1602}
1603
1604fn build(
1605    state: &AdminState,
1606    form: &PreparedForm,
1607    action: &str,
1608    error: Option<Text>,
1609    values: &HashMap<String, String>,
1610    bag: &ErrorBag,
1611    shell: &crate::Shell,
1612) -> FormTemplate {
1613    let fields = form
1614        .config
1615        .fields
1616        .iter()
1617        .zip(&form.fields)
1618        .map(|(f, pf)| {
1619            let value = FieldValue::Text(values.get(&f.name).cloned().unwrap_or_default());
1620            let required = has_required(&pf.rules);
1621            // Localize the label once: the field type sees it (aria/inline labels)
1622            // and the framework chrome renders it.
1623            let label = shell.tt(&f.label);
1624            let cx = FieldCx {
1625                name: &f.name,
1626                id: &f.name,
1627                label: &label,
1628                value: &value,
1629                required,
1630                max_length: max_length(&pf.rules),
1631                opts: &pf.opts,
1632                base: &shell.base,
1633                i18n: shell.i18n(),
1634                icons: crate::icons::Icons::new(&shell.icon_set, &shell.sprite_url),
1635            };
1636            // The type is registered (prepare validated it); the lookup here is
1637            // only to render.
1638            let control = if f.hidden {
1639                format!(
1640                    r#"<input type="hidden" name="{}" value="{}">"#,
1641                    escape_attr(&f.name),
1642                    escape_attr(values.get(&f.name).map(String::as_str).unwrap_or_default())
1643                )
1644            } else {
1645                match state.field_types.get(&f.field_type) {
1646                    Some(ft) => {
1647                        let scope = OverrideScope {
1648                            surface: Surface::Field,
1649                            view_key: &f.field_type,
1650                            resource: Some(&form.config.base_path),
1651                            field: Some(&f.name),
1652                        };
1653                        render_field(ft.as_ref(), state.overrides.as_ref(), &scope, &cx)
1654                            .into_string()
1655                    }
1656                    None => String::new(),
1657                }
1658            };
1659            FieldView {
1660                id: f.name.clone(),
1661                label,
1662                control,
1663                required,
1664                enter: f.enter.attribute(),
1665                layout: layout_classes(f.span, f.break_row),
1666                attrs: behaviour_attrs(f),
1667                hidden: f.hidden,
1668                // Localize each per-field message through the request translator.
1669                errors: bag.messages(&f.name).iter().map(|m| shell.tt(m)).collect(),
1670            }
1671        })
1672        .collect();
1673    // Collect the widget assets the rendered field types declare, deduped and
1674    // resolved to URLs for the head. Most declare none (their widgets ship in
1675    // core laterite.js).
1676    let keys: Vec<&str> = form
1677        .config
1678        .fields
1679        .iter()
1680        .zip(&form.fields)
1681        .filter_map(|(f, pf)| {
1682            state
1683                .field_types
1684                .get(&f.field_type)
1685                .map(|ft| ft.assets(&pf.opts))
1686        })
1687        .flatten()
1688        .collect();
1689    // Localize the title and banner before the shell is moved into the template.
1690    let shell_title = shell.tt(&form.config.title);
1691    let refused = error.is_some() || !bag.is_empty();
1692    let error = error.map(|m| shell.tt(&m));
1693    let mut shell = shell.clone();
1694    shell.assets = crate::page_assets(&keys, &shell.base, &state.assets, &state.asset_urls);
1695    FormTemplate {
1696        shell,
1697        title: shell_title,
1698        action: action.to_string(),
1699        cancel_path: form
1700            .config
1701            .done_path
1702            .clone()
1703            .unwrap_or_else(|| form.config.base_path.clone()),
1704        error,
1705        fields,
1706        stay: form.stay,
1707        sections: Vec::new(),
1708        pending: Vec::new(),
1709        enter_off: form.config.enter == EnterPolicy::Off,
1710        refused,
1711        leave_off: !form.config.confirm_leave,
1712        focus: match form.config.focus {
1713            FormFocus::Off => "off",
1714            // A new record has nothing in it yet, so the first field is where
1715            // the operator starts. An edit opens for reading first.
1716            FormFocus::Auto if action.ends_with("/new") => "first",
1717            FormFocus::Auto => "",
1718        },
1719    }
1720}
1721
1722struct FieldView {
1723    /// DOM id for the control and its label's `for`.
1724    id: String,
1725    label: String,
1726    /// The control HTML, rendered by the field-type registry (override-aware).
1727    /// The framework owns the surrounding chrome (label, required marker, errors).
1728    control: String,
1729    required: bool,
1730    errors: Vec<String>,
1731    /// The field's own Enter rule (`off`, `next`), or empty for the form's.
1732    enter: &'static str,
1733    /// Wrapper classes for the span and a row break, each led by a space.
1734    layout: String,
1735    /// The wrapper's preset and trigger attributes, each led by a space.
1736    attrs: String,
1737    /// A hidden input with no chrome around it.
1738    hidden: bool,
1739}
1740
1741/// One relation on an edit page: its heading, its New link and the list region.
1742pub(crate) struct RelationSection {
1743    /// The section's toolbar: its title and the New or Attach button.
1744    pub toolbar: crate::html::Markup,
1745    pub html: crate::html::Markup,
1746}
1747
1748pub(crate) fn escape_attr(s: &str) -> String {
1749    s.replace('&', "&amp;")
1750        .replace('"', "&quot;")
1751        .replace('<', "&lt;")
1752        .replace('>', "&gt;")
1753}
1754
1755/// Just the form element, for an HTMX submit that failed validation: the
1756/// response replaces the form in place rather than reloading the page.
1757#[derive(Template)]
1758#[template(path = "_form_fields.html")]
1759struct FormFragment {
1760    shell: crate::Shell,
1761    action: String,
1762    cancel_path: String,
1763    error: Option<String>,
1764    fields: Vec<FieldView>,
1765    stay: bool,
1766    /// Enter never submits this form.
1767    enter_off: bool,
1768    /// The form holds a submission that was not saved.
1769    refused: bool,
1770    /// Leaving with changes unsaved does not ask.
1771    leave_off: bool,
1772    /// `first`, `off`, or empty for the default.
1773    focus: &'static str,
1774}
1775
1776#[derive(Template)]
1777#[template(path = "form.html")]
1778struct FormTemplate {
1779    shell: crate::Shell,
1780    title: String,
1781    action: String,
1782    cancel_path: String,
1783    error: Option<String>,
1784    fields: Vec<FieldView>,
1785    /// Offer "Save and continue editing".
1786    stay: bool,
1787    /// The related records, one section each, on an edit page.
1788    sections: Vec<RelationSection>,
1789    /// The relations a create page cannot show yet, by section title.
1790    pending: Vec<String>,
1791    /// Enter never submits this form.
1792    enter_off: bool,
1793    /// The form holds a submission that was not saved.
1794    refused: bool,
1795    /// Leaving with changes unsaved does not ask.
1796    leave_off: bool,
1797    /// `first`, `off`, or empty for the default.
1798    focus: &'static str,
1799}
1800
1801/// A field as a value form renders it: the label, the control its type drew,
1802/// the help, and the wrapper's layout classes and behaviour attributes.
1803pub struct ValueFieldView {
1804    pub label: String,
1805    /// The control's DOM id, which the label points at.
1806    pub id: String,
1807    pub help: Option<String>,
1808    /// The control, rendered by the field's own type.
1809    pub control: String,
1810    /// Wrapper classes for the span and a row break, each led by a space.
1811    pub layout: String,
1812    /// The wrapper's preset and trigger attributes, each led by a space.
1813    pub attrs: String,
1814}
1815
1816#[derive(Template)]
1817#[template(path = "_value_fields.html")]
1818struct ValueFieldsTemplate {
1819    fields: Vec<ValueFieldView>,
1820}
1821
1822/// A form over a JSON object: the declared fields rendered with their stored
1823/// values, and a submission collected back through the field types into an
1824/// object with every declared key. The settings screens are one, a theme's
1825/// settings another. Built from a [`RouteCtx`](crate::routes::RouteCtx) with
1826/// [`value_form`](crate::routes::RouteCtx::value_form).
1827pub struct ValueForm {
1828    fields: Vec<FormField>,
1829    types: Arc<crate::field::FieldRegistry>,
1830    overrides: Arc<dyn crate::field::OverrideResolver>,
1831    /// What an override is scoped to (a settings code, a theme code).
1832    scope: String,
1833}
1834
1835impl ValueForm {
1836    /// Checks every field's type is registered and its options resolve. The
1837    /// error names the field and the type, for a form declared at runtime.
1838    pub(crate) fn new(
1839        fields: &[FormField],
1840        types: Arc<crate::field::FieldRegistry>,
1841        overrides: Arc<dyn crate::field::OverrideResolver>,
1842        scope: &str,
1843    ) -> Result<Self, Text> {
1844        for field in fields {
1845            let Some(ft) = types.get(&field.field_type) else {
1846                return Err(Text::dynamic(format!(
1847                    "field {:?} uses unregistered type {:?}",
1848                    field.name, field.field_type
1849                )));
1850            };
1851            if ft.resolve_options(&field.options, &types).is_err() {
1852                return Err(Text::dynamic(format!(
1853                    "field {:?} has malformed options",
1854                    field.name
1855                )));
1856            }
1857        }
1858        Ok(Self {
1859            fields: fields.to_vec(),
1860            types,
1861            overrides,
1862            scope: scope.to_string(),
1863        })
1864    }
1865
1866    /// The fields, in order.
1867    pub fn fields(&self) -> &[FormField] {
1868        &self.fields
1869    }
1870
1871    /// Each field over `stored`, ready for a template.
1872    pub fn views(&self, stored: &serde_json::Value, shell: &crate::Shell) -> Vec<ValueFieldView> {
1873        value_views(
1874            &self.fields,
1875            &self.types,
1876            self.overrides.as_ref(),
1877            stored,
1878            shell,
1879            &self.scope,
1880        )
1881    }
1882
1883    /// The fields over `stored` as one `.lat-fields` block, for a form a screen
1884    /// builds by hand around it.
1885    pub fn render(&self, stored: &serde_json::Value, shell: &crate::Shell) -> crate::html::Markup {
1886        let template = ValueFieldsTemplate {
1887            fields: self.views(stored, shell),
1888        };
1889        crate::html::Markup::from_template(&template).unwrap_or_default()
1890    }
1891
1892    /// A submission as the stored object: every declared key, each value
1893    /// through its field type. A type that refuses its input refuses the whole.
1894    pub fn collect(&self, data: &HashMap<String, String>) -> Result<serde_json::Value, Text> {
1895        value_collect(&self.fields, &self.types, data)
1896    }
1897}
1898
1899/// Each of `fields` over `stored`, rendered by its type with overrides scoped
1900/// to `scope`.
1901pub(crate) fn value_views(
1902    fields: &[FormField],
1903    types: &crate::field::FieldRegistry,
1904    overrides: &dyn crate::field::OverrideResolver,
1905    stored: &serde_json::Value,
1906    shell: &crate::Shell,
1907    scope: &str,
1908) -> Vec<ValueFieldView> {
1909    fields
1910        .iter()
1911        .map(|f| {
1912            let label = shell.tt(&f.label);
1913            let control = match types.get(&f.field_type) {
1914                Some(ft) => {
1915                    let opts = ft
1916                        .resolve_options(&f.options, types)
1917                        .unwrap_or_else(|_| ResolvedOptions::none());
1918                    let value = match stored.get(&f.name) {
1919                        Some(serde_json::Value::Array(rows)) => {
1920                            FieldValue::Json(serde_json::Value::Array(rows.clone()))
1921                        }
1922                        Some(serde_json::Value::String(text)) => {
1923                            FieldValue::Text(ft.to_control(Some(text), &opts))
1924                        }
1925                        Some(serde_json::Value::Null) | None => {
1926                            FieldValue::Text(ft.to_control(None, &opts))
1927                        }
1928                        Some(other) => {
1929                            FieldValue::Text(ft.to_control(Some(&other.to_string()), &opts))
1930                        }
1931                    };
1932                    let cx = FieldCx {
1933                        name: &f.name,
1934                        id: &f.name,
1935                        label: &label,
1936                        value: &value,
1937                        required: false,
1938                        max_length: max_length(&f.rules),
1939                        opts: &opts,
1940                        base: &shell.base,
1941                        i18n: shell.i18n(),
1942                        icons: crate::icons::Icons::new(&shell.icon_set, &shell.sprite_url),
1943                    };
1944                    let scope = OverrideScope {
1945                        surface: Surface::Field,
1946                        view_key: &f.field_type,
1947                        resource: Some(scope),
1948                        field: Some(&f.name),
1949                    };
1950                    render_field(ft.as_ref(), overrides, &scope, &cx).into_string()
1951                }
1952                None => String::new(),
1953            };
1954            ValueFieldView {
1955                label,
1956                id: f.name.clone(),
1957                help: f.help.as_ref().map(|h| shell.tt(h)),
1958                control,
1959                layout: layout_classes(f.span, f.break_row),
1960                attrs: behaviour_attrs(f),
1961            }
1962        })
1963        .collect()
1964}
1965
1966/// A submission over `fields` as a JSON object with every declared key.
1967pub(crate) fn value_collect(
1968    fields: &[FormField],
1969    types: &crate::field::FieldRegistry,
1970    data: &HashMap<String, String>,
1971) -> Result<serde_json::Value, Text> {
1972    let mut object = serde_json::Map::new();
1973    for field in fields {
1974        let Some(field_type) = types.get(&field.field_type) else {
1975            return Err(t!("This screen uses a field type that is not registered."));
1976        };
1977        let opts = field_type
1978            .resolve_options(&field.options, types)
1979            .map_err(|_| t!("This screen has a malformed field."))?;
1980        let submitted = crate::field::SubmittedField::new(&field.name, data);
1981        let value = match field_type.to_attr(&submitted, &opts, Mode::Update) {
1982            Ok(Some(value)) => attr_to_json(value),
1983            Ok(None) => serde_json::Value::String(String::new()),
1984            Err(_) => return Err(t!("Check the values and try again.")),
1985        };
1986        object.insert(field.name.clone(), value);
1987    }
1988    Ok(serde_json::Value::Object(object))
1989}
1990
1991/// A field type's attribute value as settings JSON stores it.
1992pub(crate) fn attr_to_json(value: laterite_core::AttrValue) -> serde_json::Value {
1993    use laterite_core::AttrValue;
1994    match value {
1995        AttrValue::Null => serde_json::Value::String(String::new()),
1996        AttrValue::Bool(b) => serde_json::Value::Bool(b),
1997        AttrValue::Int(i) => serde_json::Value::from(i),
1998        AttrValue::Float(f) => serde_json::Value::from(f),
1999        AttrValue::Json(j) => j,
2000        other => serde_json::Value::String(other.to_text().unwrap_or_default()),
2001    }
2002}
2003
2004#[cfg(test)]
2005mod tests {
2006    use super::*;
2007    use axum::http::StatusCode;
2008    use laterite_core::strata::{
2009        async_trait, ColumnDef, CoreResult, Migration, MigrationSet, Schema, Table,
2010    };
2011    use laterite_core::testing::{connect_test, TestGuard};
2012    use laterite_core::Db;
2013    use laterite_core::SaveCx;
2014
2015    /// A minimal table for exercising the generic insert/update path in isolation,
2016    /// defined as a portable migration so the test runs on any backend.
2017    struct CreateSamples;
2018    #[async_trait(?Send)]
2019    impl Migration for CreateSamples {
2020        fn name(&self) -> &str {
2021            "0001_create_samples"
2022        }
2023        async fn up(&self, s: &mut Schema<'_>) -> CoreResult<()> {
2024            s.exec(
2025                Table::create()
2026                    .table(Alias::new("samples"))
2027                    .if_not_exists()
2028                    .col(
2029                        ColumnDef::new(Alias::new("id"))
2030                            .big_integer()
2031                            .not_null()
2032                            .auto_increment()
2033                            .primary_key(),
2034                    )
2035                    .col(ColumnDef::new(Alias::new("code")).text().not_null())
2036                    .col(ColumnDef::new(Alias::new("name")).text().not_null())
2037                    // Nullable, so a form that does not opt into timestamps
2038                    // still inserts.
2039                    .col(ColumnDef::new(Alias::new("created_at")).text())
2040                    .col(ColumnDef::new(Alias::new("updated_at")).text())
2041                    .to_owned(),
2042            )
2043            .await
2044        }
2045    }
2046
2047    fn config() -> PreparedForm {
2048        let config = FormConfig {
2049            enter: Default::default(),
2050            confirm_leave: true,
2051            focus: Default::default(),
2052            entity: "samples".to_string(),
2053            title: "Sample".into(),
2054            base_path: "/admin/samples".to_string(),
2055            id_field: "id".to_string(),
2056            fields: vec![
2057                FormField::text("code", "Code").required().unique(),
2058                FormField::text("name", "Name").required(),
2059            ],
2060            persist: None,
2061            timestamps: false,
2062            done_path: None,
2063        };
2064        PreparedForm::prepare(
2065            config,
2066            &crate::field::builtin_registry(),
2067            &PersisterRegistry::new(),
2068            &[],
2069        )
2070        .unwrap()
2071    }
2072
2073    /// The whole delete path against a real table: the row is read, the
2074    /// listeners run, the row goes, and the after-stage sees what went.
2075    #[tokio::test]
2076    async fn a_delete_removes_the_row_through_the_pipeline() {
2077        use crate::persist::{delete, DefaultPersister, DeleteRequest};
2078
2079        let (db, _guard) = test_db().await;
2080        let st = state(db.clone());
2081        let form = config();
2082
2083        let mut data = HashMap::new();
2084        data.insert("code".to_string(), "c1".to_string());
2085        data.insert("name".to_string(), "Chair".to_string());
2086        create(
2087            &st,
2088            &form,
2089            data,
2090            crate::Shell::test(),
2091            &crate::audit::test_actor(),
2092            &crate::session::SessionHandle::from_blob(None),
2093            &axum::http::HeaderMap::new(),
2094        )
2095        .await;
2096        assert_eq!(
2097            fetch_text(&db, "name", "c1").await.as_deref(),
2098            Some("Chair")
2099        );
2100
2101        let id = row_id(&db, "c1").await;
2102        let persister = DefaultPersister::from_config(&form.config);
2103        let rec = delete(DeleteRequest {
2104            db: &db,
2105            listeners: &[],
2106            persister: &persister,
2107            actor: &laterite_core::Actor::system("test"),
2108            entity: "samples",
2109            id: &id,
2110        })
2111        .await
2112        .expect("deleted");
2113
2114        // Gone from the table, and the caller learns what it removed.
2115        assert_eq!(fetch_text(&db, "name", "c1").await, None);
2116        assert_eq!(rec.text("code"), Some("c1"));
2117    }
2118
2119    /// The stored id for a row, as text, the shape the delete path takes.
2120    async fn row_id(db: &Db, code: &str) -> String {
2121        let stmt = Query::select()
2122            .expr_as(
2123                Expr::col(Alias::new("id")).cast_as(Alias::new(text_cast(db.backend))),
2124                Alias::new("v"),
2125            )
2126            .from(Alias::new("samples"))
2127            .and_where(Expr::col(Alias::new("code")).eq(code))
2128            .to_owned();
2129        let (sql, values) = laterite_core::query::build(db.backend, stmt);
2130        let row = bind_values(sqlx::query(&sql), values)
2131            .fetch_one(&db.pool)
2132            .await
2133            .unwrap();
2134        row.get_text("v").unwrap()
2135    }
2136
2137    pub(super) fn state(db: Db) -> AdminState {
2138        AdminState::new(
2139            laterite_auth::AuthService::new(db.clone(), laterite_auth::AuthConfig::default()),
2140            db,
2141        )
2142    }
2143
2144    /// A fresh test database holding a minimal `samples` table, on whichever
2145    /// backend the run targets. Hold the returned guard for the test's lifetime.
2146    pub(super) async fn test_db() -> (Db, TestGuard) {
2147        let samples = MigrationSet::new("test.samples", vec![Box::new(CreateSamples)]);
2148        connect_test(&[samples]).await
2149    }
2150
2151    /// Reads a single text column from the one row matching `code`, so a test can
2152    /// assert what was persisted without depending on the read path under test.
2153    pub(super) async fn fetch_text(db: &Db, column: &str, code: &str) -> Option<String> {
2154        let stmt = Query::select()
2155            .expr_as(
2156                Expr::col(Alias::new(column)).cast_as(Alias::new(text_cast(db.backend))),
2157                Alias::new("v"),
2158            )
2159            .from(Alias::new("samples"))
2160            .and_where(Expr::col(Alias::new("code")).eq(code))
2161            .to_owned();
2162        let (sql, values) = to_sql(db.backend, stmt);
2163        let row = bind_values(sqlx::query(&sql), values)
2164            .fetch_optional(&db.pool)
2165            .await
2166            .unwrap()?;
2167        row.get_text_opt("v").ok().flatten()
2168    }
2169
2170    async fn body_of(resp: Response) -> String {
2171        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
2172            .await
2173            .unwrap();
2174        String::from_utf8(bytes.to_vec()).unwrap()
2175    }
2176
2177    async fn count(db: &Db) -> i64 {
2178        sqlx::query_scalar("select count(*) from samples")
2179            .fetch_one(&db.pool)
2180            .await
2181            .unwrap()
2182    }
2183
2184    fn data(pairs: &[(&str, &str)]) -> HashMap<String, String> {
2185        pairs
2186            .iter()
2187            .map(|(k, v)| (k.to_string(), v.to_string()))
2188            .collect()
2189    }
2190
2191    /// The header htmx sets on every request it makes.
2192    pub(super) fn htmx_headers() -> axum::http::HeaderMap {
2193        let mut h = axum::http::HeaderMap::new();
2194        h.insert("hx-request", "true".parse().unwrap());
2195        h
2196    }
2197
2198    #[tokio::test]
2199    async fn create_then_fetch() {
2200        let (db, _guard) = test_db().await;
2201        let cfg = config();
2202        let st = state(db.clone());
2203
2204        let resp = create(
2205            &st,
2206            &cfg,
2207            data(&[("code", "editor"), ("name", "Content Editor")]),
2208            crate::Shell::test(),
2209            &crate::audit::test_actor(),
2210            &crate::session::SessionHandle::from_blob(None),
2211            &axum::http::HeaderMap::new(),
2212        )
2213        .await;
2214        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
2215
2216        assert_eq!(
2217            fetch_text(&db, "name", "editor").await.as_deref(),
2218            Some("Content Editor")
2219        );
2220    }
2221
2222    #[tokio::test]
2223    async fn update_changes_the_row() {
2224        let (db, _guard) = test_db().await;
2225        let cfg = config();
2226        let st = state(db.clone());
2227        create(
2228            &st,
2229            &cfg,
2230            data(&[("code", "editor"), ("name", "Editor")]),
2231            crate::Shell::test(),
2232            &crate::audit::test_actor(),
2233            &crate::session::SessionHandle::from_blob(None),
2234            &axum::http::HeaderMap::new(),
2235        )
2236        .await;
2237
2238        let id = fetch_text(&db, "id", "editor")
2239            .await
2240            .expect("row should exist after create");
2241
2242        // The code is unchanged, so its unique rule must ignore the edited row.
2243        let resp = update(
2244            &st,
2245            &cfg,
2246            id,
2247            data(&[("code", "editor"), ("name", "Senior Editor")]),
2248            crate::Shell::test(),
2249            &crate::audit::test_actor(),
2250            &crate::session::SessionHandle::from_blob(None),
2251            &axum::http::HeaderMap::new(),
2252        )
2253        .await;
2254        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
2255
2256        assert_eq!(
2257            fetch_text(&db, "name", "editor").await.as_deref(),
2258            Some("Senior Editor")
2259        );
2260    }
2261
2262    #[tokio::test]
2263    async fn create_re_renders_with_a_required_message_and_inserts_nothing() {
2264        let (db, _guard) = test_db().await;
2265        let cfg = config();
2266        let st = state(db.clone());
2267
2268        let resp = create(
2269            &st,
2270            &cfg,
2271            data(&[("code", ""), ("name", "No Code")]),
2272            crate::Shell::test(),
2273            &crate::audit::test_actor(),
2274            &crate::session::SessionHandle::from_blob(None),
2275            &axum::http::HeaderMap::new(),
2276        )
2277        .await;
2278        // Re-renders the form (200), does not redirect.
2279        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
2280        assert_eq!(count(&db).await, 0);
2281        // The per-field message is rendered.
2282        assert!(body_of(resp).await.contains("Code is required."));
2283    }
2284
2285    #[tokio::test]
2286    async fn create_rejects_a_duplicate_unique_value() {
2287        let (db, _guard) = test_db().await;
2288        let cfg = config();
2289        let st = state(db.clone());
2290        create(
2291            &st,
2292            &cfg,
2293            data(&[("code", "editor"), ("name", "Editor")]),
2294            crate::Shell::test(),
2295            &crate::audit::test_actor(),
2296            &crate::session::SessionHandle::from_blob(None),
2297            &axum::http::HeaderMap::new(),
2298        )
2299        .await;
2300
2301        // A second row with the same code is refused by the unique rule.
2302        let resp = create(
2303            &st,
2304            &cfg,
2305            data(&[("code", "editor"), ("name", "Other")]),
2306            crate::Shell::test(),
2307            &crate::audit::test_actor(),
2308            &crate::session::SessionHandle::from_blob(None),
2309            &axum::http::HeaderMap::new(),
2310        )
2311        .await;
2312        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
2313        assert_eq!(count(&db).await, 1);
2314        assert!(body_of(resp).await.contains("already taken"));
2315    }
2316
2317    #[tokio::test]
2318    async fn text_email_input_rejects_a_bad_address_via_its_intrinsic_rule() {
2319        let (db, _guard) = test_db().await;
2320        let st = state(db.clone());
2321        // The `name` column is a text field with the `email` input, which
2322        // contributes Rule::Email without the descriptor listing it.
2323        let cfg = PreparedForm::prepare(
2324            FormConfig {
2325                enter: Default::default(),
2326                confirm_leave: true,
2327                focus: Default::default(),
2328                entity: "samples".to_string(),
2329                title: "Sample".into(),
2330                base_path: "/admin/samples".to_string(),
2331                id_field: "id".to_string(),
2332                fields: vec![
2333                    FormField::text("code", "Code").required(),
2334                    FormField::of("name", "Email", "text")
2335                        .options(serde_json::json!({ "input": "email" }))
2336                        .required(),
2337                ],
2338                persist: None,
2339                timestamps: false,
2340                done_path: None,
2341            },
2342            &st.field_types,
2343            &PersisterRegistry::new(),
2344            &[],
2345        )
2346        .unwrap();
2347
2348        let resp = create(
2349            &st,
2350            &cfg,
2351            data(&[("code", "c1"), ("name", "nope")]),
2352            crate::Shell::test(),
2353            &crate::audit::test_actor(),
2354            &crate::session::SessionHandle::from_blob(None),
2355            &axum::http::HeaderMap::new(),
2356        )
2357        .await;
2358        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
2359        assert_eq!(count(&db).await, 0);
2360
2361        let resp = create(
2362            &st,
2363            &cfg,
2364            data(&[("code", "c1"), ("name", "a@b.test")]),
2365            crate::Shell::test(),
2366            &crate::audit::test_actor(),
2367            &crate::session::SessionHandle::from_blob(None),
2368            &axum::http::HeaderMap::new(),
2369        )
2370        .await;
2371        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
2372        assert_eq!(count(&db).await, 1);
2373    }
2374
2375    #[test]
2376    fn prepare_rejects_an_unregistered_field_type() {
2377        let config = FormConfig {
2378            enter: Default::default(),
2379            confirm_leave: true,
2380            focus: Default::default(),
2381            entity: "samples".to_string(),
2382            title: "Sample".into(),
2383            base_path: "/admin/samples".to_string(),
2384            id_field: "id".to_string(),
2385            fields: vec![FormField::of("place", "Place", "no.such.type")],
2386            persist: None,
2387            timestamps: false,
2388            done_path: None,
2389        };
2390        let Err(err) = PreparedForm::prepare(
2391            config,
2392            &crate::field::builtin_registry(),
2393            &PersisterRegistry::new(),
2394            &[],
2395        ) else {
2396            panic!("expected prepare to reject an unregistered type");
2397        };
2398        assert!(err.contains("no.such.type"), "{err}");
2399    }
2400
2401    #[test]
2402    fn prepare_rejects_a_malformed_option() {
2403        // The text field's `input` option is a string; a wrong JSON type for it
2404        // aborts prepare naming the field.
2405        let config = FormConfig {
2406            enter: Default::default(),
2407            confirm_leave: true,
2408            focus: Default::default(),
2409            entity: "samples".to_string(),
2410            title: "Sample".into(),
2411            base_path: "/admin/samples".to_string(),
2412            id_field: "id".to_string(),
2413            fields: vec![
2414                FormField::of("email", "Email", "text").options(serde_json::json!({ "input": 7 }))
2415            ],
2416            persist: None,
2417            timestamps: false,
2418            done_path: None,
2419        };
2420        let Err(err) = PreparedForm::prepare(
2421            config,
2422            &crate::field::builtin_registry(),
2423            &PersisterRegistry::new(),
2424            &[],
2425        ) else {
2426            panic!("expected prepare to reject a malformed option");
2427        };
2428        assert!(err.contains("`email`"), "{err}");
2429    }
2430
2431    /// A persister that inserts a row then fails. The pipeline owns the
2432    /// transaction, so the insert must roll back with it.
2433    struct RollbackPersister;
2434    #[laterite_core::strata::async_trait]
2435    impl Persister for RollbackPersister {
2436        async fn create(&self, cx: &mut SaveCx<'_>, _rec: &Record) -> Result<i64, SaveError> {
2437            let backend = cx.backend();
2438            let insert = Query::insert()
2439                .into_table(Alias::new("samples"))
2440                .columns([Alias::new("code"), Alias::new("name")])
2441                .values_panic(["rolled".into(), "back".into()])
2442                .to_owned();
2443            let (sql, values) = to_sql(backend, insert);
2444            bind_values(sqlx::query(&sql), values)
2445                .execute(cx.conn())
2446                .await
2447                .map_err(|e| SaveError::Failed(e.to_string()))?;
2448            Err(SaveError::Failed("deliberate".to_string()))
2449        }
2450        async fn update(
2451            &self,
2452            _cx: &mut SaveCx<'_>,
2453            _id: &str,
2454            _rec: &Record,
2455        ) -> Result<(), SaveError> {
2456            Ok(())
2457        }
2458    }
2459
2460    /// A persister that always rejects create with a per-field validation error.
2461    struct RejectingPersister;
2462    #[laterite_core::strata::async_trait]
2463    impl Persister for RejectingPersister {
2464        async fn create(&self, _cx: &mut SaveCx<'_>, _rec: &Record) -> Result<i64, SaveError> {
2465            let mut bag = ErrorBag::default();
2466            bag.add("code", t!("Code is not allowed here."));
2467            Err(SaveError::Invalid(bag))
2468        }
2469        async fn update(
2470            &self,
2471            _cx: &mut SaveCx<'_>,
2472            _id: &str,
2473            _rec: &Record,
2474        ) -> Result<(), SaveError> {
2475            Ok(())
2476        }
2477    }
2478
2479    fn config_with(persister: &str) -> FormConfig {
2480        FormConfig {
2481            enter: Default::default(),
2482            confirm_leave: true,
2483            focus: Default::default(),
2484            entity: "samples".to_string(),
2485            title: "Sample".into(),
2486            base_path: "/admin/samples".to_string(),
2487            id_field: "id".to_string(),
2488            fields: vec![
2489                FormField::text("code", "Code").required(),
2490                FormField::text("name", "Name").required(),
2491            ],
2492            persist: Some(persister.to_string()),
2493            timestamps: false,
2494            done_path: None,
2495        }
2496    }
2497
2498    #[test]
2499    fn prepare_rejects_an_unregistered_persister() {
2500        let Err(err) = PreparedForm::prepare(
2501            config_with("no.such.persister"),
2502            &crate::field::builtin_registry(),
2503            &PersisterRegistry::new(),
2504            &[],
2505        ) else {
2506            panic!("expected prepare to reject an unregistered persister");
2507        };
2508        assert!(err.contains("no.such.persister"), "{err}");
2509    }
2510
2511    #[tokio::test]
2512    async fn a_persister_transaction_rolls_back_on_error() {
2513        let (db, _guard) = test_db().await;
2514        let st = state(db.clone());
2515        let mut persisters = PersisterRegistry::new();
2516        persisters.insert("test.rollback".to_string(), Arc::new(RollbackPersister));
2517        let form = PreparedForm::prepare(
2518            config_with("test.rollback"),
2519            &st.field_types,
2520            &persisters,
2521            &[],
2522        )
2523        .unwrap();
2524
2525        let resp = create(
2526            &st,
2527            &form,
2528            data(&[("code", "rolled"), ("name", "back")]),
2529            crate::Shell::test(),
2530            &crate::audit::test_actor(),
2531            &crate::session::SessionHandle::from_blob(None),
2532            &axum::http::HeaderMap::new(),
2533        )
2534        .await;
2535        // The persister failed, so the form re-renders (200) and its in-tx insert
2536        // rolled back: no row landed.
2537        assert_eq!(resp.status(), StatusCode::OK);
2538        assert_eq!(count(&db).await, 0);
2539    }
2540
2541    #[tokio::test]
2542    async fn a_persister_invalid_error_re_renders_422() {
2543        let (db, _guard) = test_db().await;
2544        let st = state(db.clone());
2545        let mut persisters = PersisterRegistry::new();
2546        persisters.insert("test.reject".to_string(), Arc::new(RejectingPersister));
2547        let form = PreparedForm::prepare(
2548            config_with("test.reject"),
2549            &st.field_types,
2550            &persisters,
2551            &[],
2552        )
2553        .unwrap();
2554
2555        let resp = create(
2556            &st,
2557            &form,
2558            data(&[("code", "editor"), ("name", "Editor")]),
2559            crate::Shell::test(),
2560            &crate::audit::test_actor(),
2561            &crate::session::SessionHandle::from_blob(None),
2562            &axum::http::HeaderMap::new(),
2563        )
2564        .await;
2565        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
2566        assert!(body_of(resp).await.contains("Code is not allowed here."));
2567    }
2568}
2569
2570#[cfg(test)]
2571mod timestamp_tests {
2572    use super::tests::*;
2573    use super::*;
2574    use laterite_core::listeners::{CREATED_AT, UPDATED_AT};
2575    use laterite_core::Actor;
2576
2577    fn timestamped(on: bool) -> FormConfig {
2578        FormConfig {
2579            enter: Default::default(),
2580            confirm_leave: true,
2581            focus: Default::default(),
2582            entity: "samples".to_string(),
2583            title: "Sample".into(),
2584            base_path: "/admin/samples".to_string(),
2585            id_field: "id".to_string(),
2586            fields: vec![
2587                FormField::text("code", "Code").required(),
2588                FormField::text("name", "Name").required(),
2589            ],
2590            persist: None,
2591            timestamps: on,
2592            done_path: None,
2593        }
2594    }
2595
2596    async fn create_through_pipeline(db: &laterite_core::Db, on: bool) -> Record {
2597        let form = PreparedForm::prepare(
2598            timestamped(on),
2599            &crate::field::builtin_registry(),
2600            &PersisterRegistry::new(),
2601            &[],
2602        )
2603        .unwrap();
2604        let mut data = HashMap::new();
2605        data.insert("code".to_string(), "c1".to_string());
2606        data.insert("name".to_string(), "Chair".to_string());
2607        let mut rec = declared_record(&form, &data, Mode::Create).unwrap();
2608        let actor = Actor::system("test");
2609        persist::save(
2610            persist::SaveRequest {
2611                db,
2612                listeners: &form.listeners,
2613                persister: form.persister.as_ref(),
2614                actor: &actor,
2615                op: Op::Create,
2616                id: None,
2617            },
2618            &mut rec,
2619        )
2620        .await
2621        .expect("the insert should succeed");
2622        rec
2623    }
2624
2625    #[tokio::test]
2626    async fn opting_in_stamps_the_row() {
2627        let (db, _guard) = test_db().await;
2628        let rec = create_through_pipeline(&db, true).await;
2629        assert!(rec.datetime(CREATED_AT).is_some());
2630        assert!(rec.datetime(UPDATED_AT).is_some());
2631        // The stamp reached the table, not just the record.
2632        assert!(fetch_text(&db, CREATED_AT, "c1").await.is_some());
2633    }
2634
2635    #[tokio::test]
2636    async fn leaving_it_off_writes_no_timestamps() {
2637        let (db, _guard) = test_db().await;
2638        let rec = create_through_pipeline(&db, false).await;
2639        assert!(rec.get(CREATED_AT).is_none());
2640        assert_eq!(fetch_text(&db, CREATED_AT, "c1").await, None);
2641    }
2642}
2643
2644#[cfg(test)]
2645mod htmx_tests {
2646    use super::tests::*;
2647    use super::*;
2648    use axum::http::StatusCode;
2649
2650    /// A submission missing a required field, so validation refuses it.
2651    fn invalid() -> HashMap<String, String> {
2652        let mut d = HashMap::new();
2653        d.insert("code".to_string(), String::new());
2654        d.insert("name".to_string(), "No code".to_string());
2655        d
2656    }
2657
2658    fn valid() -> HashMap<String, String> {
2659        let mut d = HashMap::new();
2660        d.insert("code".to_string(), "c1".to_string());
2661        d.insert("name".to_string(), "Chair".to_string());
2662        d
2663    }
2664
2665    async fn post(data: HashMap<String, String>, headers: axum::http::HeaderMap) -> Response {
2666        let (db, _guard) = test_db().await;
2667        let st = state(db);
2668        let form = PreparedForm::prepare(
2669            FormConfig {
2670                enter: Default::default(),
2671                confirm_leave: true,
2672                focus: Default::default(),
2673                entity: "samples".to_string(),
2674                title: "Sample".into(),
2675                base_path: "/admin/samples".to_string(),
2676                id_field: "id".to_string(),
2677                fields: vec![
2678                    FormField::text("code", "Code").required(),
2679                    FormField::text("name", "Name").required(),
2680                ],
2681                persist: None,
2682                timestamps: false,
2683                done_path: None,
2684            },
2685            &st.field_types,
2686            &PersisterRegistry::new(),
2687            &[],
2688        )
2689        .unwrap();
2690        create(
2691            &st,
2692            &form,
2693            data,
2694            crate::Shell::test(),
2695            &crate::audit::test_actor(),
2696            &crate::session::SessionHandle::from_blob(None),
2697            &headers,
2698        )
2699        .await
2700    }
2701
2702    async fn body_of(resp: Response) -> String {
2703        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
2704            .await
2705            .unwrap();
2706        String::from_utf8(bytes.to_vec()).unwrap()
2707    }
2708
2709    #[tokio::test]
2710    async fn an_htmx_submit_that_fails_returns_the_form_alone() {
2711        let resp = post(invalid(), htmx_headers()).await;
2712        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
2713        let html = body_of(resp).await;
2714        assert!(html.contains("<form"), "the form comes back");
2715        assert!(html.contains("lat-field__error"), "with its errors");
2716        // A fragment, not a page: swapping a whole document into the form would
2717        // nest the admin inside itself.
2718        assert!(!html.contains("<body"), "no page chrome");
2719    }
2720
2721    #[tokio::test]
2722    async fn a_plain_submit_that_fails_returns_the_whole_page() {
2723        let resp = post(invalid(), axum::http::HeaderMap::new()).await;
2724        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
2725        let html = body_of(resp).await;
2726        assert!(html.contains("<body"), "the admin still works without htmx");
2727        assert!(html.contains("lat-field__error"));
2728    }
2729
2730    #[tokio::test]
2731    async fn an_htmx_submit_that_succeeds_redirects_by_header() {
2732        let resp = post(valid(), htmx_headers()).await;
2733        // htmx cannot follow a 303 usefully; it reads this header instead.
2734        assert_eq!(resp.status(), StatusCode::NO_CONTENT);
2735        assert_eq!(resp.headers().get("HX-Redirect").unwrap(), "/admin/samples");
2736    }
2737
2738    #[tokio::test]
2739    async fn a_plain_submit_that_succeeds_still_redirects() {
2740        let resp = post(valid(), axum::http::HeaderMap::new()).await;
2741        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
2742    }
2743}