Skip to main content

rustango_cms/admin/
report.rs

1//! Extensible report framework — a registerable `Report` trait
2//! + the three reports the hardcoded
3//! set was missing: **page-types usage**, **unpublished changes**, and
4//! **your pages in a workflow**.
5//!
6//! A report is a slug, a title, a set of typed columns, and an async
7//! `rows()` that returns one JSON object per row (keyed by column key,
8//! plus an optional `edit_url` the table links the first cell to). The
9//! admin serves every registered report through one chrome'd dispatcher
10//! at `/cms-admin/report/<slug>` (+ a `.csv` export), and `_base.html`
11//! lists them under the Reports sidebar group via the registry — so a
12//! host adds a report with [`register_report!`](crate::register_report!) and it appears in the
13//! nav with no routing or template work.
14//!
15//! The seven pre-existing reports (aging / locked / scheduled /
16//! workflow / revisions / search / media-unused) keep their bespoke
17//! handlers for now — they carry extra UI (pagination, prune + edit
18//! actions, bulk delete) beyond a plain table; migrating them onto this
19//! framework is follow-up cleanup, not a prerequisite.
20
21use async_trait::async_trait;
22use rustango::sql::Pool;
23use serde_json::{json, Value};
24
25/// How a column's cell renders in the shared report table.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum ColumnKind {
28    /// Plain string.
29    Text,
30    /// Right-aligned numeric.
31    Number,
32    /// A status pill (`<span class="rcms-tag {value}">`).
33    Status,
34    /// An RFC 3339 timestamp rendered as relative + absolute time.
35    DateTime,
36}
37
38impl ColumnKind {
39    /// Stable token handed to the template for per-kind rendering.
40    #[must_use]
41    pub fn as_str(self) -> &'static str {
42        match self {
43            ColumnKind::Text => "text",
44            ColumnKind::Number => "number",
45            ColumnKind::Status => "status",
46            ColumnKind::DateTime => "datetime",
47        }
48    }
49}
50
51/// One report column: a `key` into each row object, a header `label`,
52/// and a render `kind`.
53#[derive(Debug, Clone)]
54pub struct ReportColumn {
55    pub key: &'static str,
56    pub label: &'static str,
57    pub kind: ColumnKind,
58}
59
60impl ReportColumn {
61    #[must_use]
62    pub const fn text(key: &'static str, label: &'static str) -> Self {
63        Self {
64            key,
65            label,
66            kind: ColumnKind::Text,
67        }
68    }
69    #[must_use]
70    pub const fn number(key: &'static str, label: &'static str) -> Self {
71        Self {
72            key,
73            label,
74            kind: ColumnKind::Number,
75        }
76    }
77    #[must_use]
78    pub const fn status(key: &'static str, label: &'static str) -> Self {
79        Self {
80            key,
81            label,
82            kind: ColumnKind::Status,
83        }
84    }
85    #[must_use]
86    pub const fn datetime(key: &'static str, label: &'static str) -> Self {
87        Self {
88            key,
89            label,
90            kind: ColumnKind::DateTime,
91        }
92    }
93}
94
95/// A registerable admin report. Implementors are zero-field structs
96/// registered with [`register_report!`](crate::register_report!).
97#[async_trait]
98pub trait Report: Send + Sync + 'static {
99    /// URL slug under `/cms-admin/report/<slug>` + the registry key.
100    fn slug(&self) -> &'static str;
101    /// Heading + sidebar label.
102    fn title(&self) -> &'static str;
103    /// Optional one-line blurb shown under the heading.
104    fn description(&self) -> Option<&'static str> {
105        None
106    }
107    /// Optional Material Symbols icon name for the sidebar.
108    fn icon(&self) -> Option<&'static str> {
109        None
110    }
111    /// The table columns, left to right.
112    fn columns(&self) -> Vec<ReportColumn>;
113    /// Build the rows. Each row is a JSON object keyed by column key;
114    /// an optional `edit_url` key links the first cell. `user_id` is
115    /// the signed-in user (for "your …"-style reports); `None` for an
116    /// unauthenticated context.
117    async fn rows(&self, pool: &Pool, user_id: Option<i64>) -> Vec<Value>;
118}
119
120/// Inventory registration — mirrors [`crate::admin::admin_page`].
121pub struct ReportRegistration {
122    pub factory: fn() -> Box<dyn Report>,
123}
124
125inventory::collect!(ReportRegistration);
126
127/// Every registered report, sorted by title.
128#[must_use]
129pub fn registered_reports() -> Vec<Box<dyn Report>> {
130    let mut v: Vec<Box<dyn Report>> = inventory::iter::<ReportRegistration>
131        .into_iter()
132        .map(|r| (r.factory)())
133        .collect();
134    v.sort_by(|a, b| a.title().cmp(b.title()));
135    v
136}
137
138/// The report registered under `slug`, if any.
139#[must_use]
140pub fn find_report(slug: &str) -> Option<Box<dyn Report>> {
141    registered_reports().into_iter().find(|r| r.slug() == slug)
142}
143
144/// Register a [`Report`] implementation.
145///
146/// ```ignore
147/// #[derive(Default)]
148/// struct MyReport;
149/// #[async_trait::async_trait]
150/// impl rustango_cms::admin::report::Report for MyReport { /* … */ }
151/// rustango_cms::register_report!(MyReport);
152/// ```
153#[macro_export]
154macro_rules! register_report {
155    ($ty:ty) => {
156        $crate::inventory::submit! {
157            $crate::admin::report::ReportRegistration {
158                factory: || ::std::boxed::Box::new(<$ty>::default()),
159            }
160        }
161    };
162}
163
164// ============================================================ built-in reports
165
166fn page_edit_url(id: i64) -> String {
167    format!("/cms-admin/pages/{id}/edit")
168}
169
170fn rfc3339<Tz: chrono::TimeZone>(dt: &chrono::DateTime<Tz>) -> String {
171    dt.to_rfc3339()
172}
173
174/// **Page-types usage** — how many pages exist of each
175/// registered page type. Surfaces unused types + content distribution.
176#[derive(Default)]
177pub struct PageTypesUsageReport;
178
179#[async_trait]
180impl Report for PageTypesUsageReport {
181    fn slug(&self) -> &'static str {
182        "page-types"
183    }
184    fn title(&self) -> &'static str {
185        "Page types usage"
186    }
187    fn description(&self) -> Option<&'static str> {
188        Some("How many pages exist of each registered page type.")
189    }
190    fn icon(&self) -> Option<&'static str> {
191        Some("category")
192    }
193    fn columns(&self) -> Vec<ReportColumn> {
194        vec![
195            ReportColumn::text("type", "Type"),
196            ReportColumn::text("identifier", "Identifier"),
197            ReportColumn::text("app", "App"),
198            ReportColumn::number("pages", "Pages"),
199        ]
200    }
201    async fn rows(&self, pool: &Pool, _user_id: Option<i64>) -> Vec<Value> {
202        use crate::page::Page;
203        use crate::page_type_model::PageType;
204        use rustango::sql::FetcherPool as _;
205
206        let pages: Vec<Page> = Page::objects().fetch(pool).await.unwrap_or_default();
207        let mut counts: std::collections::HashMap<i64, i64> = std::collections::HashMap::new();
208        for p in &pages {
209            *counts.entry(p.page_type_id).or_insert(0) += 1;
210        }
211        let mut types: Vec<PageType> = PageType::objects().fetch(pool).await.unwrap_or_default();
212        // App, then type, alphabetically — stable + scannable.
213        types.sort_by(|a, b| {
214            a.app_label
215                .cmp(&b.app_label)
216                .then_with(|| a.verbose_name.cmp(&b.verbose_name))
217        });
218        types
219            .iter()
220            .map(|t| {
221                let count =
222                    t.id.get()
223                        .copied()
224                        .and_then(|id| counts.get(&id).copied())
225                        .unwrap_or(0);
226                json!({
227                    "type": t.verbose_name,
228                    "identifier": t.type_name,
229                    "app": t.app_label,
230                    "pages": count,
231                })
232            })
233            .collect()
234    }
235}
236
237/// **Unpublished changes** — pages that were published once but now sit
238/// in draft (the editor saved a draft of a live page). In this CMS the
239/// page row's `status` is the editor's chosen status, so a previously
240/// published page (`published_at` set) currently at `status = draft`
241/// has edits not yet re-published.
242#[derive(Default)]
243pub struct UnpublishedChangesReport;
244
245#[async_trait]
246impl Report for UnpublishedChangesReport {
247    fn slug(&self) -> &'static str {
248        "unpublished-changes"
249    }
250    fn title(&self) -> &'static str {
251        "Unpublished changes"
252    }
253    fn description(&self) -> Option<&'static str> {
254        Some("Previously published pages with draft edits not yet re-published.")
255    }
256    fn icon(&self) -> Option<&'static str> {
257        Some("edit_note")
258    }
259    fn columns(&self) -> Vec<ReportColumn> {
260        vec![
261            ReportColumn::text("title", "Page"),
262            ReportColumn::status("status", "Status"),
263            ReportColumn::datetime("last_published", "Last published"),
264            ReportColumn::datetime("edited", "Draft edited"),
265        ]
266    }
267    async fn rows(&self, pool: &Pool, _user_id: Option<i64>) -> Vec<Value> {
268        use crate::page::{Page, PageStatus};
269        use rustango::core::Column as _;
270        use rustango::sql::FetcherPool as _;
271
272        let mut pages: Vec<Page> = Page::objects()
273            .where_(Page::status.eq(PageStatus::Draft.as_str().to_owned()))
274            .fetch(pool)
275            .await
276            .unwrap_or_default();
277        // Only drafts of *previously published* pages — a brand-new
278        // never-published draft has no live version to diverge from.
279        pages.retain(|p| p.published_at.is_some());
280        // Most-recently-edited first.
281        pages.sort_by(|a, b| {
282            b.updated_at
283                .get()
284                .copied()
285                .cmp(&a.updated_at.get().copied())
286        });
287        pages
288            .iter()
289            .map(|p| {
290                let id = p.id.get().copied().unwrap_or_default();
291                json!({
292                    "title": p.title,
293                    "status": p.status,
294                    "last_published": p.last_published_at.as_ref().map(rfc3339),
295                    "edited": p.updated_at.get().map(rfc3339),
296                    "edit_url": page_edit_url(id),
297                })
298            })
299            .collect()
300    }
301}
302
303/// **Your pages in a workflow** — pages the signed-in user submitted
304/// that are still in flight (in progress or sent back for changes).
305#[derive(Default)]
306pub struct WorkflowYourPagesReport;
307
308#[async_trait]
309impl Report for WorkflowYourPagesReport {
310    fn slug(&self) -> &'static str {
311        "your-workflow-pages"
312    }
313    fn title(&self) -> &'static str {
314        "Your pages in a workflow"
315    }
316    fn description(&self) -> Option<&'static str> {
317        Some("Pages you submitted that are still awaiting a workflow decision.")
318    }
319    fn icon(&self) -> Option<&'static str> {
320        Some("rule")
321    }
322    fn columns(&self) -> Vec<ReportColumn> {
323        vec![
324            ReportColumn::text("page", "Page"),
325            ReportColumn::text("workflow", "Workflow"),
326            ReportColumn::status("status", "Status"),
327            ReportColumn::text("current_step", "Current step"),
328            ReportColumn::datetime("submitted", "Submitted"),
329        ]
330    }
331    async fn rows(&self, pool: &Pool, user_id: Option<i64>) -> Vec<Value> {
332        use crate::page::Page;
333        use crate::workflow::{Workflow, WorkflowState, WorkflowStatus, WorkflowTask};
334        use rustango::core::Column as _;
335        use rustango::sql::FetcherPool as _;
336
337        let Some(uid) = user_id else {
338            return Vec::new();
339        };
340        let states: Vec<WorkflowState> = WorkflowState::objects()
341            .where_(WorkflowState::requested_by.eq(uid))
342            .where_(WorkflowState::status.is_in([
343                WorkflowStatus::InProgress.as_str().to_owned(),
344                WorkflowStatus::NeedsChanges.as_str().to_owned(),
345            ]))
346            .order_by(&[("requested_at", true)]) // newest first
347            .fetch(pool)
348            .await
349            .unwrap_or_default();
350        if states.is_empty() {
351            return Vec::new();
352        }
353        // Bulk-resolve the joined names so the report is a few queries,
354        // not one-per-row.
355        let pages: std::collections::HashMap<i64, Page> = Page::objects()
356            .fetch(pool)
357            .await
358            .unwrap_or_default()
359            .into_iter()
360            .filter_map(|p| p.id.get().copied().map(|id| (id, p)))
361            .collect();
362        let workflows: std::collections::HashMap<i64, String> = Workflow::objects()
363            .fetch(pool)
364            .await
365            .unwrap_or_default()
366            .into_iter()
367            .filter_map(|w| w.id.get().copied().map(|id| (id, w.name)))
368            .collect();
369        let tasks: std::collections::HashMap<i64, String> = WorkflowTask::objects()
370            .fetch(pool)
371            .await
372            .unwrap_or_default()
373            .into_iter()
374            .filter_map(|t| t.id.get().copied().map(|id| (id, t.name)))
375            .collect();
376
377        states
378            .iter()
379            .map(|s| {
380                let page = pages.get(&s.page_id);
381                let title = page.map_or("(deleted page)", |p| p.title.as_str());
382                let edit_url = page.and_then(|p| p.id.get().copied()).map(page_edit_url);
383                let workflow = workflows.get(&s.workflow_id).map_or("—", String::as_str);
384                let step = s
385                    .current_task_id
386                    .and_then(|tid| tasks.get(&tid))
387                    .map_or("—", String::as_str);
388                json!({
389                    "page": title,
390                    "workflow": workflow,
391                    "status": s.status,
392                    "current_step": step,
393                    "submitted": s.requested_at.get().map(rfc3339),
394                    "edit_url": edit_url,
395                })
396            })
397            .collect()
398    }
399}
400
401register_report!(PageTypesUsageReport);
402register_report!(UnpublishedChangesReport);
403register_report!(WorkflowYourPagesReport);
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408
409    #[test]
410    fn three_builtin_reports_register() {
411        let reports = registered_reports();
412        for slug in ["page-types", "unpublished-changes", "your-workflow-pages"] {
413            assert!(
414                reports.iter().any(|r| r.slug() == slug),
415                "report `{slug}` should be registered"
416            );
417        }
418    }
419
420    #[test]
421    fn find_resolves_by_slug_and_misses_cleanly() {
422        assert!(find_report("page-types").is_some());
423        assert_eq!(
424            find_report("page-types").unwrap().title(),
425            "Page types usage"
426        );
427        assert!(find_report("no-such-report").is_none());
428    }
429
430    #[test]
431    fn registered_reports_sorted_by_title() {
432        let titles: Vec<&str> = registered_reports().iter().map(|r| r.title()).collect();
433        let mut sorted = titles.clone();
434        sorted.sort_unstable();
435        assert_eq!(titles, sorted, "registry should be title-sorted");
436    }
437
438    #[test]
439    fn column_kinds_have_stable_tokens() {
440        assert_eq!(ColumnKind::Text.as_str(), "text");
441        assert_eq!(ColumnKind::Number.as_str(), "number");
442        assert_eq!(ColumnKind::Status.as_str(), "status");
443        assert_eq!(ColumnKind::DateTime.as_str(), "datetime");
444    }
445
446    #[test]
447    fn column_builders_set_kind() {
448        assert_eq!(ReportColumn::text("a", "A").kind, ColumnKind::Text);
449        assert_eq!(ReportColumn::number("a", "A").kind, ColumnKind::Number);
450        assert_eq!(ReportColumn::status("a", "A").kind, ColumnKind::Status);
451        assert_eq!(ReportColumn::datetime("a", "A").kind, ColumnKind::DateTime);
452    }
453
454    #[test]
455    fn every_report_declares_columns() {
456        for r in registered_reports() {
457            assert!(!r.columns().is_empty(), "{} has no columns", r.slug());
458        }
459    }
460}