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, paged 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 one page of the model's rows as JSON" — the index
24/// data source. Called with `(pool, limit, offset)`; returns that window
25/// in primary-key order plus the total row count. Built by
26/// [`register_model_admin!`](crate::register_model_admin!) from the
27/// concrete model's `objects()` (a derive-generated inherent method, so
28/// it can't be reached generically — hence the thunk).
29pub type ListRowsFn =
30    fn(Pool, i64, i64) -> Pin<Box<dyn Future<Output = (Vec<serde_json::Value>, i64)> + Send>>;
31
32/// One registered model admin.
33pub struct ModelAdmin {
34    /// URL slug under `/cms-admin/model/<slug>` (use the table name).
35    pub slug: &'static str,
36    /// Human-readable plural label for the index heading / nav.
37    pub label: &'static str,
38    /// The model's schema — drives the index columns (`list_display`).
39    pub schema: &'static ModelSchema,
40    /// Fetch one page of rows as JSON for the index, with the total.
41    pub list_rows: ListRowsFn,
42}
43
44inventory::collect!(ModelAdmin);
45
46/// Every registered model admin, sorted by slug.
47#[must_use]
48pub fn registered() -> Vec<&'static ModelAdmin> {
49    let mut v: Vec<_> = inventory::iter::<ModelAdmin>.into_iter().collect();
50    v.sort_by_key(|m| m.slug);
51    v
52}
53
54/// The model admin registered under `slug`, if any.
55#[must_use]
56pub fn find(slug: &str) -> Option<&'static ModelAdmin> {
57    inventory::iter::<ModelAdmin>
58        .into_iter()
59        .find(|m| m.slug == slug)
60}
61
62/// The index columns as `(field_name, header_label)` pairs. Uses the
63/// model's `admin(list_display = …)` when set; otherwise falls back to
64/// the `display` field, else the first few scalar fields — so a model
65/// with no admin hints still renders something useful.
66#[must_use]
67pub fn list_columns(schema: &ModelSchema) -> Vec<(String, String)> {
68    let names: Vec<&'static str> = schema
69        .admin
70        .map(|a| a.list_display)
71        .filter(|d| !d.is_empty())
72        .map(<[&'static str]>::to_vec)
73        .unwrap_or_else(|| {
74            schema
75                .display
76                .map(|d| vec![d])
77                .unwrap_or_else(|| schema.fields.iter().take(4).map(|f| f.name).collect())
78        });
79    names
80        .iter()
81        .map(|n| {
82            let label = schema
83                .field(n)
84                .map_or_else(|| (*n).to_owned(), |f| f.display_label().to_owned());
85            ((*n).to_owned(), label)
86        })
87        .collect()
88}
89
90/// Render one row's value for column `col` as a display string. Strings
91/// pass through; null / missing → empty; everything else → its compact
92/// JSON (numbers, bools, nested objects).
93#[must_use]
94pub fn row_cell(row: &serde_json::Value, col: &str) -> String {
95    match row.get(col) {
96        Some(serde_json::Value::String(s)) => s.clone(),
97        None | Some(serde_json::Value::Null) => String::new(),
98        Some(other) => other.to_string(),
99    }
100}
101
102/// Register a generic admin for a `#[derive(Model)]` type.
103///
104/// ```ignore
105/// rustango_cms::register_model_admin!(crate::Author, "author", "Authors");
106/// // → a chrome'd index at /cms-admin/model/author, columns from the
107/// //   model's admin(list_display = …).
108/// ```
109///
110/// The model must derive `serde::Serialize` (rows are serialized to
111/// JSON for the generic index).
112#[macro_export]
113macro_rules! register_model_admin {
114    ($ty:ty, $slug:expr, $label:expr $(,)?) => {
115        $crate::inventory::submit! {
116            $crate::admin::model_admin::ModelAdmin {
117                slug: $slug,
118                label: $label,
119                schema: <$ty as $crate::__private::Model>::SCHEMA,
120                list_rows: |pool: $crate::__private::Pool, limit: i64, offset: i64| {
121                    ::std::boxed::Box::pin(async move {
122                        use $crate::__private::{CounterPool as _, FetcherPool as _};
123                        let total = <$ty>::objects().count(&pool).await.unwrap_or_default();
124                        let mut qs = <$ty>::objects();
125                        // A stable order, so paging neither repeats nor skips rows.
126                        if let ::std::option::Option::Some(pk) =
127                            <$ty as $crate::__private::Model>::SCHEMA.primary_key()
128                        {
129                            qs = qs.order_by(&[(pk.name, false)]);
130                        }
131                        let rows: ::std::vec::Vec<$ty> = qs
132                            .limit(limit)
133                            .offset(offset)
134                            .fetch(&pool)
135                            .await
136                            .unwrap_or_default();
137                        let rows = rows
138                            .iter()
139                            .filter_map(|r| $crate::__private::serde_json::to_value(r).ok())
140                            .collect::<::std::vec::Vec<$crate::__private::serde_json::Value>>();
141                        (rows, total)
142                    })
143                },
144            }
145        }
146    };
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    // Dogfood the macro on a real CMS model to prove it compiles +
154    // registers (Locale has an `admin(list_display = …)`).
155    crate::register_model_admin!(crate::locale::Locale, "__test_locale", "Test Locales");
156
157    #[test]
158    fn macro_registers_and_find_resolves() {
159        let ma = find("__test_locale").expect("registered");
160        assert_eq!(ma.label, "Test Locales");
161        assert_eq!(ma.schema.table, "cms_locale");
162        assert!(registered().iter().any(|m| m.slug == "__test_locale"));
163    }
164
165    #[test]
166    fn columns_come_from_list_display_with_labels() {
167        use rustango::core::Model as _;
168        let cols = list_columns(crate::locale::Locale::SCHEMA);
169        assert!(!cols.is_empty(), "a model with admin hints yields columns");
170        // Each column is (field_name, label); labels are non-empty.
171        assert!(cols.iter().all(|(n, l)| !n.is_empty() && !l.is_empty()));
172    }
173
174    #[test]
175    fn row_cell_stringifies_by_json_kind() {
176        let row = serde_json::json!({"code": "en", "sort_order": 3, "active": true, "x": null});
177        assert_eq!(row_cell(&row, "code"), "en"); // string: bare
178        assert_eq!(row_cell(&row, "sort_order"), "3"); // number
179        assert_eq!(row_cell(&row, "active"), "true"); // bool
180        assert_eq!(row_cell(&row, "x"), ""); // null → empty
181        assert_eq!(row_cell(&row, "missing"), ""); // absent → empty
182    }
183}
184
185#[cfg(all(test, feature = "sqlite"))]
186mod paging_tests {
187    use super::find;
188    use rustango::core::Model as _;
189    use rustango::sql::{Auto, Pool};
190
191    // Registered in `tests` above.
192    const SLUG: &str = "__test_locale";
193
194    #[tokio::test]
195    async fn list_rows_returns_one_window_in_key_order_and_the_total() {
196        let pool = Pool::connect("sqlite::memory:").await.expect("mem pool");
197        let ddl = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(
198            pool.dialect(),
199            crate::locale::Locale::SCHEMA,
200        );
201        for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
202            rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
203                .await
204                .expect("ddl");
205        }
206        for (i, code) in ["en", "fr", "de", "uk", "pl"].into_iter().enumerate() {
207            let mut l = crate::locale::Locale {
208                id: Auto::Unset,
209                code: code.to_owned(),
210                name: code.to_owned(),
211                is_default: i == 0,
212                active: true,
213                // Reverse of insertion, so key order is not sort order.
214                sort_order: 10 - i as i32,
215                created_at: Auto::Unset,
216            };
217            l.save(&pool).await.expect("locale");
218        }
219        let ma = find(SLUG).expect("registered");
220        let codes = |rows: &[serde_json::Value]| -> Vec<String> {
221            rows.iter().map(|r| r["code"].as_str().unwrap_or_default().to_owned()).collect()
222        };
223        let (first, total) = (ma.list_rows)(pool.clone(), 2, 0).await;
224        assert_eq!(total, 5);
225        assert_eq!(codes(&first), ["en", "fr"]);
226        let (last, _) = (ma.list_rows)(pool.clone(), 2, 4).await;
227        assert_eq!(codes(&last), ["pl"]);
228        let (past, total) = (ma.list_rows)(pool, 2, 10).await;
229        assert!(past.is_empty());
230        assert_eq!(total, 5);
231    }
232}