umbral-admin 0.0.12

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

use std::collections::HashMap;

use axum::extract::{Path, State};
use minijinja::context;
use umbral::web::{HeaderMap, IntoResponse, Redirect, Response, StatusCode};

use umbral::orm::DynQuerySet;

use crate::AdminState;
use crate::auth::require_staff;
use crate::discovery::{find_model, pk_column, user_theme};
use crate::engine::render;
use crate::error::AdminError;
use crate::handlers::sheet::edit_sheet_handler;
use crate::rows::{fetch_rows_filtered, insert_row_in_tx, update_row_in_tx};
use crate::util::{
    apply_write_error_to_fields, is_htmx, parse_unique_violation_column, sanitise_form_error,
};
use crate::view::{
    form_fields_for, form_m2m_fields_for, model_for_template, sidebar_apps, validate_form,
};

/// Decode a request body into ordered `(field, value)` pairs, handling
/// both urlencoded and `multipart/form-data` admin POSTs (Wave 4).
///
/// For multipart bodies the file parts are stored through the ambient
/// Storage backend and their values become the returned storage keys —
/// the exact same flat shape `serde_urlencoded::from_str` yields, so the
/// caller's `HashMap` (last-wins) and `Vec` (repeated M2M values) builds
/// are unchanged. Empty file parts are skipped by
/// `parse_and_store_multipart`, so an edit that doesn't re-pick a file
/// simply omits that column (update preserves the existing key).
///
/// Returns an `AdminError` on a malformed body or a storage failure,
/// mirroring the urlencoded `BadInput` path the handlers used before.
pub(crate) async fn body_to_pairs(
    content_type: &str,
    body: axum::body::Bytes,
) -> Result<Vec<(String, String)>, AdminError> {
    if umbral::web::is_multipart(content_type) {
        umbral::web::parse_and_store_multipart(content_type, body)
            .await
            .map_err(|e| AdminError::BadInput(e.to_string()))
    } else {
        let s = String::from_utf8(body.to_vec())
            .map_err(|_| AdminError::BadInput("request body was not valid UTF-8".to_string()))?;
        serde_urlencoded::from_str(&s).map_err(|e| AdminError::BadInput(e.to_string()))
    }
}

/// Cross-module wrapper used by the sheet handler — keeps
/// `apply_m2m_selections` private to this file while still letting
/// `handlers::sheet::sheet_create` reuse the same write path.
pub(crate) async fn apply_m2m_selections_pub(
    parent: &umbral::migrate::ModelMeta,
    parent_pk_str: &str,
    multi_form: &[(String, String)],
) -> Result<(), sqlx::Error> {
    apply_m2m_selections(parent, parent_pk_str, multi_form).await
}

/// Persist M2M field selections for a parent row, one
/// `set_junction_dynamic` call per `Model::M2M_RELATIONS` entry.
///
/// Walks `parent.m2m_relations` (the ModelMeta mirror of
/// `Model::M2M_RELATIONS`), extracts every checked candidate from the
/// form's repeated `m2m_<field>` values, parses the parent + child
/// PKs through `form_str_to_sea_value` so the bind types match the
/// junction's column types, and replaces the junction's existing
/// rows for this parent inside a single transaction.
///
/// Called by `create` (after INSERT) and `update` (after UPDATE).
/// No-op when the parent has no M2M relations or the form has no
/// `m2m_*` entries.
async fn apply_m2m_selections(
    parent: &umbral::migrate::ModelMeta,
    parent_pk_str: &str,
    multi_form: &[(String, String)],
) -> Result<(), sqlx::Error> {
    // Standalone entry (the sheet-create flow): wrap the tx-aware core in its
    // own transaction. The admin change form folds M2M into the PARENT tx via
    // `apply_m2m_selections_in_tx` instead — see `save_parent_and_inlines`.
    let mut tx = umbral::db::begin().await?;
    apply_m2m_selections_in_tx(parent, parent_pk_str, multi_form, &mut tx).await?;
    tx.commit().await?;
    Ok(())
}

/// gaps4 #14: apply the form's M2M selections on an EXISTING transaction, so
/// they commit or roll back with the parent + inline writes as one unit. The
/// admin change form used to save the parent in a tx, commit, then write M2M in
/// a second tx — a failure there left the parent updated but the relations not,
/// an observable partial write with no clean rollback.
async fn apply_m2m_selections_in_tx(
    parent: &umbral::migrate::ModelMeta,
    parent_pk_str: &str,
    multi_form: &[(String, String)],
    tx: &mut umbral::db::Transaction,
) -> Result<(), sqlx::Error> {
    if parent.m2m_relations.is_empty() {
        return Ok(());
    }
    let Some(parent_pk_col) = parent.fields.iter().find(|c| c.primary_key) else {
        return Ok(());
    };
    // Parse the parent PK once — same value binds against every
    // junction's `parent_id` column for this row.
    let parent_value = match umbral::orm::write::json_to_sea_value(
        parent_pk_col.ty,
        &serde_json::Value::String(parent_pk_str.to_string()),
        false,
        &parent_pk_col.name,
        None,
    ) {
        Ok(v) => v,
        Err(_) => return Ok(()),
    };
    for rel in &parent.m2m_relations {
        let field_key = format!("m2m_{}", rel.field_name);
        let raw_child_values: Vec<&str> = multi_form
            .iter()
            .filter_map(|(k, v)| {
                if k == &field_key {
                    Some(v.as_str())
                } else {
                    None
                }
            })
            .filter(|v| !v.is_empty())
            .collect();
        // Look up the child's PK column to dispatch the bind type.
        let Some(target) = umbral::migrate::registered_models()
            .into_iter()
            .find(|m| m.table == rel.target_table)
        else {
            continue;
        };
        let Some(child_pk_col) = target.fields.iter().find(|c| c.primary_key) else {
            continue;
        };
        let mut child_values = Vec::with_capacity(raw_child_values.len());
        for raw in raw_child_values {
            match umbral::orm::write::json_to_sea_value(
                child_pk_col.ty,
                &serde_json::Value::String(raw.to_string()),
                false,
                &child_pk_col.name,
                None,
            ) {
                Ok(v) => child_values.push(v),
                Err(_) => continue,
            }
        }
        let junction_table = format!("{}_{}", parent.table, rel.field_name);
        umbral::orm::set_junction_dynamic_in_tx(
            &junction_table,
            parent_value.clone(),
            child_values,
            tx,
        )
        .await?;
    }
    Ok(())
}

/// `GET /admin/{table}/{id}` — read-only detail page.
pub(crate) async fn detail(
    State(state): State<AdminState>,
    headers: HeaderMap,
    Path((table, id)): Path<(String, String)>,
) -> Response {
    let path = format!("{}/{table}/{id}", crate::branding::current().base_path);
    let user = match require_staff(&headers, &path).await {
        Ok(u) => u,
        Err(r) => return r,
    };
    let Some((plugin_name, model)) = find_model(&table) else {
        return AdminError::NotFound(format!("no model with table `{table}`")).into_response();
    };
    if let Err(r) =
        crate::permcheck::require(&user, &plugin_name, &table, crate::permcheck::Action::View).await
    {
        return r;
    }
    let perms = crate::permcheck::AdminPerms::load(&user, &plugin_name, &table).await;
    let Some(pk) = pk_column(&model) else {
        return AdminError::Render(format!("model `{table}` has no primary key")).into_response();
    };
    let all_cols: Vec<String> = model.fields.iter().map(|f| f.name.clone()).collect();
    let rows = match fetch_rows_filtered(&model, (&pk.name, &id), &all_cols).await {
        Ok(r) => r,
        Err(e) => return e.into_response(),
    };
    let Some(row) = rows.into_iter().next() else {
        return AdminError::NotFound(format!("no row with {} = {}", pk.name, id)).into_response();
    };
    let apps = sidebar_apps(&state, &user).await;
    let breadcrumbs = vec![
        serde_json::json!({ "label": model.name.clone(), "url": format!("{}/{table}/", crate::branding::current().base_path) }),
        serde_json::json!({ "label": format!("#{id}"), "url": format!("{}/{table}/{id}", crate::branding::current().base_path) }),
    ];
    let initial_theme = user_theme(&user).await;
    match render(
        "admin/detail.html",
        context!(
            user          => user.username.clone(),
            model         => model_for_template(&model),
            row           => row,
            pk            => pk.name.clone(),
            apps          => apps,
            active_table  => table,
            breadcrumbs   => breadcrumbs,
            initial_theme => initial_theme,
            perms         => perms,
        ),
    ) {
        Ok(html) => html.into_response(),
        Err(e) => e.into_response(),
    }
}

/// `GET /admin/{table}/new` — empty create form.
pub(crate) async fn new_form(
    State(state): State<AdminState>,
    headers: HeaderMap,
    Path(table): Path<String>,
) -> Response {
    let path = format!("{}/{table}/new", crate::branding::current().base_path);
    let user = match require_staff(&headers, &path).await {
        Ok(u) => u,
        Err(r) => return r,
    };
    let Some((plugin_name, model)) = find_model(&table) else {
        return AdminError::NotFound(format!("no model with table `{table}`")).into_response();
    };
    if let Err(r) =
        crate::permcheck::require(&user, &plugin_name, &table, crate::permcheck::Action::Add).await
    {
        return r;
    }
    let perms = crate::permcheck::AdminPerms::load(&user, &plugin_name, &table).await;
    let cfg = state.config_for(&table);
    let fields = form_fields_for(&model, None, cfg);
    // BUG-16 admin: empty M2M selection on the create form (no
    // parent PK yet — the junction rows get written post-INSERT by
    // the POST handler once the parent has an id).
    let m2m_fields = form_m2m_fields_for(&model, None).await;
    // Inlines: blank `extra` rows only (no parent PK yet).
    let inlines = match crate::inlines::build_inline_views(&model, None, cfg).await {
        Ok(v) => v,
        Err(e) => return e.into_response(),
    };
    let apps = sidebar_apps(&state, &user).await;
    let breadcrumbs = vec![
        serde_json::json!({ "label": model.name.clone(), "url": format!("{}/{table}/", crate::branding::current().base_path) }),
        serde_json::json!({ "label": "Add", "url": format!("{}/{table}/new", crate::branding::current().base_path) }),
    ];
    let initial_theme = user_theme(&user).await;
    match render(
        "admin/form.html",
        context!(
            user          => user.username.clone(),
            model         => model_for_template(&model),
            fields        => fields,
            m2m_fields    => m2m_fields,
            inlines       => inlines,
            verb          => "Create",
            action        => format!("{}/{}/new", crate::branding::current().base_path, model.table),
            error         => "",
            apps          => apps,
            active_table  => table,
            breadcrumbs   => breadcrumbs,
            initial_theme => initial_theme,
            perms         => perms,
        ),
    ) {
        Ok(html) => html.into_response(),
        Err(e) => e.into_response(),
    }
}

/// `POST /admin/{table}/new` — full-page create. Audit-logs the insert
/// then redirects to the changelist; on failure re-renders the form
/// with the inline error.
pub(crate) async fn create(
    State(state): State<AdminState>,
    headers: HeaderMap,
    Path(table): Path<String>,
    body: axum::body::Bytes,
) -> Response {
    let path = format!("{}/{table}/new", crate::branding::current().base_path);
    let user = match require_staff(&headers, &path).await {
        Ok(u) => u,
        Err(r) => return r,
    };
    let Some((plugin_name, model)) = find_model(&table) else {
        return AdminError::NotFound(format!("no model with table `{table}`")).into_response();
    };
    if let Err(r) =
        crate::permcheck::require(&user, &plugin_name, &table, crate::permcheck::Action::Add).await
    {
        return r;
    }
    // Decode the body once into ordered (field, value) pairs, storing any
    // uploaded files via the ambient Storage (Wave 4). The pairs then
    // feed the two views the write paths need:
    //   - HashMap collapses duplicates to "last wins" (scalar fields,
    //     including the file column's stored key).
    //   - Vec<(K, V)> preserves duplicates (`m2m_<field>` repeated
    //     entries — the checkbox list emits one pair per checked
    //     candidate).
    let content_type = headers
        .get(umbral::web::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    let pairs = match body_to_pairs(content_type, body).await {
        Ok(p) => p,
        Err(e) => return e.into_response(),
    };
    let form: HashMap<String, String> = pairs.iter().cloned().collect();
    let multi_form: Vec<(String, String)> = pairs;
    let cfg = state.config_for(&table);
    // gaps2 #43: validate every field up front and surface ALL failures
    // at once (each below its own input) rather than letting the user
    // discover them one DB error at a time.
    let field_errors = validate_form(&model, &form, cfg);
    if !field_errors.is_empty() {
        let mut fields = form_fields_for(&model, Some(&form), cfg);
        for f in &mut fields {
            if let Some(m) = field_errors.get(&f.name) {
                f.error = m.clone();
            }
        }
        let m2m_fields = form_m2m_fields_for(&model, None).await;
        let inlines = crate::inlines::build_inline_views_from_submitted(&model, cfg, &multi_form);
        let apps = sidebar_apps(&state, &user).await;
        let breadcrumbs = vec![
            serde_json::json!({ "label": model.name.clone(), "url": format!("{}/{table}/", crate::branding::current().base_path) }),
            serde_json::json!({ "label": "Add", "url": format!("{}/{table}/new", crate::branding::current().base_path) }),
        ];
        let initial_theme = user_theme(&user).await;
        return match render(
            "admin/form.html",
            context!(
                user          => user.username.clone(),
                model         => model_for_template(&model),
                fields        => fields,
                m2m_fields    => m2m_fields,
                inlines       => inlines,
                verb          => "Create",
                action        => format!("{}/{}/new", crate::branding::current().base_path, model.table),
                error         => "",
                apps          => apps,
                active_table  => table,
                breadcrumbs   => breadcrumbs,
                initial_theme => initial_theme,
            ),
        ) {
            Ok(html) => (StatusCode::BAD_REQUEST, html).into_response(),
            Err(e2) => e2.into_response(),
        };
    }
    // Atomic save: parent INSERT + inline children, one transaction.
    // Any child failure drops the tx so neither the parent nor any
    // child persists (the load-bearing rollback guarantee).
    let saved =
        save_parent_and_inlines(&model, None, &form, cfg, &multi_form, user.is_superuser).await;
    match saved {
        Ok(_) => {
            // gaps4 #14: M2M is now written inside `save_parent_and_inlines`'
            // transaction, so there is nothing to apply post-commit — the save
            // is atomic across parent + inlines + relations.
            crate::models::log(
                user.id,
                "create",
                &table,
                None,
                &format!("created {} (via form)", model.name),
            )
            .await;
            Redirect::to(&format!(
                "{}/{}/",
                crate::branding::current().base_path,
                model.table
            ))
            .into_response()
        }
        Err(e) => {
            // gaps2 #12 part 2: for WriteError, merge per-field messages
            // into each field's `.error` slot; non-field errors go to the
            // top banner. For Sqlx UNIQUE violations we also attribute to
            // the field when we can parse the column name.
            let mut fields = form_fields_for(&model, Some(&form), cfg);
            let banner_error = match &e {
                AdminError::Write(we) => {
                    sanitise_form_error(&e); // fires the tracing::error! log
                    apply_write_error_to_fields(we, &mut fields)
                }
                AdminError::Sqlx(sqlx_err) => {
                    let msg = sqlx_err.to_string();
                    if let Some(col) = parse_unique_violation_column(&msg) {
                        if let Some(f) = fields.iter_mut().find(|f| f.name == col) {
                            f.error = format!("A record with this `{col}` already exists.");
                            String::new()
                        } else {
                            sanitise_form_error(&e)
                        }
                    } else {
                        sanitise_form_error(&e)
                    }
                }
                // BadInput carries the inline row diagnostic verbatim.
                AdminError::BadInput(msg) => msg.clone(),
                _ => sanitise_form_error(&e),
            };
            let m2m_fields = form_m2m_fields_for(&model, None).await;
            let inlines =
                crate::inlines::build_inline_views_from_submitted(&model, cfg, &multi_form);
            let apps = sidebar_apps(&state, &user).await;
            let breadcrumbs = vec![
                serde_json::json!({ "label": model.name.clone(), "url": format!("{}/{table}/", crate::branding::current().base_path) }),
                serde_json::json!({ "label": "Add", "url": format!("{}/{table}/new", crate::branding::current().base_path) }),
            ];
            let initial_theme = user_theme(&user).await;
            match render(
                "admin/form.html",
                context!(
                    user          => user.username.clone(),
                    model         => model_for_template(&model),
                    fields        => fields,
                    m2m_fields    => m2m_fields,
                    inlines       => inlines,
                    verb          => "Create",
                    action        => format!("{}/{}/new", crate::branding::current().base_path, model.table),
                    error         => banner_error,
                    apps          => apps,
                    active_table  => table,
                    breadcrumbs   => breadcrumbs,
                    initial_theme => initial_theme,
                ),
            ) {
                Ok(html) => (StatusCode::BAD_REQUEST, html).into_response(),
                Err(e2) => e2.into_response(),
            }
        }
    }
}

/// Cross-module wrapper so `handlers::sheet::sheet_create` reuses the
/// exact same atomic parent-INSERT + inline-children save path the
/// full-page `create` uses, keeping `save_parent_and_inlines` private.
pub(crate) async fn create_parent_and_inlines_pub(
    model: &umbral::migrate::ModelMeta,
    form: &HashMap<String, String>,
    cfg: Option<&crate::config::AdminConfig>,
    multi_form: &[(String, String)],
    authorize_privileged: bool,
) -> Result<String, AdminError> {
    save_parent_and_inlines(model, None, form, cfg, multi_form, authorize_privileged).await
}

/// Save a parent row plus all its inline children atomically.
///
/// `existing_pk` is `Some((pk_col, pk_value))` for an UPDATE, `None` for
/// an INSERT. Opens one transaction, writes the parent, sets the FK on
/// each inline child to the (possibly just-allocated) parent PK, then
/// commits. On any error the transaction is dropped — rolling back the
/// parent write together with every child write. Returns the parent PK
/// as a string on success.
async fn save_parent_and_inlines(
    model: &umbral::migrate::ModelMeta,
    existing_pk: Option<(&umbral::migrate::Column, &str)>,
    form: &HashMap<String, String>,
    cfg: Option<&crate::config::AdminConfig>,
    multi_form: &[(String, String)],
    authorize_privileged: bool,
) -> Result<String, AdminError> {
    let mut tx = umbral::db::begin().await.map_err(AdminError::Sqlx)?;

    let parent_pk = match existing_pk {
        Some((pk, pk_value)) => {
            update_row_in_tx(
                &mut tx,
                model,
                pk,
                pk_value,
                form,
                cfg,
                authorize_privileged,
            )
            .await?;
            pk_value.to_string()
        }
        None => insert_row_in_tx(&mut tx, model, form, cfg, authorize_privileged).await?,
    };

    crate::inlines::save_inlines_in_tx(&mut tx, model, &parent_pk, cfg, multi_form).await?;

    // gaps4 #14: M2M selections join the SAME transaction as the parent + inline
    // writes, so a junction failure rolls the whole save back instead of leaving
    // the parent persisted with its relations half-written.
    apply_m2m_selections_in_tx(model, &parent_pk, multi_form, &mut tx)
        .await
        .map_err(AdminError::Sqlx)?;

    tx.commit().await.map_err(AdminError::Sqlx)?;
    Ok(parent_pk)
}

/// `GET /admin/{table}/{id}/edit` — prefilled edit form.
pub(crate) async fn edit_form(
    State(state): State<AdminState>,
    headers: HeaderMap,
    Path((table, id)): Path<(String, String)>,
) -> Response {
    let path = format!("{}/{table}/{id}/edit", crate::branding::current().base_path);
    let user = match require_staff(&headers, &path).await {
        Ok(u) => u,
        Err(r) => return r,
    };
    let Some((plugin_name, model)) = find_model(&table) else {
        return AdminError::NotFound(format!("no model with table `{table}`")).into_response();
    };
    if let Err(r) = crate::permcheck::require(
        &user,
        &plugin_name,
        &table,
        crate::permcheck::Action::Change,
    )
    .await
    {
        return r;
    }
    let perms = crate::permcheck::AdminPerms::load(&user, &plugin_name, &table).await;
    let Some(pk) = pk_column(&model) else {
        return AdminError::Render(format!("model `{table}` has no primary key")).into_response();
    };
    let all_cols: Vec<String> = model.fields.iter().map(|f| f.name.clone()).collect();
    let rows = match fetch_rows_filtered(&model, (&pk.name, &id), &all_cols).await {
        Ok(r) => r,
        Err(e) => return e.into_response(),
    };
    let Some(row) = rows.into_iter().next() else {
        return AdminError::NotFound(format!("no row with {} = {}", pk.name, id)).into_response();
    };
    let row_strings: HashMap<String, String> =
        row.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
    let cfg = state.config_for(&table);
    let fields = form_fields_for(&model, Some(&row_strings), cfg);
    // BUG-16 admin: pre-check the current M2M selection for this
    // parent row. The PK comes from the URL path; the helper does
    // one `SELECT DISTINCT child_id FROM <junction> WHERE parent_id
    // = ?` per M2M field.
    let m2m_fields = form_m2m_fields_for(&model, Some(&id)).await;
    // Inlines: existing children (prefilled) + `extra` blank rows.
    let inlines = match crate::inlines::build_inline_views(&model, Some(&id), cfg).await {
        Ok(v) => v,
        Err(e) => return e.into_response(),
    };
    let apps = sidebar_apps(&state, &user).await;
    let breadcrumbs = vec![
        serde_json::json!({ "label": model.name.clone(), "url": format!("{}/{table}/", crate::branding::current().base_path) }),
        serde_json::json!({ "label": format!("#{id}"), "url": format!("{}/{table}/{id}", crate::branding::current().base_path) }),
        serde_json::json!({ "label": "Edit", "url": format!("{}/{table}/{id}/edit", crate::branding::current().base_path) }),
    ];
    let initial_theme = user_theme(&user).await;
    match render(
        "admin/form.html",
        context!(
            user          => user.username.clone(),
            model         => model_for_template(&model),
            fields        => fields,
            m2m_fields    => m2m_fields,
            inlines       => inlines,
            verb          => "Edit",
            action        => format!("{}/{}/{}/edit", crate::branding::current().base_path, model.table, id),
            row           => row,
            pk            => pk.name.clone(),
            error         => "",
            apps          => apps,
            active_table  => table,
            breadcrumbs   => breadcrumbs,
            initial_theme => initial_theme,
            perms         => perms,
        ),
    ) {
        Ok(html) => html.into_response(),
        Err(e) => e.into_response(),
    }
}

/// `POST /admin/{table}/{id}/edit` — full-page or HTMX update.
///
/// Two HTMX cases:
///
///   1. `_save_continue` is present in the form: re-render the edit
///      sheet so the user can keep editing.
///   2. Plain Save: emit an `HX-Trigger` that closes the sheet and
///      refreshes the table, all without a full page nav.
pub(crate) async fn update(
    State(state): State<AdminState>,
    headers: HeaderMap,
    Path((table, id)): Path<(String, String)>,
    body: axum::body::Bytes,
) -> Response {
    let path = format!("{}/{table}/{id}/edit", crate::branding::current().base_path);
    let user = match require_staff(&headers, &path).await {
        Ok(u) => u,
        Err(r) => return r,
    };
    let Some((plugin_name, model)) = find_model(&table) else {
        return AdminError::NotFound(format!("no model with table `{table}`")).into_response();
    };
    if let Err(r) = crate::permcheck::require(
        &user,
        &plugin_name,
        &table,
        crate::permcheck::Action::Change,
    )
    .await
    {
        return r;
    }
    let Some(pk) = pk_column(&model) else {
        return AdminError::Render(format!("model `{table}` has no primary key")).into_response();
    };
    // Wave 4: same body decode as `create`. An empty file part is
    // skipped by `parse_and_store_multipart`, so the file column is
    // simply absent from `form` when the user didn't pick a new file —
    // `update_form` only writes columns present in the map, so the
    // existing stored key is preserved (never nulled).
    let content_type = headers
        .get(umbral::web::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    let pairs = match body_to_pairs(content_type, body).await {
        Ok(p) => p,
        Err(e) => return e.into_response(),
    };
    let form: HashMap<String, String> = pairs.iter().cloned().collect();
    let multi_form: Vec<(String, String)> = pairs;
    let cfg = state.config_for(&table);
    // gaps2 #43: same up-front, all-at-once field validation as `create`.
    let field_errors = validate_form(&model, &form, cfg);
    if !field_errors.is_empty() {
        let mut fields = form_fields_for(&model, Some(&form), cfg);
        for f in &mut fields {
            if let Some(m) = field_errors.get(&f.name) {
                f.error = m.clone();
            }
        }
        let m2m_fields = form_m2m_fields_for(&model, Some(&id)).await;
        let inlines = crate::inlines::build_inline_views_from_submitted(&model, cfg, &multi_form);
        // Sheet-aware: an invalid field from the slide-over sheet
        // re-renders the sheet fragment (same shared handler).
        if is_htmx(&headers) {
            let password_field = cfg.and_then(|c| c.password_field.as_deref()).unwrap_or("");
            return match render(
                "admin/sheet_edit.html",
                context!(
                    model          => model_for_template(&model),
                    instance_id    => id,
                    fields         => fields,
                    m2m_fields     => m2m_fields,
                    inlines        => inlines,
                    error          => "",
                    password_field => password_field,
                ),
            ) {
                Ok(html) => (StatusCode::BAD_REQUEST, html).into_response(),
                Err(e2) => e2.into_response(),
            };
        }
        let apps = sidebar_apps(&state, &user).await;
        let breadcrumbs = vec![
            serde_json::json!({ "label": model.name.clone(), "url": format!("{}/{table}/", crate::branding::current().base_path) }),
            serde_json::json!({ "label": format!("#{id}"), "url": format!("{}/{table}/{id}", crate::branding::current().base_path) }),
            serde_json::json!({ "label": "Edit", "url": format!("{}/{table}/{id}/edit", crate::branding::current().base_path) }),
        ];
        let initial_theme = user_theme(&user).await;
        return match render(
            "admin/form.html",
            context!(
                user          => user.username.clone(),
                model         => model_for_template(&model),
                fields        => fields,
                m2m_fields    => m2m_fields,
                inlines       => inlines,
                verb          => "Edit",
                action        => format!("{}/{}/{}/edit", crate::branding::current().base_path, model.table, id),
                error         => "",
                apps          => apps,
                active_table  => table,
                breadcrumbs   => breadcrumbs,
                initial_theme => initial_theme,
            ),
        ) {
            Ok(html) => (StatusCode::BAD_REQUEST, html).into_response(),
            Err(e2) => e2.into_response(),
        };
    }
    // Atomic save: parent UPDATE + inline children, one transaction.
    let saved = save_parent_and_inlines(
        &model,
        Some((pk, &id)),
        &form,
        cfg,
        &multi_form,
        user.is_superuser,
    )
    .await;
    match saved {
        Ok(_) => {
            // gaps4 #14: M2M selections are replaced inside the parent UPDATE's
            // transaction (see `save_parent_and_inlines`), so the whole edit —
            // parent, inlines, relations — commits or rolls back as one unit.
            // gaps3 #59: the pk is text. Parsing it to i64 discarded it for every
            // Uuid/String-keyed model — the audit row named the table but not the row.
            let object_id = Some(id.clone());
            crate::models::log(
                user.id,
                "update",
                &table,
                object_id,
                &format!("updated {} #{}", model.name, id),
            )
            .await;

            if is_htmx(&headers) {
                if form.contains_key("_save_continue") {
                    // Re-render the sheet (stays open) AND refresh the
                    // underlying changelist so the saved change shows in the
                    // list behind the sheet. No `closeSheet` — symmetric with
                    // the plain-save path but without dismissing the panel.
                    // The admin.js `refreshTable` listener re-fetches /rows
                    // using window.location.search, preserving the active
                    // search/sort/page/filter kwargs.
                    let mut resp =
                        edit_sheet_handler(State(state), headers, Path((table, id))).await;
                    let trigger = serde_json::json!({
                        "refreshTable": {},
                        "showToast": {
                            "message": format!("{} saved", model.name),
                            "level": "success"
                        },
                    });
                    if let Ok(hv) = trigger.to_string().parse() {
                        resp.headers_mut().insert("HX-Trigger", hv);
                    }
                    return resp;
                }
                // gaps2 #13: success toast alongside closeSheet +
                // refreshTable. Symmetric with `sheet::sheet_create`.
                let trigger = serde_json::json!({
                    "closeSheet": {},
                    "refreshTable": {},
                    "showToast": {
                        "message": format!("{} updated", model.name),
                        "level": "success"
                    },
                });
                let mut resp = axum::response::Response::builder()
                    .status(StatusCode::OK)
                    .header("HX-Trigger", trigger.to_string())
                    .body(axum::body::Body::empty())
                    .unwrap();
                resp.headers_mut()
                    .insert("Content-Type", "text/html; charset=utf-8".parse().unwrap());
                return resp;
            }

            Redirect::to(&format!(
                "{}/{}/{}",
                crate::branding::current().base_path,
                model.table,
                id
            ))
            .into_response()
        }
        Err(e) => {
            // gaps2 #12 part 2: same per-field attribution as `create`.
            let mut fields = form_fields_for(&model, Some(&form), cfg);
            let banner_error = match &e {
                AdminError::Write(we) => {
                    sanitise_form_error(&e); // fires the tracing::error! log
                    apply_write_error_to_fields(we, &mut fields)
                }
                AdminError::Sqlx(sqlx_err) => {
                    let msg = sqlx_err.to_string();
                    if let Some(col) = parse_unique_violation_column(&msg) {
                        if let Some(f) = fields.iter_mut().find(|f| f.name == col) {
                            f.error = format!("A record with this `{col}` already exists.");
                            String::new()
                        } else {
                            sanitise_form_error(&e)
                        }
                    } else {
                        sanitise_form_error(&e)
                    }
                }
                // BadInput carries the inline row diagnostic verbatim.
                AdminError::BadInput(msg) => msg.clone(),
                _ => sanitise_form_error(&e),
            };
            let m2m_fields = form_m2m_fields_for(&model, Some(&id)).await;
            let inlines =
                crate::inlines::build_inline_views_from_submitted(&model, cfg, &multi_form);
            // Sheet-aware error re-render: a bad submit from the slide-over
            // sheet (HTMX, posting to this same shared handler) re-renders
            // the SHEET fragment — keeping the user's values + the error
            // in the open panel — rather than a full page. Mirrors the
            // `_save_continue` → `edit_sheet_handler` success precedent.
            if is_htmx(&headers) {
                let password_field = cfg.and_then(|c| c.password_field.as_deref()).unwrap_or("");
                return match render(
                    "admin/sheet_edit.html",
                    context!(
                        model          => model_for_template(&model),
                        instance_id    => id,
                        fields         => fields,
                        m2m_fields     => m2m_fields,
                        inlines        => inlines,
                        error          => banner_error,
                        password_field => password_field,
                    ),
                ) {
                    Ok(html) => (StatusCode::BAD_REQUEST, html).into_response(),
                    Err(e2) => e2.into_response(),
                };
            }
            let apps = sidebar_apps(&state, &user).await;
            let breadcrumbs = vec![
                serde_json::json!({ "label": model.name.clone(), "url": format!("{}/{table}/", crate::branding::current().base_path) }),
                serde_json::json!({ "label": format!("#{id}"), "url": format!("{}/{table}/{id}", crate::branding::current().base_path) }),
                serde_json::json!({ "label": "Edit", "url": format!("{}/{table}/{id}/edit", crate::branding::current().base_path) }),
            ];
            let initial_theme = user_theme(&user).await;
            match render(
                "admin/form.html",
                context!(
                    user          => user.username.clone(),
                    model         => model_for_template(&model),
                    fields        => fields,
                    m2m_fields    => m2m_fields,
                    inlines       => inlines,
                    verb          => "Edit",
                    action        => format!("{}/{}/{}/edit", crate::branding::current().base_path, model.table, id),
                    error         => banner_error,
                    apps          => apps,
                    active_table  => table,
                    breadcrumbs   => breadcrumbs,
                    initial_theme => initial_theme,
                ),
            ) {
                Ok(html) => (StatusCode::BAD_REQUEST, html).into_response(),
                Err(e2) => e2.into_response(),
            }
        }
    }
}

/// `POST /admin/{table}/{id}/delete` — legacy form-POST delete.
pub(crate) async fn delete(
    State(_state): State<AdminState>,
    headers: HeaderMap,
    Path((table, id)): Path<(String, String)>,
) -> Response {
    let path = format!(
        "{}/{table}/{id}/delete",
        crate::branding::current().base_path
    );
    let who = match require_staff(&headers, &path).await {
        Ok(u) => u,
        Err(r) => return r,
    };
    let Some((plugin_name, model)) = find_model(&table) else {
        return AdminError::NotFound(format!("no model with table `{table}`")).into_response();
    };
    if let Err(r) =
        crate::permcheck::require(&who, &plugin_name, &table, crate::permcheck::Action::Delete)
            .await
    {
        return r;
    }
    let Some(pk) = pk_column(&model) else {
        return AdminError::Render(format!("model `{table}` has no primary key")).into_response();
    };
    match DynQuerySet::for_meta(&model)
        .filter_eq_string(&pk.name, &id)
        .delete()
        .await
    {
        Ok(_) => {
            // gaps3 #59: the pk is text. Parsing it to i64 discarded it for every
            // Uuid/String-keyed model — the audit row named the table but not the row.
            let object_id = Some(id.clone());
            crate::models::log(
                who.id,
                "delete",
                &table,
                object_id,
                &format!("deleted {} #{}", model.name, id),
            )
            .await;
            Redirect::to(&format!(
                "{}/{}/",
                crate::branding::current().base_path,
                model.table
            ))
            .into_response()
        }
        // gaps2 #12: `e` is `DynError` now; route through the
        // `From<DynError>` impl so Write(WriteError) keeps its
        // structure instead of flattening to "database error".
        Err(e) => AdminError::from(e).into_response(),
    }
}

/// `DELETE /admin/{table}/{id}` — HTMX delete. Returns an empty body
/// with `HX-Trigger: closeSheet + refreshTable` so the changelist
/// swaps in place (matches the in-place refresh `update` does after
/// a save). Falls back to a full reload on the listener side when
/// the caller isn't on a changelist (detail page delete).
pub(crate) async fn htmx_delete(
    State(_state): State<AdminState>,
    headers: HeaderMap,
    Path((table, id)): Path<(String, String)>,
) -> Response {
    let path = format!("{}/{table}/{id}", crate::branding::current().base_path);
    let who = match require_staff(&headers, &path).await {
        Ok(u) => u,
        Err(r) => return r,
    };
    let Some((plugin_name, model)) = find_model(&table) else {
        return AdminError::NotFound(format!("no model with table `{table}`")).into_response();
    };
    if let Err(r) =
        crate::permcheck::require(&who, &plugin_name, &table, crate::permcheck::Action::Delete)
            .await
    {
        return r;
    }
    let Some(pk) = pk_column(&model) else {
        return AdminError::Render(format!("model `{table}` has no primary key")).into_response();
    };
    match DynQuerySet::for_meta(&model)
        .filter_eq_string(&pk.name, &id)
        .delete()
        .await
    {
        Ok(_) => {
            // gaps3 #59: the pk is text. Parsing it to i64 discarded it for every
            // Uuid/String-keyed model — the audit row named the table but not the row.
            let object_id = Some(id.clone());
            crate::models::log(
                who.id,
                "delete",
                &table,
                object_id,
                &format!("deleted {} #{}", model.name, id),
            )
            .await;
            // gaps2 #13: success toast on delete too.
            let trigger = serde_json::json!({
                "closeSheet": {},
                "refreshTable": {},
                "showToast": {
                    "message": format!("{} #{} deleted", model.name, id),
                    "level": "success"
                },
            });
            let mut resp = axum::response::Response::builder()
                .status(StatusCode::OK)
                .header("HX-Trigger", trigger.to_string())
                .body(axum::body::Body::empty())
                .unwrap_or_else(|_| {
                    Redirect::to(&format!(
                        "{}/{}/",
                        crate::branding::current().base_path,
                        model.table
                    ))
                    .into_response()
                });
            resp.headers_mut()
                .insert("Content-Type", "text/html; charset=utf-8".parse().unwrap());
            resp
        }
        // gaps2 #12: `e` is `DynError`; route via `From<DynError>`.
        Err(e) => AdminError::from(e).into_response(),
    }
}