Skip to main content

rustango_cms/admin/
model_admin.rs

1//! Generic model-admin — a `ModelViewSet`-style CRUD admin for
2//! arbitrary `#[derive(Model)]` types, rendered inside the CMS admin
3//! chrome.
4//!
5//! The framework's own `ListView`/`ViewSet` can't inject the CMS's
6//! async, DB-backed `add_chrome`, so they can't back a chrome'd admin
7//! screen. This is a CMS-native path: a host registers a model with
8//! [`register_model_admin!`](crate::register_model_admin!), which captures the model's
9//! [`rustango::core::ModelSchema`] + a type-erased "list rows
10//! as JSON" thunk, and the admin serves a chrome'd index at
11//! `/cms-admin/model/<slug>` driven by the model's `list_display`.
12//!
13//! It ships the registry + the read-only index. Create / edit /
14//! delete (generic forms from `FieldSchema`) + filter / search / order
15//! are not implemented yet.
16
17use std::future::Future;
18use std::pin::Pin;
19
20use rustango::core::ModelSchema;
21use rustango::sql::Pool;
22
23/// Type-erased "fetch every row of the model as JSON" — the index
24/// data source. Built by [`register_model_admin!`](crate::register_model_admin!) from the concrete
25/// model's `objects().fetch()` (a derive-generated inherent
26/// method, so it can't be reached generically — hence the thunk).
27pub type ListRowsFn = fn(Pool) -> Pin<Box<dyn Future<Output = Vec<serde_json::Value>> + Send>>;
28
29/// One registered model admin.
30pub struct ModelAdmin {
31    /// URL slug under `/cms-admin/model/<slug>` (use the table name).
32    pub slug: &'static str,
33    /// Human-readable plural label for the index heading / nav.
34    pub label: &'static str,
35    /// The model's schema — drives the index columns (`list_display`).
36    pub schema: &'static ModelSchema,
37    /// Fetch all rows as JSON for the index.
38    pub list_rows: ListRowsFn,
39}
40
41inventory::collect!(ModelAdmin);
42
43/// Every registered model admin, sorted by slug.
44#[must_use]
45pub fn registered() -> Vec<&'static ModelAdmin> {
46    let mut v: Vec<_> = inventory::iter::<ModelAdmin>.into_iter().collect();
47    v.sort_by_key(|m| m.slug);
48    v
49}
50
51/// The model admin registered under `slug`, if any.
52#[must_use]
53pub fn find(slug: &str) -> Option<&'static ModelAdmin> {
54    inventory::iter::<ModelAdmin>
55        .into_iter()
56        .find(|m| m.slug == slug)
57}
58
59/// The index columns as `(field_name, header_label)` pairs. Uses the
60/// model's `admin(list_display = …)` when set; otherwise falls back to
61/// the `display` field, else the first few scalar fields — so a model
62/// with no admin hints still renders something useful.
63#[must_use]
64pub fn list_columns(schema: &ModelSchema) -> Vec<(String, String)> {
65    let names: Vec<&'static str> = schema
66        .admin
67        .map(|a| a.list_display)
68        .filter(|d| !d.is_empty())
69        .map(<[&'static str]>::to_vec)
70        .unwrap_or_else(|| {
71            schema
72                .display
73                .map(|d| vec![d])
74                .unwrap_or_else(|| schema.fields.iter().take(4).map(|f| f.name).collect())
75        });
76    names
77        .iter()
78        .map(|n| {
79            let label = schema
80                .field(n)
81                .map_or_else(|| (*n).to_owned(), |f| f.display_label().to_owned());
82            ((*n).to_owned(), label)
83        })
84        .collect()
85}
86
87/// Render one row's value for column `col` as a display string. Strings
88/// pass through; null / missing → empty; everything else → its compact
89/// JSON (numbers, bools, nested objects).
90#[must_use]
91pub fn row_cell(row: &serde_json::Value, col: &str) -> String {
92    match row.get(col) {
93        Some(serde_json::Value::String(s)) => s.clone(),
94        None | Some(serde_json::Value::Null) => String::new(),
95        Some(other) => other.to_string(),
96    }
97}
98
99/// Register a generic admin for a `#[derive(Model)]` type.
100///
101/// ```ignore
102/// rustango_cms::register_model_admin!(crate::Author, "author", "Authors");
103/// // → a chrome'd index at /cms-admin/model/author, columns from the
104/// //   model's admin(list_display = …).
105/// ```
106///
107/// The model must derive `serde::Serialize` (rows are serialized to
108/// JSON for the generic index).
109#[macro_export]
110macro_rules! register_model_admin {
111    ($ty:ty, $slug:expr, $label:expr $(,)?) => {
112        $crate::inventory::submit! {
113            $crate::admin::model_admin::ModelAdmin {
114                slug: $slug,
115                label: $label,
116                schema: <$ty as $crate::__private::Model>::SCHEMA,
117                list_rows: |pool: $crate::__private::Pool| {
118                    ::std::boxed::Box::pin(async move {
119                        use $crate::__private::FetcherPool as _;
120                        let rows: ::std::vec::Vec<$ty> =
121                            <$ty>::objects().fetch(&pool).await.unwrap_or_default();
122                        rows.iter()
123                            .filter_map(|r| $crate::__private::serde_json::to_value(r).ok())
124                            .collect::<::std::vec::Vec<$crate::__private::serde_json::Value>>()
125                    })
126                },
127            }
128        }
129    };
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    // Dogfood the macro on a real CMS model to prove it compiles +
137    // registers (Locale has an `admin(list_display = …)`).
138    crate::register_model_admin!(crate::locale::Locale, "__test_locale", "Test Locales");
139
140    #[test]
141    fn macro_registers_and_find_resolves() {
142        let ma = find("__test_locale").expect("registered");
143        assert_eq!(ma.label, "Test Locales");
144        assert_eq!(ma.schema.table, "cms_locale");
145        assert!(registered().iter().any(|m| m.slug == "__test_locale"));
146    }
147
148    #[test]
149    fn columns_come_from_list_display_with_labels() {
150        use rustango::core::Model as _;
151        let cols = list_columns(crate::locale::Locale::SCHEMA);
152        assert!(!cols.is_empty(), "a model with admin hints yields columns");
153        // Each column is (field_name, label); labels are non-empty.
154        assert!(cols.iter().all(|(n, l)| !n.is_empty() && !l.is_empty()));
155    }
156
157    #[test]
158    fn row_cell_stringifies_by_json_kind() {
159        let row = serde_json::json!({"code": "en", "sort_order": 3, "active": true, "x": null});
160        assert_eq!(row_cell(&row, "code"), "en"); // string: bare
161        assert_eq!(row_cell(&row, "sort_order"), "3"); // number
162        assert_eq!(row_cell(&row, "active"), "true"); // bool
163        assert_eq!(row_cell(&row, "x"), ""); // null → empty
164        assert_eq!(row_cell(&row, "missing"), ""); // absent → empty
165    }
166}