Skip to main content

rustio_admin/admin/
modeladmin.rs

1//! `ModelAdmin` — Django-style customisation surface.
2//!
3//! Every model that ships through `Admin::model::<M>()` must
4//! implement `ModelAdmin`. The trait defines defaults for every
5//! method, so a project that wants standard behaviour writes a one-
6//! line empty impl:
7//!
8//! ```ignore
9//! use rustio_admin::ModelAdmin;
10//!
11//! impl ModelAdmin for Course {}            // accept every default
12//! ```
13//!
14//! Override only the methods you care about; the rest inherit the
15//! trait defaults:
16//!
17//! ```ignore
18//! impl ModelAdmin for Course {
19//!     fn list_display() -> &'static [&'static str] {
20//!         &["code", "title", "credit_hours", "is_published"]
21//!     }
22//!     fn list_filter()  -> &'static [&'static str] { &["status", "level"] }
23//!     fn search_fields() -> &'static [&'static str] { &["code", "title"] }
24//!     fn ordering()     -> &'static [&'static str] { &["code"] }
25//! }
26//! ```
27//!
28//! The values are captured into [`super::AdminEntry`] at registration
29//! time. The runtime reads them straight from the entry — no
30//! per-request virtual dispatch beyond the existing `dyn AdminOps`.
31//!
32//! ### Why no blanket impl?
33//!
34//! An earlier draft shipped `impl<T: AdminModel> ModelAdmin for T {}`
35//! so every derived `AdminModel` would auto-pick-up the defaults.
36//! That collides with Rust's coherence rules — without
37//! `feature(specialization)` (nightly-only), a blanket impl forbids
38//! any per-type impl, which would block project overrides entirely.
39//! The opt-in `impl ModelAdmin for X {}` is the standard stable-Rust
40//! pattern (serde, axum, std).
41
42use super::AdminModel;
43
44/// One named group of fields on the change form. The framework's
45/// default heuristic in [`super::render::form_ctx`] groups by name
46/// (Default / System / Advanced); a project that wants explicit
47/// section ordering returns a non-empty `&'static [Fieldset]` from
48/// [`ModelAdmin::fieldsets`] and the renderer honours that instead.
49#[derive(Debug, Clone)]
50pub struct Fieldset {
51    pub title: &'static str,
52    pub fields: &'static [&'static str],
53}
54
55/// Django-style customisation surface for a registered admin model.
56///
57/// Every type that implements [`AdminModel`] gets a default impl via
58/// the blanket below. Override the methods you care about; everything
59/// else inherits sensible defaults.
60pub trait ModelAdmin: AdminModel {
61    /// Columns shown on the list page, in order. Default: every
62    /// field declared on `AdminModel::FIELDS`.
63    ///
64    /// Returning `&[]` means "use the model's full field list" — the
65    /// list page expands the empty default into `M::FIELDS`. Any
66    /// non-empty slice replaces the defaults verbatim.
67    fn list_display() -> &'static [&'static str] {
68        &[]
69    }
70
71    /// Columns offered as filter chips in the sidebar. Default: none.
72    fn list_filter() -> &'static [&'static str] {
73        &[]
74    }
75
76    /// Columns searched by the list-page search box (case-insensitive
77    /// substring match). Default: none.
78    fn search_fields() -> &'static [&'static str] {
79        &[]
80    }
81
82    /// Default ordering. `-foo` for `foo DESC`, `foo` for `foo ASC`.
83    /// Multiple entries → multi-column ORDER BY in slice order.
84    /// Default: `["-id"]` (newest first).
85    fn ordering() -> &'static [&'static str] {
86        &["-id"]
87    }
88
89    /// Rows per page on the list view. Default: 50.
90    fn list_per_page() -> usize {
91        50
92    }
93
94    /// Read-only fields on the change form. Default: none.
95    fn readonly_fields() -> &'static [&'static str] {
96        &[]
97    }
98
99    /// Field grouping on the change form. Default: empty — fall back
100    /// to the framework heuristic (`Default` / `System` / `Advanced`).
101    fn fieldsets() -> &'static [Fieldset] {
102        &[]
103    }
104
105    /// Custom bulk actions surfaced as extra buttons in the list-view
106    /// bulk bar (next to the framework's built-in Delete). Default:
107    /// none.
108    ///
109    /// `BulkAction` is metadata only — the dispatcher
110    /// (`AdminOps::execute_bulk_action`) is what actually runs the
111    /// action on the selected rows. Project models that need a custom
112    /// action override `AdminOps::execute_bulk_action` to match on
113    /// `name` and apply the work; the framework's default impl
114    /// returns a clear `BadRequest` for any name it doesn't recognise,
115    /// so a forgotten implementation surfaces as an error page rather
116    /// than a silent no-op.
117    fn bulk_actions() -> &'static [BulkAction] {
118        &[]
119    }
120}
121
122/// One project-defined bulk action declared by
123/// [`ModelAdmin::bulk_actions`]. Static metadata only — see
124/// `AdminOps::execute_bulk_action` for the runtime dispatcher.
125#[derive(Debug, Clone, Copy)]
126pub struct BulkAction {
127    /// Stable URL slug. Routed at `POST /admin/:model/bulk/:name`.
128    /// Use snake_case identifiers; the framework reserves `delete`
129    /// for its built-in cascade-aware delete (handled separately at
130    /// `/bulk_delete`).
131    pub name: &'static str,
132    /// Human-readable button label. Rendered as-is in the bulk bar
133    /// and on the confirmation page header.
134    pub label: &'static str,
135    /// `true` → render the button with the framework's destructive
136    /// (red) styling. Use for actions that lose data or change state
137    /// in a hard-to-undo way.
138    pub destructive: bool,
139    /// `true` → POST shows a confirmation page first listing every
140    /// selected row; the user must click again to commit. `false` →
141    /// execute on the first POST. Default in the recommended call
142    /// pattern is `true` for any action a user might regret.
143    pub confirm: bool,
144}
145
146/// One column to sort by, with direction.
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub enum SortDir {
149    Asc,
150    Desc,
151}
152
153impl SortDir {
154    /// Stable SQL fragment.
155    pub fn sql(self) -> &'static str {
156        match self {
157            SortDir::Asc => "ASC",
158            SortDir::Desc => "DESC",
159        }
160    }
161}
162
163/// Parse one `ordering()` slice entry. `"-foo"` → (`"foo"`, Desc);
164/// `"foo"` → (`"foo"`, Asc).
165pub fn parse_order_spec(spec: &str) -> (String, SortDir) {
166    if let Some(rest) = spec.strip_prefix('-') {
167        (rest.to_string(), SortDir::Desc)
168    } else {
169        (spec.to_string(), SortDir::Asc)
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    #[test]
178    fn parse_order_spec_handles_leading_minus() {
179        assert_eq!(parse_order_spec("-id"), ("id".to_string(), SortDir::Desc));
180        assert_eq!(parse_order_spec("name"), ("name".to_string(), SortDir::Asc));
181    }
182
183    #[test]
184    fn sort_dir_sql_is_stable() {
185        assert_eq!(SortDir::Asc.sql(), "ASC");
186        assert_eq!(SortDir::Desc.sql(), "DESC");
187    }
188}