rustio-core 1.8.1

RustIO runtime library: HTTP, router, Postgres ORM, admin, RBAC, search, migrations, AI planner.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
//! Built-in admin pages for users and groups. These are wired into
//! the admin automatically — users never have to opt in, since every
//! project needs them.
//!
//! The pages are simpler than normal model admin pages (smaller forms,
//! custom actions like "set password"), so they don't use the
//! `AdminModel` trait — they're rendered by bespoke handlers.

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

use serde::Serialize;

use crate::auth::{self, Identity, Role};
use crate::error::{Error, Result};
use crate::http::{Request, Response};
use crate::orm::{Db, Row};
use crate::templates::Templates;

use super::render;
use super::render::{BaseContext, FlashCtx, SidebarEntry};
use super::types::Admin;

pub(crate) struct AuthAdminCtx {
    pub admin: Arc<Admin>,
    pub db: Db,
    pub templates: Arc<Templates>,
}

// ---------- Users list ----------

#[derive(Serialize)]
struct UserRow {
    id: i64,
    email: String,
    role: String,
    is_active: bool,
    created_at: String,
}

#[derive(Serialize)]
struct UsersListCtx {
    #[serde(flatten)]
    base: BaseContext,
    page_title: &'static str,
    entries: Vec<SidebarEntry>,
    users: Vec<UserRow>,
    flash: Option<FlashCtx>,
}

pub(crate) async fn list_users(
    ctx: &AuthAdminCtx,
    identity: Identity,
    csrf: String,
) -> Result<Response> {
    let rows = sqlx::query(
        "SELECT id, email, role, is_active, created_at
           FROM rustio_users
          ORDER BY id ASC",
    )
    .fetch_all(ctx.db.pool())
    .await?;

    let users = rows
        .iter()
        .map(|r| {
            let r = Row::from_pg(r);
            Ok(UserRow {
                id: r.get_i64("id")?,
                email: r.get_string("email")?,
                role: r.get_string("role")?,
                is_active: r.get_bool("is_active")?,
                created_at: r
                    .get_datetime("created_at")?
                    .format("%Y-%m-%d %H:%M")
                    .to_string(),
            })
        })
        .collect::<Result<Vec<_>>>()?;

    let view = UsersListCtx {
        base: BaseContext::new(Some(&identity), csrf, &ctx.admin),
        page_title: "Users",
        entries: ctx
            .admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        users,
        flash: None,
    };
    let body = ctx.templates.render("admin/users_list.html", &view)?;
    Ok(Response::html(body))
}

// ---------- User edit ----------

#[derive(Serialize)]
struct UserEditCtx {
    #[serde(flatten)]
    base: BaseContext,
    page_title: String,
    entries: Vec<SidebarEntry>,
    user_id: i64,
    email: String,
    role: String,
    is_active: bool,
    all_groups: Vec<GroupRow>,
    user_groups: Vec<i64>,
    errors: Vec<String>,
    flash: Option<FlashCtx>,
    /// Phase 7a/0.5/f — set when this user is the sole active
    /// developer. The template renders a yellow banner so admins know
    /// a role change here will be rejected by `do_user_edit`.
    is_last_developer: bool,
    /// Phase 6.2 — Identity section (email-disabled / role / is_active)
    /// rendered through the shared FormField include. Built from
    /// the existing email/role/is_active fields above so re-render on
    /// validation failure preserves the operator's edits.
    identity_sections: Vec<render::FormSection>,
    /// Phase 6.2 — Reset password section (new_password optional).
    /// Renders below the groups custom block to preserve the
    /// pre-6.2 visual order.
    password_sections: Vec<render::FormSection>,
}

#[derive(Serialize)]
struct GroupRow {
    id: i64,
    name: String,
    description: String,
}

async fn load_groups(db: &Db) -> Result<Vec<GroupRow>> {
    let rows = sqlx::query("SELECT id, name, description FROM rustio_groups ORDER BY name ASC")
        .fetch_all(db.pool())
        .await?;
    rows.iter()
        .map(|r| {
            let r = Row::from_pg(r);
            Ok(GroupRow {
                id: r.get_i64("id")?,
                name: r.get_string("name")?,
                description: r.get_string("description")?,
            })
        })
        .collect()
}

pub(crate) async fn show_user_edit(
    ctx: &AuthAdminCtx,
    identity: Identity,
    user_id: i64,
    csrf: String,
) -> Result<Response> {
    let row = sqlx::query("SELECT id, email, role, is_active FROM rustio_users WHERE id = $1")
        .bind(user_id)
        .fetch_optional(ctx.db.pool())
        .await?;
    let row = row.ok_or_else(|| Error::NotFound(format!("user #{user_id}")))?;
    let r = Row::from_pg(&row);

    let group_ids: Vec<i64> =
        sqlx::query_scalar::<_, i64>("SELECT group_id FROM rustio_user_groups WHERE user_id = $1")
            .bind(user_id)
            .fetch_all(ctx.db.pool())
            .await?;

    let is_last_developer =
        auth::would_orphan_developers(&ctx.db, user_id, Some(Role::User)).await?;

    let email_str = r.get_string("email")?;
    let role_str = r.get_string("role")?;
    let is_active_val = r.get_bool("is_active")?;
    let view = UserEditCtx {
        base: BaseContext::new(Some(&identity), csrf, &ctx.admin),
        page_title: format!("Edit user #{user_id}"),
        entries: ctx
            .admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        user_id,
        identity_sections: render::user_edit_identity_sections(
            &email_str,
            &role_str,
            is_active_val,
        ),
        password_sections: render::user_edit_password_sections(),
        email: email_str,
        role: role_str,
        is_active: is_active_val,
        all_groups: load_groups(&ctx.db).await?,
        user_groups: group_ids,
        errors: vec![],
        flash: None,
        is_last_developer,
    };
    let body = ctx.templates.render("admin/user_edit.html", &view)?;
    Ok(Response::html(body))
}

pub(crate) async fn do_user_edit(
    ctx: &AuthAdminCtx,
    identity: Identity,
    user_id: i64,
    req: Request,
) -> Result<Response> {
    let form = req.form()?;
    let role = Role::parse(form.required("role")?)?;
    let is_active = form.bool_flag("is_active");

    // Collect the ticked group ids upfront — used either to apply
    // below, or to preserve the user's selection on a re-render with
    // errors.
    let mut wanted: Vec<i64> = Vec::new();
    for (k, v) in form.as_map() {
        if let Some(id_str) = k.strip_prefix("group_") {
            if v == "on" {
                if let Ok(gid) = id_str.parse::<i64>() {
                    wanted.push(gid);
                }
            }
        }
    }
    let new_password = form
        .get("new_password")
        .map(|s| s.to_string())
        .unwrap_or_default();

    // Phase 7a/0.5/f — last-developer guard. Block any change that
    // would leave the system with zero active developers. The helper
    // is role-based; a deactivation (is_active=false) is equivalent
    // to removing this user from the active-developer pool, so we
    // pass a non-Developer sentinel role in that case so the helper
    // catches it.
    let effective_role = if is_active { role } else { Role::User };
    if auth::would_orphan_developers(&ctx.db, user_id, Some(effective_role)).await? {
        let csrf = req
            .ctx()
            .get::<crate::middleware::CsrfGuard>()
            .map(|g| g.token.clone())
            .unwrap_or_default();
        return render_user_edit_with_errors(
            ctx,
            &identity,
            user_id,
            role,
            is_active,
            wanted,
            csrf,
            vec!["Cannot demote or deactivate the last active developer. \
                 Use rustio-cli to promote a backup developer first."
                .into()],
        )
        .await;
    }

    sqlx::query(
        "UPDATE rustio_users SET role = $1, is_active = $2, updated_at = NOW() WHERE id = $3",
    )
    .bind(role.as_str())
    .bind(is_active)
    .bind(user_id)
    .execute(ctx.db.pool())
    .await?;

    sqlx::query("DELETE FROM rustio_user_groups WHERE user_id = $1")
        .bind(user_id)
        .execute(ctx.db.pool())
        .await?;
    // Phase 7a/0.5/sec3 — the wholesale DELETE bypasses
    // `remove_user_from_group`'s built-in cache invalidation. Without
    // this explicit call, a user demoted to zero groups keeps every
    // permission for up to 60 seconds (PERM_CACHE_TTL). When the
    // checkbox loop below adds at least one group back, that path's
    // own invalidation covers us — but the all-unchecked case lands
    // here.
    auth::invalidate_user_cache(user_id);
    for gid in wanted {
        auth::add_user_to_group(&ctx.db, user_id, gid).await?;
    }

    if !new_password.is_empty() {
        auth::set_password(&ctx.db, user_id, &new_password).await?;
    }

    Ok(Response::redirect("/admin/users"))
}

/// Re-render the user edit form with validation errors displayed
/// inline. Used by `do_user_edit` when the orphan guard rejects a
/// change. Returns 400 Bad Request so callers (and tests) can
/// distinguish a rejected save from a successful redirect.
#[allow(clippy::too_many_arguments)]
async fn render_user_edit_with_errors(
    ctx: &AuthAdminCtx,
    identity: &Identity,
    user_id: i64,
    role: Role,
    is_active: bool,
    user_groups: Vec<i64>,
    csrf: String,
    errors: Vec<String>,
) -> Result<Response> {
    let row = sqlx::query("SELECT email FROM rustio_users WHERE id = $1")
        .bind(user_id)
        .fetch_optional(ctx.db.pool())
        .await?;
    let row = row.ok_or_else(|| Error::NotFound(format!("user #{user_id}")))?;
    let r = Row::from_pg(&row);

    let is_last_developer =
        auth::would_orphan_developers(&ctx.db, user_id, Some(Role::User)).await?;

    let email_str = r.get_string("email")?;
    let role_str: String = role.as_str().into();

    // Phase 7.5 — the only error this fn produces is the
    // last-developer orphan guard, which is a property of the role
    // change. Key it onto `role` so the inline error renders next to
    // the role select. If callers later widen the scope, they should
    // pass a `field_errors` argument explicitly.
    let mut field_errors: HashMap<String, Vec<String>> = HashMap::new();
    for msg in &errors {
        field_errors
            .entry("role".into())
            .or_default()
            .push(msg.clone());
    }
    let mut identity_sections =
        render::user_edit_identity_sections(&email_str, &role_str, is_active);
    render::apply_field_errors(&mut identity_sections, &field_errors);
    let view = UserEditCtx {
        base: BaseContext::new(Some(identity), csrf, &ctx.admin),
        page_title: format!("Edit user #{user_id}"),
        entries: ctx
            .admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        user_id,
        identity_sections,
        password_sections: render::user_edit_password_sections(),
        email: email_str,
        role: role_str,
        is_active,
        all_groups: load_groups(&ctx.db).await?,
        user_groups,
        errors,
        flash: None,
        is_last_developer,
    };
    let body = ctx.templates.render("admin/user_edit.html", &view)?;
    Ok(Response::html(body).with_status(hyper::StatusCode::BAD_REQUEST))
}

// ---------- User view (Phase 7a/0.5/h) ----------
//
// Read-only profile page. Sits between the users list (which now
// links each row here, not to /edit) and the destructive surfaces.
// The view is the navigation hub — Back, Edit, Delete buttons all
// live here — so the edit + delete pages don't have to render
// profile metadata; they stay focused on the action they perform.

/// Phase 10/b — splitview/tabs user-profile context. Replaces the
/// pre-10/b shape (target_* fields + delete-guard booleans) with a
/// nested `user` object plus per-tab payloads. The Delete button is
/// no longer rendered inline; destructive ops live on the separate
/// `/admin/users/:id/delete` confirm page (which keeps its own
/// guarding).
#[derive(Serialize)]
struct UserViewCtx {
    #[serde(flatten)]
    base: BaseContext,
    page_title: String,
    entries: Vec<SidebarEntry>,

    /// The user being viewed. Pre-formatted for direct display.
    user: UserViewTarget,
    /// 50-row list-pane sample. Sorted by `created_at DESC`. Spec note:
    /// the user-spec asked for `last_seen DESC` with a fallback to
    /// `created_at DESC` if the cross-table subquery proved costly.
    /// `last_seen` lives on `rustio_sessions` only, so a `last_seen`
    /// sort needs a correlated subquery (or LATERAL join) per row;
    /// `/b` ships the cheaper single-table sort to keep the list-pane
    /// fast. A follow-up can switch once the cost is measured.
    users: Vec<UserListItem>,
    total: i64,

    /// Counts always shown on the tab bar.
    activity_count: i64,
    permission_count: i64,
    session_count: i64,

    /// `"overview" | "activity" | "permissions" | "sessions"`. The
    /// template branches on this string in the detail-body region.
    tab: &'static str,

    /// Overview: last 7 events. Activity: 50 events for the current page.
    /// Empty for permissions/sessions tabs.
    recent_events: Vec<TimelineEvent>,
    /// Activity-tab pagination. `page=1` is the default. `total_pages`
    /// is `1` when there are no events (avoids div-by-zero in the pager).
    activity_page: i64,
    activity_total_pages: i64,

    /// Permissions tab payload. Empty unless `tab == "permissions"`.
    permissions: Vec<PermissionItem>,
    /// Sessions tab payload. Empty unless `tab == "sessions"`.
    sessions: Vec<SessionItem>,

    /// Phase 10/c — sections contributed by the project's
    /// [`Admin::user_profile_extension`] closure, if registered.
    /// Rendered in the Overview tab via the
    /// `{% block project_user_fields %}` template block. Empty when
    /// no extension is registered or `tab != "overview"`.
    project_fields: Vec<super::types::UserProfileSection>,

    /// Edit button visibility. Administrator sessions always allow it;
    /// future tiers may not.
    can_edit: bool,
}

#[derive(Serialize)]
struct UserViewTarget {
    id: i64,
    email: String,
    /// Display label; `full_name` if set, else humanized email local-part.
    full_name: String,
    /// Raw `full_name` column for the show-grid Full-name row's
    /// "no value" rendering. Distinct from `full_name` (which always
    /// has a usable display string).
    full_name_value: Option<String>,
    role: String,
    is_admin: bool,
    is_developer: bool,
    is_active: bool,
    is_demo: bool,
    demo_label: Option<String>,
    locale: Option<String>,
    timezone: Option<String>,
    created_at_iso: String,
    last_seen_relative: String,
    last_login_iso: String,
    groups: Vec<String>,
}

#[derive(Serialize)]
struct UserListItem {
    id: i64,
    email: String,
    full_name: String,
    is_active: bool,
    last_seen_relative: String,
}

#[derive(Serialize)]
struct TimelineEvent {
    id: i64,
    /// `"success" | "info" | "warning" | "error" | "muted"`. Drives
    /// the dot color in the timeline component.
    kind: &'static str,
    /// Already-escaped, ready for `{{ event.message|safe }}`.
    message: String,
    timestamp_relative: String,
    /// Human-readable actor label (e.g. `"user:42"`). Future:
    /// hyperlinked to the actor's profile.
    actor: String,
}

#[derive(Serialize)]
struct PermissionItem {
    name: String,
    /// `"direct"` for `rustio_user_permissions` rows, `"via <Group>"`
    /// for inheritance.
    source: String,
}

#[derive(Serialize)]
struct SessionItem {
    /// First 7 chars of the session token; the full token is never
    /// exposed in the rendered HTML.
    token_short: String,
    created_at_iso: String,
    last_seen_relative: String,
    ip: Option<String>,
    user_agent: Option<String>,
}

const ACTIVITY_PER_PAGE: i64 = 50;
const OVERVIEW_RECENT_LIMIT: i64 = 7;
const LIST_PANE_LIMIT: i64 = 50;

pub(crate) async fn show_user_view(
    ctx: &AuthAdminCtx,
    identity: Identity,
    user_id: i64,
    csrf: String,
    tab: Option<String>,
    page: i64,
) -> Result<Response> {
    let profile = auth::load_user_profile(&ctx.db, user_id)
        .await?
        .ok_or_else(|| Error::NotFound(format!("user #{user_id}")))?;

    let groups = load_user_groups(&ctx.db, user_id).await?;
    let last_seen = load_max_session_ts(&ctx.db, user_id, "last_seen").await;
    let last_login = load_max_session_ts(&ctx.db, user_id, "created_at").await;
    let activity_count = load_user_activity_count(&ctx.db, user_id).await;
    let permission_count = load_user_permission_count(&ctx.db, user_id).await;
    let session_count = load_user_session_count(&ctx.db, user_id).await;

    let tab_str: &'static str = match tab.as_deref() {
        Some("activity") => "activity",
        Some("permissions") => "permissions",
        Some("sessions") => "sessions",
        _ => "overview",
    };
    let page = page.max(1);

    let (recent_events, activity_page, activity_total_pages) = match tab_str {
        "activity" => {
            let total_pages = (activity_count.max(1) + ACTIVITY_PER_PAGE - 1) / ACTIVITY_PER_PAGE;
            let total_pages = total_pages.max(1);
            let page = page.min(total_pages);
            let offset = (page - 1) * ACTIVITY_PER_PAGE;
            let evts = load_user_audit(&ctx.db, user_id, ACTIVITY_PER_PAGE, offset).await?;
            (evts, page, total_pages)
        }
        "overview" => {
            let evts = load_user_audit(&ctx.db, user_id, OVERVIEW_RECENT_LIMIT, 0).await?;
            (evts, 1, 1)
        }
        _ => (Vec::new(), 1, 1),
    };

    let permissions = if tab_str == "permissions" {
        load_user_permissions(&ctx.db, user_id).await?
    } else {
        Vec::new()
    };
    let sessions = if tab_str == "sessions" {
        load_user_sessions(&ctx.db, user_id).await?
    } else {
        Vec::new()
    };

    let users = load_user_list(&ctx.db, LIST_PANE_LIMIT).await?;
    let total: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM rustio_users")
        .fetch_one(ctx.db.pool())
        .await
        .unwrap_or(0);

    // Phase 10/c — call the project-registered extension closure (if any)
    // only on the Overview tab. Other tabs don't render the extension
    // section, so we skip the work to keep tab switches snappy.
    let project_fields = if tab_str == "overview" {
        match ctx.admin.user_profile_ext() {
            Some(ext) => ext(ctx.db.clone(), profile.clone()).await?,
            None => Vec::new(),
        }
    } else {
        Vec::new()
    };

    let role_label = profile.role.label().to_string();
    let display_name = profile
        .full_name
        .clone()
        .filter(|s| !s.trim().is_empty())
        .unwrap_or_else(|| humanize_email(&profile.email));

    let view = UserViewCtx {
        base: BaseContext::new(Some(&identity), csrf, &ctx.admin),
        page_title: format!("{} — Users", profile.email),
        entries: ctx
            .admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        user: UserViewTarget {
            id: profile.id,
            email: profile.email.clone(),
            full_name: display_name,
            full_name_value: profile.full_name.clone(),
            role: role_label,
            is_admin: profile.role.includes(Role::Administrator),
            is_developer: profile.role.includes(Role::Developer),
            is_active: profile.is_active,
            is_demo: profile.is_demo,
            demo_label: profile.demo_label.clone(),
            locale: profile.locale.clone(),
            timezone: profile.timezone.clone(),
            created_at_iso: profile.created_at.format("%Y-%m-%d %H:%M UTC").to_string(),
            last_seen_relative: last_seen
                .map(render::relative_time)
                .unwrap_or_else(|| "never".into()),
            last_login_iso: last_login
                .map(|t| t.format("%Y-%m-%d %H:%M UTC").to_string())
                .unwrap_or_else(|| "never".into()),
            groups,
        },
        users,
        total,
        activity_count,
        permission_count,
        session_count,
        tab: tab_str,
        recent_events,
        activity_page,
        activity_total_pages,
        permissions,
        sessions,
        project_fields,
        can_edit: true,
    };
    let body = ctx.templates.render("admin/user_view.html", &view)?;
    Ok(Response::html(body))
}

// ---------- show_user_view helpers (Phase 10/b) ----------

async fn load_user_groups(db: &Db, user_id: i64) -> Result<Vec<String>> {
    let rows: Vec<(String,)> = sqlx::query_as(
        "SELECT g.name FROM rustio_groups g
         JOIN rustio_user_groups ug ON ug.group_id = g.id
         WHERE ug.user_id = $1
         ORDER BY g.name ASC",
    )
    .bind(user_id)
    .fetch_all(db.pool())
    .await
    .map_err(|e| Error::Internal(format!("query user groups: {e}")))?;
    Ok(rows.into_iter().map(|(n,)| n).collect())
}

async fn load_max_session_ts(db: &Db, user_id: i64, col: &str) -> Option<chrono::DateTime<chrono::Utc>> {
    // `col` is one of "last_seen" / "created_at" — never user input.
    // String interpolation here is bound to the function's call sites
    // in this module (no caller passes external data through `col`).
    let sql = format!("SELECT MAX({col}) FROM rustio_sessions WHERE user_id = $1");
    sqlx::query_scalar::<_, Option<chrono::DateTime<chrono::Utc>>>(&sql)
        .bind(user_id)
        .fetch_one(db.pool())
        .await
        .ok()
        .flatten()
}

async fn load_user_activity_count(db: &Db, user_id: i64) -> i64 {
    sqlx::query_scalar("SELECT COUNT(*) FROM rustio_admin_actions WHERE user_id = $1")
        .bind(user_id)
        .fetch_one(db.pool())
        .await
        .unwrap_or(0)
}

async fn load_user_session_count(db: &Db, user_id: i64) -> i64 {
    sqlx::query_scalar("SELECT COUNT(*) FROM rustio_sessions WHERE user_id = $1")
        .bind(user_id)
        .fetch_one(db.pool())
        .await
        .unwrap_or(0)
}

async fn load_user_permission_count(db: &Db, user_id: i64) -> i64 {
    sqlx::query_scalar(
        "SELECT COUNT(DISTINCT p.id)
         FROM rustio_permissions p
         LEFT JOIN rustio_user_permissions up
                ON up.permission_id = p.id AND up.user_id = $1
         LEFT JOIN rustio_group_permissions gp
                ON gp.permission_id = p.id
         LEFT JOIN rustio_user_groups ug
                ON ug.group_id = gp.group_id AND ug.user_id = $1
         WHERE up.user_id IS NOT NULL OR ug.user_id IS NOT NULL",
    )
    .bind(user_id)
    .fetch_one(db.pool())
    .await
    .unwrap_or(0)
}

async fn load_user_audit(
    db: &Db,
    user_id: i64,
    limit: i64,
    offset: i64,
) -> Result<Vec<TimelineEvent>> {
    let rows: Vec<(i64, String, String, i64, chrono::DateTime<chrono::Utc>, String)> =
        sqlx::query_as(
            "SELECT id, action_type, model_name, object_id, timestamp, summary
             FROM rustio_admin_actions
             WHERE user_id = $1
             ORDER BY timestamp DESC, id DESC
             LIMIT $2 OFFSET $3",
        )
        .bind(user_id)
        .bind(limit)
        .bind(offset)
        .fetch_all(db.pool())
        .await
        .map_err(|e| Error::Internal(format!("query audit: {e}")))?;

    Ok(rows
        .into_iter()
        .map(|(id, action, model, obj, ts, summary)| TimelineEvent {
            id,
            kind: match action.as_str() {
                "create" => "success",
                "delete" => "error",
                "update" => "info",
                _ => "muted",
            },
            message: format!(
                "<strong>{}</strong> on {} #{}",
                html_escape(&summary),
                html_escape(&model),
                obj,
            ),
            timestamp_relative: render::relative_time(ts),
            actor: format!("user:{user_id}"),
        })
        .collect())
}

async fn load_user_permissions(db: &Db, user_id: i64) -> Result<Vec<PermissionItem>> {
    // Direct grants → source = "direct".
    let direct: Vec<(String,)> = sqlx::query_as(
        "SELECT p.name
         FROM rustio_permissions p
         JOIN rustio_user_permissions up ON up.permission_id = p.id
         WHERE up.user_id = $1
         ORDER BY p.name ASC",
    )
    .bind(user_id)
    .fetch_all(db.pool())
    .await
    .map_err(|e| Error::Internal(format!("query direct perms: {e}")))?;

    // Inherited via groups → source = "via <Group name>".
    let inherited: Vec<(String, String)> = sqlx::query_as(
        "SELECT p.name, g.name
         FROM rustio_permissions p
         JOIN rustio_group_permissions gp ON gp.permission_id = p.id
         JOIN rustio_groups g ON g.id = gp.group_id
         JOIN rustio_user_groups ug ON ug.group_id = g.id
         WHERE ug.user_id = $1
         ORDER BY p.name ASC, g.name ASC",
    )
    .bind(user_id)
    .fetch_all(db.pool())
    .await
    .map_err(|e| Error::Internal(format!("query inherited perms: {e}")))?;

    // Merge: a permission can be both direct AND via a group. We list
    // each (perm, source) row separately so admins can see all sources.
    // Order: direct first (rare, important to surface), then inherited.
    let mut out: Vec<PermissionItem> = Vec::with_capacity(direct.len() + inherited.len());
    for (name,) in direct {
        out.push(PermissionItem { name, source: "direct".into() });
    }
    for (name, group) in inherited {
        out.push(PermissionItem { name, source: format!("via {group}") });
    }
    Ok(out)
}

async fn load_user_sessions(db: &Db, user_id: i64) -> Result<Vec<SessionItem>> {
    type SessionRow = (
        String,
        chrono::DateTime<chrono::Utc>,
        chrono::DateTime<chrono::Utc>,
        Option<String>,
        Option<String>,
    );
    let rows: Vec<SessionRow> = sqlx::query_as(
        "SELECT token, created_at, last_seen, ip, user_agent
         FROM rustio_sessions
         WHERE user_id = $1
         ORDER BY created_at DESC",
    )
    .bind(user_id)
    .fetch_all(db.pool())
    .await
    .map_err(|e| Error::Internal(format!("query sessions: {e}")))?;

    Ok(rows
        .into_iter()
        .map(|(token, created_at, last_seen, ip, user_agent)| {
            let token_short: String = token.chars().take(7).collect();
            SessionItem {
                token_short,
                created_at_iso: created_at.format("%Y-%m-%d %H:%M UTC").to_string(),
                last_seen_relative: render::relative_time(last_seen),
                ip,
                user_agent,
            }
        })
        .collect())
}

async fn load_user_list(db: &Db, limit: i64) -> Result<Vec<UserListItem>> {
    let rows: Vec<(i64, String, Option<String>, bool)> = sqlx::query_as(
        "SELECT id, email, full_name, is_active
         FROM rustio_users
         ORDER BY created_at DESC
         LIMIT $1",
    )
    .bind(limit)
    .fetch_all(db.pool())
    .await
    .map_err(|e| Error::Internal(format!("query user list: {e}")))?;

    let mut out = Vec::with_capacity(rows.len());
    for (id, email, full_name, is_active) in rows {
        let last_seen = load_max_session_ts(db, id, "last_seen").await;
        let display = full_name
            .filter(|s| !s.trim().is_empty())
            .unwrap_or_else(|| humanize_email(&email));
        out.push(UserListItem {
            id,
            email,
            full_name: display,
            is_active,
            last_seen_relative: last_seen
                .map(render::relative_time)
                .unwrap_or_else(|| "".into()),
        });
    }
    Ok(out)
}

fn humanize_email(email: &str) -> String {
    let local = email.split('@').next().unwrap_or(email);
    let humanized: String = local
        .split(['.', '_', '-'])
        .filter(|p| !p.is_empty())
        .map(|p| {
            let mut chars = p.chars();
            match chars.next() {
                Some(c) => c.to_uppercase().chain(chars).collect::<String>(),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join(" ");
    if humanized.is_empty() {
        email.to_string()
    } else {
        humanized
    }
}

fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

// ---------- User delete (Phase 7a/0.5/f) ----------

#[derive(Serialize)]
struct UserDeleteCtx {
    #[serde(flatten)]
    base: BaseContext,
    page_title: String,
    entries: Vec<SidebarEntry>,
    user_id: i64,
    email: String,
    role: String,
    /// Memberships dropped on cascade.
    group_count: i64,
    /// Active sessions terminated on cascade.
    session_count: i64,
    /// Direct permission grants dropped on cascade.
    direct_perm_count: i64,
    /// Set when the target is the currently logged-in user. The
    /// confirm form hides the submit button in this case.
    is_self: bool,
    /// Set when removing this user would leave zero active developers.
    /// Like `is_self`, this disables the submit button.
    is_last_developer: bool,
}

pub(crate) async fn show_user_delete(
    ctx: &AuthAdminCtx,
    identity: Identity,
    user_id: i64,
    csrf: String,
) -> Result<Response> {
    let row = sqlx::query("SELECT id, email, role FROM rustio_users WHERE id = $1")
        .bind(user_id)
        .fetch_optional(ctx.db.pool())
        .await?;
    let row = row.ok_or_else(|| Error::NotFound(format!("user #{user_id}")))?;
    let r = Row::from_pg(&row);

    let group_count: i64 =
        sqlx::query_scalar("SELECT COUNT(*) FROM rustio_user_groups WHERE user_id = $1")
            .bind(user_id)
            .fetch_one(ctx.db.pool())
            .await?;
    let session_count: i64 = sqlx::query_scalar(
        "SELECT COUNT(*) FROM rustio_sessions WHERE user_id = $1 AND expires_at > NOW()",
    )
    .bind(user_id)
    .fetch_one(ctx.db.pool())
    .await?;
    let direct_perm_count: i64 =
        sqlx::query_scalar("SELECT COUNT(*) FROM rustio_user_permissions WHERE user_id = $1")
            .bind(user_id)
            .fetch_one(ctx.db.pool())
            .await?;

    let is_self = identity.user_id == user_id;
    // Pretend the user is being demoted to nothing — that's what a
    // delete effectively is. `would_orphan_developers` returns true if
    // the target is the sole active developer.
    let is_last_developer =
        auth::would_orphan_developers(&ctx.db, user_id, Some(Role::User)).await?;

    let email = r.get_string("email")?;
    let view = UserDeleteCtx {
        base: BaseContext::new(Some(&identity), csrf, &ctx.admin),
        page_title: format!("Delete user: {email}"),
        entries: ctx
            .admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        user_id,
        email,
        role: r.get_string("role")?,
        group_count,
        session_count,
        direct_perm_count,
        is_self,
        is_last_developer,
    };
    let body = ctx
        .templates
        .render("admin/user_confirm_delete.html", &view)?;
    Ok(Response::html(body))
}

pub(crate) async fn do_user_delete(
    ctx: &AuthAdminCtx,
    identity: Identity,
    user_id: i64,
    _req: Request,
) -> Result<Response> {
    // Self-delete guard: an admin cannot delete their own logged-in
    // account. Without this, a successful POST would invalidate the
    // current session via cascade and leave the system in an odd state
    // (and the admin would need to re-login just to undo a typo).
    if identity.user_id == user_id {
        return Err(Error::BadRequest(
            "You cannot delete your own account while signed in.".into(),
        ));
    }

    // Last-developer guard. A delete is the strongest form of demotion;
    // reuse the helper by passing a non-Developer role.
    if auth::would_orphan_developers(&ctx.db, user_id, Some(Role::User)).await? {
        return Err(Error::BadRequest(
            "Cannot delete the last active developer. \
             Use rustio-cli to promote a backup developer first."
                .into(),
        ));
    }

    sqlx::query("DELETE FROM rustio_users WHERE id = $1")
        .bind(user_id)
        .execute(ctx.db.pool())
        .await?;

    // Cascade through user_groups, user_permissions, and sessions
    // happens at the FK level. The permission cache is keyed on
    // user_id — drop the entry so a re-created user with the same id
    // (vanishingly unlikely with BIGSERIAL but cheap insurance) starts
    // clean.
    auth::invalidate_user_cache(user_id);

    Ok(Response::redirect("/admin/users"))
}

// ---------- Groups ----------

#[derive(Serialize)]
struct GroupsListCtx {
    #[serde(flatten)]
    base: BaseContext,
    page_title: &'static str,
    entries: Vec<SidebarEntry>,
    groups: Vec<GroupRow>,
    flash: Option<FlashCtx>,
}

pub(crate) async fn list_groups(
    ctx: &AuthAdminCtx,
    identity: Identity,
    csrf: String,
) -> Result<Response> {
    let view = GroupsListCtx {
        base: BaseContext::new(Some(&identity), csrf, &ctx.admin),
        page_title: "Groups",
        entries: ctx
            .admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        groups: load_groups(&ctx.db).await?,
        flash: None,
    };
    let body = ctx.templates.render("admin/groups_list.html", &view)?;
    Ok(Response::html(body))
}

#[derive(Serialize)]
struct GroupEditCtx {
    #[serde(flatten)]
    base: BaseContext,
    page_title: String,
    entries: Vec<SidebarEntry>,
    group_id: i64,
    name: String,
    description: String,
    all_permissions: Vec<PermRow>,
    group_permissions: Vec<i64>,
    errors: Vec<String>,
    flash: Option<FlashCtx>,
    /// Phase 6.2 — General section (name + description) rendered
    /// through the shared FormField include. Permissions grid stays
    /// as a custom block (sanctioned per spec correction #2).
    sections: Vec<render::FormSection>,
}

#[derive(Serialize)]
struct PermRow {
    id: i64,
    name: String,
}

pub(crate) async fn show_group_edit(
    ctx: &AuthAdminCtx,
    identity: Identity,
    group_id: i64,
    csrf: String,
) -> Result<Response> {
    let row = sqlx::query("SELECT id, name, description FROM rustio_groups WHERE id = $1")
        .bind(group_id)
        .fetch_optional(ctx.db.pool())
        .await?;
    let row = row.ok_or_else(|| Error::NotFound(format!("group #{group_id}")))?;
    let r = Row::from_pg(&row);

    let all: Vec<PermRow> = {
        let rows = sqlx::query("SELECT id, name FROM rustio_permissions ORDER BY name ASC")
            .fetch_all(ctx.db.pool())
            .await?;
        rows.iter()
            .map(|r| {
                let r = Row::from_pg(r);
                Ok(PermRow {
                    id: r.get_i64("id")?,
                    name: r.get_string("name")?,
                })
            })
            .collect::<Result<Vec<_>>>()?
    };

    let current: Vec<i64> = sqlx::query_scalar::<_, i64>(
        "SELECT permission_id FROM rustio_group_permissions WHERE group_id = $1",
    )
    .bind(group_id)
    .fetch_all(ctx.db.pool())
    .await?;

    let name_str = r.get_string("name")?;
    let description_str = r.get_string("description")?;
    let view = GroupEditCtx {
        base: BaseContext::new(Some(&identity), csrf, &ctx.admin),
        page_title: format!("Edit group #{group_id}"),
        entries: ctx
            .admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        group_id,
        sections: render::group_form_sections(&name_str, &description_str),
        name: name_str,
        description: description_str,
        all_permissions: all,
        group_permissions: current,
        errors: vec![],
        flash: None,
    };
    let body = ctx.templates.render("admin/group_edit.html", &view)?;
    Ok(Response::html(body))
}

pub(crate) async fn do_group_edit(
    ctx: &AuthAdminCtx,
    _identity: Identity,
    group_id: i64,
    req: Request,
) -> Result<Response> {
    let form = req.form()?;
    let name = form.required("name")?;
    let description = form.get("description").unwrap_or("");

    sqlx::query("UPDATE rustio_groups SET name = $1, description = $2 WHERE id = $3")
        .bind(name)
        .bind(description)
        .bind(group_id)
        .execute(ctx.db.pool())
        .await?;

    // Rewrite permission assignment.
    sqlx::query("DELETE FROM rustio_group_permissions WHERE group_id = $1")
        .bind(group_id)
        .execute(ctx.db.pool())
        .await?;

    for (k, v) in form.as_map() {
        if let Some(id_str) = k.strip_prefix("perm_") {
            if v == "on" {
                if let Ok(pid) = id_str.parse::<i64>() {
                    sqlx::query(
                        "INSERT INTO rustio_group_permissions (group_id, permission_id)
                         VALUES ($1, $2) ON CONFLICT DO NOTHING",
                    )
                    .bind(group_id)
                    .bind(pid)
                    .execute(ctx.db.pool())
                    .await?;
                }
            }
        }
    }

    Ok(Response::redirect("/admin/groups"))
}

// ---------- Group delete (Phase 7a/0.5/sec1) ----------

#[derive(Serialize)]
struct GroupDeleteCtx {
    #[serde(flatten)]
    base: BaseContext,
    page_title: String,
    entries: Vec<SidebarEntry>,
    group_id: i64,
    name: String,
    description: String,
    /// How many users currently belong to this group. The delete
    /// cascades through `rustio_user_groups` (FK ON DELETE CASCADE)
    /// so the row count drops to zero on save.
    user_count: i64,
    /// How many permissions are currently attached. Cascade through
    /// `rustio_group_permissions`.
    perm_count: i64,
}

pub(crate) async fn show_group_delete(
    ctx: &AuthAdminCtx,
    identity: Identity,
    group_id: i64,
    csrf: String,
) -> Result<Response> {
    let row = sqlx::query("SELECT id, name, description FROM rustio_groups WHERE id = $1")
        .bind(group_id)
        .fetch_optional(ctx.db.pool())
        .await?;
    let row = row.ok_or_else(|| Error::NotFound(format!("group #{group_id}")))?;
    let r = Row::from_pg(&row);

    let user_count: i64 =
        sqlx::query_scalar("SELECT COUNT(*) FROM rustio_user_groups WHERE group_id = $1")
            .bind(group_id)
            .fetch_one(ctx.db.pool())
            .await?;
    let perm_count: i64 =
        sqlx::query_scalar("SELECT COUNT(*) FROM rustio_group_permissions WHERE group_id = $1")
            .bind(group_id)
            .fetch_one(ctx.db.pool())
            .await?;

    let name = r.get_string("name")?;
    let view = GroupDeleteCtx {
        base: BaseContext::new(Some(&identity), csrf, &ctx.admin),
        page_title: format!("Delete group: {name}"),
        entries: ctx
            .admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        group_id,
        name,
        description: r.get_string("description")?,
        user_count,
        perm_count,
    };
    let body = ctx
        .templates
        .render("admin/group_confirm_delete.html", &view)?;
    Ok(Response::html(body))
}

pub(crate) async fn do_group_delete(
    ctx: &AuthAdminCtx,
    _identity: Identity,
    group_id: i64,
    _req: Request,
) -> Result<Response> {
    // Capture every user that's losing this group BEFORE the cascade
    // wipes the M2M table — we need the ids to invalidate the perm
    // cache once their membership drops.
    let user_ids: Vec<i64> =
        sqlx::query_scalar("SELECT user_id FROM rustio_user_groups WHERE group_id = $1")
            .bind(group_id)
            .fetch_all(ctx.db.pool())
            .await?;

    // The FKs on rustio_user_groups + rustio_group_permissions are
    // ON DELETE CASCADE, so this single DELETE clears all M2M rows.
    sqlx::query("DELETE FROM rustio_groups WHERE id = $1")
        .bind(group_id)
        .execute(ctx.db.pool())
        .await?;

    // Cache invalidation has to be explicit — the cascade ran in PG,
    // not via our `remove_user_from_group` helper.
    for uid in user_ids {
        crate::auth::invalidate_user_cache(uid);
    }

    Ok(Response::redirect("/admin/groups"))
}

// ---------- New user ----------

#[derive(Serialize)]
struct UserNewCtx {
    #[serde(flatten)]
    base: BaseContext,
    page_title: &'static str,
    entries: Vec<SidebarEntry>,
    email: String,
    /// Selected role string for re-rendering on validation failure.
    /// Defaults to `"staff"` on a fresh form (Phase 7a/0.5/d).
    role: String,
    errors: Vec<String>,
    /// Phase 6.2 — sections drive the shared FormField include in
    /// user_new.html. Built from `email` + `role` via
    /// `render::user_new_form_sections`; the bespoke fields above
    /// remain for backward-compat with any external consumer that
    /// reads them but the template no longer renders raw inputs.
    sections: Vec<render::FormSection>,
}

pub(crate) async fn show_new_user(
    ctx: &AuthAdminCtx,
    identity: Identity,
    csrf: String,
) -> Result<Response> {
    let email = String::new();
    let role: String = "staff".into();
    let view = UserNewCtx {
        base: BaseContext::new(Some(&identity), csrf, &ctx.admin),
        page_title: "Add user",
        entries: ctx
            .admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        sections: render::user_new_form_sections(&email, &role),
        email,
        role,
        errors: Vec::new(),
    };
    let body = ctx.templates.render("admin/user_new.html", &view)?;
    Ok(Response::html(body))
}

/// Same minimum length used by the self-service password change page.
const MIN_NEW_USER_PASSWORD_LEN: usize = 8;

/// Cheap email-shape check — `<x>@<y>.<z>` with non-empty parts.
/// Matches what most folks expect from a "looks like an email"
/// validation; the canonical RFC check happens at deliverability time
/// elsewhere.
fn looks_like_email(s: &str) -> bool {
    let s = s.trim();
    let Some((local, domain)) = s.split_once('@') else {
        return false;
    };
    if local.is_empty() || domain.is_empty() {
        return false;
    }
    let Some((host, tld)) = domain.rsplit_once('.') else {
        return false;
    };
    !host.is_empty() && !tld.is_empty()
}

pub(crate) async fn do_new_user(
    ctx: &AuthAdminCtx,
    identity: Identity,
    req: Request,
) -> Result<Response> {
    let form = req.form()?;
    let email = form.get("email").unwrap_or("").trim().to_string();
    let password = form.get("password").unwrap_or("");
    let role_str = form.get("role").unwrap_or("staff").to_string();

    // Phase 7.5 — push every error twice: once into the global Vec
    // (catch-all banner) and once into the field-keyed map. Both
    // views render from the same source of truth; `apply_field_errors`
    // copies the keyed entries onto each FormField at re-render time.
    let mut errors: Vec<String> = Vec::new();
    let mut field_errors: HashMap<String, Vec<String>> = HashMap::new();

    // Parse role first so we can preserve the user's selection on
    // re-render even if other fields fail.
    let role_parsed = Role::parse(&role_str).ok();
    if role_parsed.is_none() {
        let msg = format!("Unknown role: \"{role_str}\".");
        errors.push(msg.clone());
        field_errors.entry("role".into()).or_default().push(msg);
    }

    if email.is_empty() {
        let msg = "Email is required.";
        errors.push(msg.into());
        field_errors
            .entry("email".into())
            .or_default()
            .push(msg.into());
    } else if !looks_like_email(&email) {
        let msg = "Enter a valid email address.";
        errors.push(msg.into());
        field_errors
            .entry("email".into())
            .or_default()
            .push(msg.into());
    } else {
        // Pre-check uniqueness for a clean message — the unique
        // constraint would otherwise surface as a Postgres error.
        let existing = auth::find_user_by_email(&ctx.db, &email).await?;
        if existing.is_some() {
            let msg = format!("A user with email \"{email}\" already exists.");
            errors.push(msg.clone());
            field_errors.entry("email".into()).or_default().push(msg);
        }
    }

    if password.len() < MIN_NEW_USER_PASSWORD_LEN {
        let msg = format!(
            "This password is too short. It must contain at least {MIN_NEW_USER_PASSWORD_LEN} characters."
        );
        errors.push(msg.clone());
        field_errors.entry("password".into()).or_default().push(msg);
    }

    if errors.is_empty() {
        let role = role_parsed.expect("role parsed when errors empty");
        let new_id = auth::create_user(&ctx.db, &email, password, role).await?;
        return Ok(Response::redirect(format!("/admin/users/{new_id}/edit")));
    }

    // Re-render with errors. Password is intentionally NOT echoed back —
    // the user retypes. Email and role selection ARE preserved.
    let csrf = req
        .ctx()
        .get::<crate::middleware::CsrfGuard>()
        .map(|g| g.token.clone())
        .unwrap_or_default();
    let mut sections = render::user_new_form_sections(&email, &role_str);
    render::apply_field_errors(&mut sections, &field_errors);
    let view = UserNewCtx {
        base: BaseContext::new(Some(&identity), csrf, &ctx.admin),
        page_title: "Add user",
        entries: ctx
            .admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        sections,
        email,
        role: role_str,
        errors,
    };
    let body = ctx.templates.render("admin/user_new.html", &view)?;
    Ok(Response::html(body).with_status(hyper::StatusCode::BAD_REQUEST))
}

// ---------- New group ----------

#[derive(Serialize)]
struct GroupNewCtx {
    #[serde(flatten)]
    base: BaseContext,
    page_title: &'static str,
    entries: Vec<SidebarEntry>,
    name: String,
    description: String,
    errors: Vec<String>,
    /// Phase 6.2 — General section (name + description) rendered
    /// through the shared FormField include.
    sections: Vec<render::FormSection>,
}

pub(crate) async fn show_new_group(
    ctx: &AuthAdminCtx,
    identity: Identity,
    csrf: String,
) -> Result<Response> {
    let name = String::new();
    let description = String::new();
    let view = GroupNewCtx {
        base: BaseContext::new(Some(&identity), csrf, &ctx.admin),
        page_title: "Add group",
        entries: ctx
            .admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        sections: render::group_form_sections(&name, &description),
        name,
        description,
        errors: Vec::new(),
    };
    let body = ctx.templates.render("admin/group_new.html", &view)?;
    Ok(Response::html(body))
}

pub(crate) async fn do_new_group(
    ctx: &AuthAdminCtx,
    identity: Identity,
    req: Request,
) -> Result<Response> {
    let form = req.form()?;
    let name = form.get("name").unwrap_or("").trim().to_string();
    let description = form.get("description").unwrap_or("").to_string();

    // Phase 7.5 — global Vec + field-keyed map, both populated in
    // lockstep. Only `name` has validators here; the description is
    // free-form.
    let mut errors: Vec<String> = Vec::new();
    let mut field_errors: HashMap<String, Vec<String>> = HashMap::new();
    if name.is_empty() {
        let msg = "Name is required.";
        errors.push(msg.into());
        field_errors
            .entry("name".into())
            .or_default()
            .push(msg.into());
    } else if name.len() > 150 {
        let msg = "Name must be 150 characters or fewer.";
        errors.push(msg.into());
        field_errors
            .entry("name".into())
            .or_default()
            .push(msg.into());
    }

    if errors.is_empty() {
        // INSERT — `ON CONFLICT (name) DO NOTHING` would mask the
        // duplicate-name error; let the unique-constraint violation
        // bubble up so the user sees a real error.
        let result = sqlx::query(
            "INSERT INTO rustio_groups (name, description) VALUES ($1, $2) RETURNING id",
        )
        .bind(&name)
        .bind(&description)
        .fetch_one(ctx.db.pool())
        .await;

        match result {
            Ok(row) => {
                let r = Row::from_pg(&row);
                let new_id: i64 = r.get_i64("id")?;
                return Ok(Response::redirect(format!("/admin/groups/{new_id}/edit")));
            }
            Err(sqlx::Error::Database(db_err)) if db_err.constraint().is_some() => {
                let msg = format!("A group named \"{name}\" already exists.");
                errors.push(msg.clone());
                field_errors.entry("name".into()).or_default().push(msg);
            }
            Err(e) => return Err(e.into()),
        }
    }

    let csrf = req
        .ctx()
        .get::<crate::middleware::CsrfGuard>()
        .map(|g| g.token.clone())
        .unwrap_or_default();
    let mut sections = render::group_form_sections(&name, &description);
    render::apply_field_errors(&mut sections, &field_errors);
    let view = GroupNewCtx {
        base: BaseContext::new(Some(&identity), csrf, &ctx.admin),
        page_title: "Add group",
        entries: ctx
            .admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        sections,
        name,
        description,
        errors,
    };
    let body = ctx.templates.render("admin/group_new.html", &view)?;
    Ok(Response::html(body).with_status(hyper::StatusCode::BAD_REQUEST))
}