Skip to main content

rustango_cms/
page_type_model.rs

1//! [`PageType`] — the per-tenant `cms_page_type` row that gives each
2//! registered [`PageTypeHandler`](crate::PageTypeHandler) a stable id
3//! for `cms_page.page_type_id`. Rows are upserted by
4//! [`ensure_seeded`](crate::ensure_seeded).
5
6use rustango::sql::Auto;
7use rustango::Model;
8use serde::{Deserialize, Serialize};
9
10/// Per-tenant registry row describing a registered page type.
11///
12/// Each `PageTypeHandler` (the `Send + Sync` Rust trait) maps to a
13/// row in this table. The row is the database identity used by
14/// [`Page::page_type_id`](crate::Page) — handlers come and go with
15/// process restarts, but pages need a stable FK target.
16///
17/// Mirrors `rustango::ContentType` in shape: `(app_label,
18/// type_name)` is the natural key; `type_name` alone is unique
19/// across the process so user code can resolve a handler by name.
20#[derive(Model, Debug, Clone, Serialize, Deserialize)]
21#[rustango(
22    table = "cms_page_type",
23    app = "cms",
24    display = "verbose_name",
25    admin(
26        list_display = "type_name, verbose_name, app_label, default_template, is_creatable",
27        search_fields = "type_name, verbose_name",
28        ordering = "app_label, type_name",
29        list_filter = "app_label, is_creatable",
30    )
31)]
32pub struct PageType {
33    #[rustango(primary_key)]
34    pub id: Auto<i64>,
35
36    /// Logical app this type belongs to (e.g. `"cms_articles"`).
37    /// Lets the admin group page types and lets handlers in
38    /// different crates coexist without collision.
39    #[rustango(max_length = 100, index)]
40    pub app_label: String,
41
42    /// Stable identifier matching `PageTypeHandler::type_name()`.
43    /// Globally unique within the tenant; this is what user code
44    /// reads to find the right handler at render time.
45    #[rustango(max_length = 100, unique)]
46    pub type_name: String,
47
48    /// Human-readable label shown in the admin's "Add page" picker.
49    #[rustango(max_length = 200)]
50    pub verbose_name: String,
51
52    /// Tera template path the renderer falls back to when the
53    /// `Page` row doesn't override it. Resolved against the host
54    /// app's Tera instance.
55    ///
56    /// An **empty string is the "no template" sentinel** — a type that
57    /// exists only to answer JSON. See [`crate::page_view`].
58    #[rustango(max_length = 255)]
59    pub default_template: String,
60
61    /// Which representation this type serves on its public URL:
62    /// `"auto"` (default), `"html"`, or `"api"`.
63    ///
64    /// `auto` derives it from [`Self::default_template`] — blank means
65    /// JSON-only — so every pre-existing row keeps rendering exactly as
66    /// before. `api` serves JSON at the page's own URL under
67    /// `Accept: application/json`; `html` forces the template path.
68    /// Parsed leniently by [`crate::page_view::PageViewMode::parse`],
69    /// so an unrecognised value read by an older binary during a
70    /// rolling deploy behaves as `auto` rather than failing the request.
71    #[rustango(max_length = 16, default = "'auto'")]
72    pub view_mode: String,
73
74    /// When `false` the type cannot be picked from the "Add page"
75    /// menu — used for abstract / programmatically-created types.
76    pub is_creatable: bool,
77
78    /// JSON array of `type_name`s allowed as direct parents. Empty
79    /// array means no restriction. Stored as JSONB for cheap
80    /// updates without a schema migration when the rule shifts.
81    pub allowed_parent_types: serde_json::Value,
82
83    /// JSON array of `type_name`s allowed as direct children.
84    /// Symmetric with [`Self::allowed_parent_types`] — both lists
85    /// are checked at create / move time. Default `'[]'::jsonb`
86    /// ("no restriction") so existing rows pre-dating slice 0003
87    /// keep working.
88    #[rustango(default = "'[]'::jsonb")]
89    pub allowed_child_types: serde_json::Value,
90
91    /// Slug of the workflow pages of this type go through, chosen on the
92    /// admin's page-type form; empty means publish directly. A code
93    /// type's `PageTypeHandler::workflow_slug()` takes precedence.
94    #[rustango(max_length = 100, default = "''")]
95    pub workflow: String,
96
97    #[rustango(auto_now_add)]
98    pub created_at: Auto<chrono::DateTime<chrono::Utc>>,
99    #[rustango(auto_now)]
100    pub updated_at: Auto<chrono::DateTime<chrono::Utc>>,
101}
102
103impl PageType {
104    /// Type names this type may be created under; empty means anywhere.
105    ///
106    /// Read from the row, which holds the rule for every type: a code type
107    /// writes its handler's list at seed, an admin-made type stores what was
108    /// entered on its form.
109    #[must_use]
110    pub fn allowed_parents(&self) -> Vec<String> {
111        names(&self.allowed_parent_types)
112    }
113
114    /// The workflow pages of this type go through, by name, or `None` to
115    /// publish directly. A code type's `workflow_slug()` comes first, then
116    /// the choice made on the admin's page-type form.
117    #[must_use]
118    pub fn workflow_name(&self) -> Option<String> {
119        crate::page_type::find_handler(&self.type_name)
120            .and_then(|h| h.workflow_slug().map(str::to_owned))
121            .or_else(|| Some(self.workflow.trim().to_owned()).filter(|w| !w.is_empty()))
122    }
123
124    /// Type names allowed as this type's children; empty means any.
125    #[must_use]
126    pub fn allowed_children(&self) -> Vec<String> {
127        names(&self.allowed_child_types)
128    }
129}
130
131/// A JSON array of type names; anything else is no names.
132fn names(v: &serde_json::Value) -> Vec<String> {
133    v.as_array()
134        .map(|a| a.iter().filter_map(|s| s.as_str().map(str::to_owned)).filter(|s| !s.is_empty()).collect())
135        .unwrap_or_default()
136}