rustio-admin 0.1.0

Django Admin, but for Rust. A small, focused admin framework.
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
//! The admin's data vocabulary. Kept separate from rendering and
//! handlers so changes here ripple out predictably.

// `for_testing[_failing_list]` + the PanicOps/FailingOps fixtures
// are part of the admin's test surface but no in-tree test exercises
// them yet (the legacy admin/macro_tests etc. land in a follow-up).
// Keep them gated behind cfg(test) elsewhere; allow dead inside that
// gate.
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use crate::error::Result;
use crate::http::FormData;
use crate::orm::{Db, Value};

pub(crate) type CreateResult<'a> =
    Pin<Box<dyn Future<Output = Result<std::result::Result<i64, Vec<String>>>> + Send + 'a>>;

pub(crate) type UpdateResult<'a> =
    Pin<Box<dyn Future<Output = Result<std::result::Result<(), Vec<String>>>> + Send + 'a>>;

// ---------------------------------------------------------------------------
// User profile extension API
// ---------------------------------------------------------------------------

/// One labeled section rendered in the project-extension area of the
/// built-in user profile page (admin/user_view.html — `{% block
/// project_user_fields %}`). A project's extension closure returns
/// `Vec<UserProfileSection>` so it can contribute multiple disjoint
/// areas in a single registration.
#[derive(Debug, Clone, serde::Serialize)]
pub struct UserProfileSection {
    pub label: String,
    pub rows: Vec<UserProfileRow>,
}

/// One key-value row inside a [`UserProfileSection`]. Both fields are
/// `String` so projects can format whatever shape they need. Rendered
/// escaped — pass plain text; for arbitrary HTML, projects override
/// the template block instead.
#[derive(Debug, Clone, serde::Serialize)]
pub struct UserProfileRow {
    pub label: String,
    pub value: String,
}

/// The boxed-closure shape stored on `Admin`. `pub(crate)` because
/// projects use the generic [`Admin::user_profile_extension`] builder
/// method and never have to name this directly.
pub(crate) type UserProfileExtensionFn =
    Arc<dyn Fn(Db, crate::auth::UserProfile) -> UserProfileExtensionFuture + Send + Sync + 'static>;

pub(crate) type UserProfileExtensionFuture =
    Pin<Box<dyn Future<Output = Result<Vec<UserProfileSection>>> + Send + 'static>>;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum FieldType {
    I32,
    I64,
    Bool,
    String,
    DateTime,
    OptionalI64,
    OptionalString,
    OptionalDateTime,
}

impl FieldType {
    pub fn widget(&self) -> &'static str {
        match self {
            FieldType::Bool => "checkbox",
            FieldType::DateTime | FieldType::OptionalDateTime => "datetime",
            FieldType::I32 | FieldType::I64 | FieldType::OptionalI64 => "number",
            FieldType::String | FieldType::OptionalString => "text",
        }
    }

    pub fn nullable(&self) -> bool {
        matches!(
            self,
            FieldType::OptionalI64 | FieldType::OptionalString | FieldType::OptionalDateTime
        )
    }
}

#[derive(Debug, Clone)]
pub struct AdminField {
    pub name: &'static str,
    pub label: &'static str,
    pub field_type: FieldType,
    pub editable: bool,
    pub relation: Option<AdminRelation>,
    /// Closed list of allowed string values for this field. When
    /// `Some`, the form layer renders a `<select>` with one option per
    /// entry. The values double as labels (raw, not humanised) per
    /// the "no invented content" rule.
    pub choices: Option<&'static [&'static str]>,
}

#[derive(Debug, Clone)]
pub struct AdminRelation {
    pub target_model: &'static str,
    pub display_field: Option<&'static str>,
    /// `true` for many-to-many relations (form renders
    /// `<select multiple>`), `false` for the default belongs-to
    /// (single `<select>`). Macro emits `false`; consumers that want
    /// M2M behaviour must hand-set this until the macro learns a
    /// `#[rustio(many_to_many)]` attribute.
    pub multi: bool,
}

/// What the `#[derive(RustioAdmin)]` macro produces for each struct.
pub trait AdminModel: Send + Sync + 'static {
    const ADMIN_NAME: &'static str;
    const DISPLAY_NAME: &'static str;
    const SINGULAR_NAME: &'static str;
    const FIELDS: &'static [AdminField];

    /// Render one row for the list page (column → display string).
    fn display_values(&self) -> Vec<(String, String)>;

    /// Populate a new instance from an HTTP form. Returns a list of
    /// validation errors if anything was wrong.
    fn from_form(form: &FormData) -> std::result::Result<Self, Vec<String>>
    where
        Self: Sized;

    /// A stable label for one instance (used on the delete confirm page).
    fn object_label(&self) -> String;

    fn id(&self) -> i64;

    fn values_to_update(&self) -> Vec<(&'static str, Value)>;
}

/// Runtime metadata about one admin-registered model. Captures both
/// the [`AdminModel`] static surface and the [`super::ModelAdmin`]
/// customisation values at registration time, so handlers read every
/// per-model knob from this struct instead of re-resolving traits.
pub struct AdminEntry {
    pub admin_name: &'static str,
    pub display_name: &'static str,
    pub singular_name: &'static str,
    /// SQL table name. For user-registered models this is `<M as Model>::TABLE`;
    /// for the synthetic core User entry it's `"rustio_users"`.
    pub table: &'static str,
    pub fields: &'static [AdminField],
    /// `true` only for framework-owned entries (currently just `User`).
    pub core: bool,
    /// `ModelAdmin::list_display()`. Empty → use every column on
    /// `fields`; non-empty → use exactly the listed names in order.
    pub list_display: &'static [&'static str],
    /// `ModelAdmin::list_filter()`. Empty by default.
    pub list_filter: &'static [&'static str],
    /// `ModelAdmin::search_fields()`. Empty by default.
    pub search_fields: &'static [&'static str],
    /// `ModelAdmin::ordering()`. Strings parsed via
    /// [`super::modeladmin::parse_order_spec`].
    pub ordering: &'static [&'static str],
    /// `ModelAdmin::list_per_page()`. Default 50.
    pub list_per_page: usize,
    /// `ModelAdmin::readonly_fields()`. Empty by default.
    pub readonly_fields: &'static [&'static str],
    /// `ModelAdmin::fieldsets()`. Empty → fall back to the
    /// framework's name-heuristic grouping.
    pub fieldsets: &'static [super::modeladmin::Fieldset],
    pub(crate) ops: Arc<dyn AdminOps>,
}

/// Per-request options for [`AdminOps::list`]. Empty / `None` fields
/// mean "framework default": no ordering override falls back to
/// `id DESC` inside the runtime, no filters skips the WHERE clause,
/// no limit fetches every row.
#[derive(Debug, Clone, Default)]
pub struct ListOpts {
    /// Validated `(column, dir)` pairs to apply as `ORDER BY`. The
    /// column name is bound to the model's `M::COLUMNS` set inside
    /// the runtime, so callers can pass user-supplied names without
    /// SQL-injection risk.
    pub ordering: Vec<(String, super::modeladmin::SortDir)>,
    /// `(column, value)` pairs applied as `WHERE col::text = $N`.
    /// Cast to text so the comparison matches the same string-shape
    /// semantics the in-memory pre-P10 filter used for bool / int /
    /// timestamp columns.
    pub filters: Vec<(String, String)>,
    /// Free-text search: `(term, columns)`. The runtime emits
    /// `WHERE (col1::text ILIKE $N OR col2::text ILIKE $N OR …)`
    /// with `$N = '%term%'`. An empty `term` or empty `columns`
    /// leaves the WHERE alone.
    pub search: Option<(String, Vec<String>)>,
    /// `LIMIT $N` for the data query. The COUNT(*) query never
    /// applies it. `None` → no limit.
    pub limit: Option<i64>,
    /// `OFFSET $N` for the data query. `None` or `Some(0)` → no offset.
    pub offset: Option<i64>,
}

/// Result of [`AdminOps::list`]: the requested page plus the total
/// row count under the same WHERE clause (so handlers can render
/// pagination footers without a separate query).
#[derive(Debug, Default)]
pub struct ListPage {
    pub rows: Vec<ListRow>,
    pub total: i64,
}

/// Type-erased CRUD operations. The `Admin::model::<M>()` call captures
/// a concrete `M: AdminModel + Model` and hides it behind this trait so
/// the router can treat every model uniformly. The single live impl is
/// [`super::ops::ConcreteOps<M>`].
pub(crate) trait AdminOps: Send + Sync {
    fn list<'a>(
        &'a self,
        db: &'a Db,
        opts: ListOpts,
    ) -> Pin<Box<dyn Future<Output = Result<ListPage>> + Send + 'a>>;

    fn find_row<'a>(
        &'a self,
        db: &'a Db,
        id: i64,
    ) -> Pin<Box<dyn Future<Output = Result<Option<EditRow>>> + Send + 'a>>;

    fn create<'a>(&'a self, db: &'a Db, form: &'a FormData) -> CreateResult<'a>;

    fn update<'a>(&'a self, db: &'a Db, id: i64, form: &'a FormData) -> UpdateResult<'a>;

    fn delete<'a>(
        &'a self,
        db: &'a Db,
        id: i64,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;

    fn object_label<'a>(
        &'a self,
        db: &'a Db,
        id: i64,
    ) -> Pin<Box<dyn Future<Output = Result<Option<String>>> + Send + 'a>>;
}

/// A row as shown on the list page.
#[derive(Debug)]
pub struct ListRow {
    pub id: i64,
    pub cells: Vec<String>,
}

/// The raw field values used to pre-fill the edit form.
#[derive(Debug)]
pub struct EditRow {
    #[allow(dead_code)]
    pub id: i64,
    pub values: Vec<(String, String)>,
}

/// Per-project admin branding. Defaults are RustIO-flavoured;
/// projects override via [`Admin::site_branding`].
#[derive(Clone, Debug)]
pub struct SiteBranding {
    pub site_title: String,
    pub site_header: String,
    pub index_title: String,
    pub footer_copyright: String,
    /// DNS-shape string available to project handlers; not surfaced in
    /// any framework template.
    pub domain: String,
}

impl Default for SiteBranding {
    fn default() -> Self {
        Self {
            site_title: "RustIO administration".into(),
            site_header: "RustIO administration".into(),
            index_title: "Site administration".into(),
            footer_copyright: format!("RustIO {}", env!("CARGO_PKG_VERSION")),
            domain: "rustio.local".into(),
        }
    }
}

/// Full admin chrome palette. Each field maps onto one of the
/// framework's `--rio-*` design tokens defined in `_base.html`, so
/// overriding these values via `Admin::theme(...)` re-skins the
/// entire admin shell without touching CSS.
///
/// Defaults match the framework's current chrome so a project that
/// doesn't call `.theme(...)` renders unchanged.
///
/// Hex form (`#rrggbb` or `rrggbb`); leading `#` is auto-normalised
/// at render time. Malformed values fall back to framework defaults
/// rather than panic — the admin path never breaks over a config typo.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AdminTheme {
    pub accent: String,
    pub bg: String,
    pub surface: String,
    pub text: String,
    pub text_muted: String,
    pub border: String,
}

impl Default for AdminTheme {
    fn default() -> Self {
        // Cobalt Blue light palette.
        Self {
            accent: "#2563EB".into(),
            bg: "#F4F6FB".into(),
            surface: "#FFFFFF".into(),
            text: "#111827".into(),
            text_muted: "#4B5563".into(),
            border: "#D1D5DB".into(),
        }
    }
}

/// Builder for the admin. Register models with `.model::<M>()`, then
/// hand it to the router via `register_admin_routes`.
pub struct Admin {
    pub(crate) entries: Vec<AdminEntry>,
    pub(crate) site_branding: SiteBranding,
    pub(crate) user_profile_ext: Option<UserProfileExtensionFn>,
    pub(crate) theme: AdminTheme,
}

impl Default for Admin {
    fn default() -> Self {
        Self::new()
    }
}

impl Admin {
    /// Constructs a new `Admin` with the framework's core entries
    /// pre-seeded. The only core entry is `User`; project models are
    /// added on top via [`Self::model`].
    pub fn new() -> Self {
        Self {
            entries: vec![core_user_entry()],
            site_branding: SiteBranding::default(),
            user_profile_ext: None,
            theme: AdminTheme::default(),
        }
    }

    /// Override the default RustIO branding.
    pub fn site_branding(mut self, branding: SiteBranding) -> Self {
        self.site_branding = branding;
        self
    }

    /// Read-only access to the active branding.
    pub fn branding(&self) -> &SiteBranding {
        &self.site_branding
    }

    /// Set the admin chrome's accent colour. Hex form, with or without
    /// the leading `#` (`"#1e6ba8"` and `"1e6ba8"` both work).
    pub fn accent_color(mut self, color: impl Into<String>) -> Self {
        self.theme.accent = normalise_hex(color);
        self
    }

    /// Set the entire admin chrome palette in one call. See
    /// [`AdminTheme`] for the field-by-field contract.
    pub fn theme(mut self, theme: AdminTheme) -> Self {
        self.theme = theme;
        self
    }

    /// Read-only access to the configured accent colour (`#rrggbb`).
    pub fn accent(&self) -> &str {
        &self.theme.accent
    }

    /// Read-only access to the active full theme.
    pub fn active_theme(&self) -> &AdminTheme {
        &self.theme
    }

    pub fn model<M>(mut self) -> Self
    where
        M: super::ModelAdmin + crate::orm::Model,
    {
        let ops: Arc<dyn AdminOps> = Arc::new(super::ops::ConcreteOps::<M>::new());
        self.entries.push(AdminEntry {
            admin_name: M::ADMIN_NAME,
            display_name: M::DISPLAY_NAME,
            singular_name: M::SINGULAR_NAME,
            table: <M as crate::orm::Model>::TABLE,
            fields: M::FIELDS,
            core: false,
            list_display: M::list_display(),
            list_filter: M::list_filter(),
            search_fields: M::search_fields(),
            ordering: M::ordering(),
            list_per_page: M::list_per_page(),
            readonly_fields: M::readonly_fields(),
            fieldsets: M::fieldsets(),
            ops,
        });
        self
    }

    pub fn entries(&self) -> &[AdminEntry] {
        &self.entries
    }

    /// Register a project-specific extension that contributes extra
    /// sections to the built-in user profile page. The closure is
    /// invoked on every render of `GET /admin/users/:id` (Overview tab);
    /// it receives the `Db` handle and the loaded
    /// [`crate::auth::UserProfile`] (no `password_hash`) and returns a
    /// `Vec<UserProfileSection>`. Sections render in the order returned,
    /// immediately after the core profile show-grid.
    ///
    /// Zero-config baseline: don't call this method, and the extension
    /// area stays empty. Projects that need richer layout than key-value
    /// rows override the `{% block project_user_fields %}` template
    /// block in `templates/admin/user_view.html` instead.
    pub fn user_profile_extension<F, Fut>(mut self, ext: F) -> Self
    where
        F: Fn(Db, crate::auth::UserProfile) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Vec<UserProfileSection>>> + Send + 'static,
    {
        self.user_profile_ext = Some(Arc::new(move |db, user| Box::pin(ext(db, user))));
        self
    }

    /// Internal accessor — handlers fetch the registered extension
    /// closure (if any) here. Used by `admin/builtin.rs` (P6.b).
    #[allow(dead_code)]
    pub(crate) fn user_profile_ext(&self) -> Option<&UserProfileExtensionFn> {
        self.user_profile_ext.as_ref()
    }

    pub fn find(&self, admin_name: &str) -> Option<&AdminEntry> {
        self.entries.iter().find(|e| e.admin_name == admin_name)
    }

    /// Register the canonical (add/change/delete/view) permissions for
    /// every model. Call during startup after `init_tables`.
    pub async fn seed_permissions(&self, db: &crate::orm::Db) -> crate::error::Result<()> {
        for entry in &self.entries {
            let singular = entry.singular_name.to_ascii_lowercase();
            crate::auth::register_model_permissions(db, entry.admin_name, &singular).await?;
        }
        Ok(())
    }
}

// -------------------------------------------------------------------------
// Core User entry — synthetic, route-only stub
// -------------------------------------------------------------------------
//
// Every project's admin index lists `Users` so operators can navigate
// to the bespoke `/admin/users/*` pages owned by `admin::builtin`. The
// `User` entry is built directly here rather than implementing
// `AdminModel` on a placeholder struct: the auth subsystem already
// owns the live `/admin/users` page with its own logic; routing
// through generic CRUD here would spawn a duplicate page.

const CORE_USER_FIELDS: &[AdminField] = &[
    AdminField {
        name: "id",
        label: "id",
        field_type: FieldType::I64,
        editable: false,
        relation: None,
        choices: None,
    },
    AdminField {
        name: "email",
        label: "email",
        field_type: FieldType::String,
        editable: true,
        relation: None,
        choices: None,
    },
    AdminField {
        name: "password_hash",
        label: "password_hash",
        field_type: FieldType::String,
        editable: false,
        relation: None,
        choices: None,
    },
    AdminField {
        name: "role",
        label: "role",
        field_type: FieldType::String,
        editable: true,
        relation: None,
        choices: None,
    },
    AdminField {
        name: "is_active",
        label: "is_active",
        field_type: FieldType::Bool,
        editable: true,
        relation: None,
        choices: None,
    },
    AdminField {
        name: "created_at",
        label: "created_at",
        field_type: FieldType::DateTime,
        editable: false,
        relation: None,
        choices: None,
    },
];

/// Normalise a user-supplied colour string to `#rrggbb` form. Accepts
/// both `"#1e6ba8"` and `"1e6ba8"`; trims whitespace; does NOT validate
/// that the body is hex (that's the renderer's job, where invalid
/// values fall back to the framework default rather than panic). The
/// `format!()` adds back exactly one leading `#`.
pub(crate) fn normalise_hex(input: impl Into<String>) -> String {
    let raw = input.into();
    let trimmed = raw.trim().trim_start_matches('#');
    format!("#{trimmed}")
}

fn core_user_entry() -> AdminEntry {
    AdminEntry {
        admin_name: "users",
        display_name: "Users",
        singular_name: "User",
        table: "rustio_users",
        fields: CORE_USER_FIELDS,
        core: true,
        list_display: &[],
        list_filter: &[],
        search_fields: &[],
        ordering: &["-id"],
        list_per_page: 50,
        readonly_fields: &[],
        fieldsets: &[],
        ops: Arc::new(CoreUserOps),
    }
}

/// Route-only stub for the synthetic User entry. The live
/// `/admin/users` page is wired separately by `admin::builtin`, so
/// every method here returns a dedicated error rather than silently
/// half-working. If the generic admin ever routes to this, the error
/// makes the misuse obvious.
struct CoreUserOps;

fn core_user_route_error() -> crate::error::Error {
    crate::error::Error::Internal(
        "the core User entry is route-only — use the dedicated /admin/users page".into(),
    )
}

impl AdminOps for CoreUserOps {
    fn list<'a>(
        &'a self,
        _db: &'a Db,
        _opts: ListOpts,
    ) -> Pin<Box<dyn Future<Output = Result<ListPage>> + Send + 'a>> {
        Box::pin(async { Err(core_user_route_error()) })
    }

    fn find_row<'a>(
        &'a self,
        _db: &'a Db,
        _id: i64,
    ) -> Pin<Box<dyn Future<Output = Result<Option<EditRow>>> + Send + 'a>> {
        Box::pin(async { Err(core_user_route_error()) })
    }

    fn create<'a>(&'a self, _db: &'a Db, _form: &'a FormData) -> CreateResult<'a> {
        Box::pin(async { Err(core_user_route_error()) })
    }

    fn update<'a>(&'a self, _db: &'a Db, _id: i64, _form: &'a FormData) -> UpdateResult<'a> {
        Box::pin(async { Err(core_user_route_error()) })
    }

    fn delete<'a>(
        &'a self,
        _db: &'a Db,
        _id: i64,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
        Box::pin(async { Err(core_user_route_error()) })
    }

    fn object_label<'a>(
        &'a self,
        _db: &'a Db,
        _id: i64,
    ) -> Pin<Box<dyn Future<Output = Result<Option<String>>> + Send + 'a>> {
        Box::pin(async { Err(core_user_route_error()) })
    }
}

// Test fixtures (PanicOps / FailingOps + AdminEntry::for_testing*) live
// with the legacy `admin/macro_tests.rs` etc. that haven't been ported
// yet. Re-add them here when the first in-tree test needs them.