use rustango::sql::Auto;
use crate::log_err::LogErr as _;
use rustango::Model;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PageStatus {
Draft,
Scheduled,
Published,
Archived,
Expired,
}
impl PageStatus {
pub const ALL: [Self; 5] = [
Self::Draft,
Self::Scheduled,
Self::Published,
Self::Archived,
Self::Expired,
];
pub const PUBLIC: [Self; 2] = [Self::Published, Self::Archived];
pub const EDITABLE: [Self; 4] = [Self::Draft, Self::Scheduled, Self::Published, Self::Archived];
#[must_use]
pub fn parse_editable(s: &str) -> Option<Self> {
Self::EDITABLE.into_iter().find(|v| v.as_str() == s)
}
#[must_use]
pub fn public_strings() -> [String; 2] {
Self::PUBLIC.map(|s| s.as_str().to_owned())
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|v| v.as_str() == s)
}
pub fn as_str(self) -> &'static str {
match self {
Self::Draft => "draft",
Self::Scheduled => "scheduled",
Self::Published => "published",
Self::Archived => "archived",
Self::Expired => "expired",
}
}
#[must_use]
pub fn is_public(self) -> bool {
matches!(self, Self::Published | Self::Archived)
}
#[must_use]
pub fn str_is_public(status: &str) -> bool {
status == Self::Published.as_str() || status == Self::Archived.as_str()
}
#[must_use]
pub fn str_goes_live(from: &str, to: &str) -> bool {
from != to && (Self::str_is_public(to) || to == Self::Scheduled.as_str())
}
}
#[derive(Model, Debug, Clone, Serialize, Deserialize)]
#[rustango(
table = "cms_page",
app = "cms",
display = "title",
admin(
list_display = "title, slug, page_type_id, status, depth, published_at",
search_fields = "title, slug",
ordering = "path",
list_filter = "page_type_id, status",
)
)]
pub struct Page {
#[rustango(primary_key)]
pub id: Auto<i64>,
#[rustango(fk = "cms_page_type", on = "id", index)]
pub page_type_id: i64,
#[rustango(max_length = 255)]
pub title: String,
#[rustango(max_length = 255)]
pub slug: String,
#[rustango(max_length = 510, index)]
pub path: String,
#[rustango(max_length = 510, index, default = "''")]
pub url_path: String,
pub depth: i32,
#[rustango(fk = "self", on = "id")]
pub parent_id: Option<i64>,
#[rustango(fk = "self", on = "id")]
pub locale_variant_of: Option<i64>,
#[rustango(fk = "self", on = "id")]
pub alias_of: Option<i64>,
#[rustango(fk = "cms_theme", on = "id")]
pub theme_id: Option<i64>,
pub sort_order: i32,
#[rustango(max_length = 16, index)]
pub status: String,
pub published_at: Option<chrono::DateTime<chrono::Utc>>,
#[serde(default)]
pub last_published_at: Option<chrono::DateTime<chrono::Utc>>,
pub go_live_at: Option<chrono::DateTime<chrono::Utc>>,
pub expire_at: Option<chrono::DateTime<chrono::Utc>>,
#[rustango(max_length = 70)]
pub seo_title: String,
#[rustango(max_length = 200)]
pub seo_description: String,
#[rustango(default = "true")]
pub robots_index: bool,
#[rustango(default = "0.5")]
pub sitemap_priority: f32,
#[rustango(max_length = 510, default = "''")]
pub preview_path: String,
#[rustango(max_length = 255, default = "''")]
pub template_override: String,
#[rustango(default = "false")]
pub show_in_menus: bool,
#[rustango(max_length = 120, default = "''")]
pub og_title: String,
#[rustango(max_length = 300, default = "''")]
pub og_description: String,
#[rustango(fk = "cms_media", on = "id")]
pub og_image_media_id: Option<i64>,
#[rustango(max_length = 32, default = "'summary_large_image'")]
pub twitter_card: String,
#[rustango(default = "false")]
pub notification_pre_published_sent: bool,
#[rustango(auto_now_add)]
pub created_at: Auto<chrono::DateTime<chrono::Utc>>,
#[rustango(auto_now)]
pub updated_at: Auto<chrono::DateTime<chrono::Utc>>,
}
#[derive(Debug, Clone, Default)]
pub struct ScheduleSweepResult {
pub published: usize,
pub expired: usize,
pub changed_urls: Vec<String>,
pub went_live: Vec<Page>,
pub taken_down: Vec<i64>,
}
pub async fn went_live_effects(pool: &rustango::sql::Pool, tenant_slug: &str, page: &Page, user_id: Option<i64>) {
crate::task_queue::sync_page_search(tenant_slug, page).await;
crate::hooks::fire_after_publish_page(crate::hooks::HookCtx::new(pool, tenant_slug, user_id), page).await;
}
pub async fn record_sweep_publishes(
pool: &rustango::sql::Pool,
tenant_slug: &str,
result: &ScheduleSweepResult,
mailer: Option<(&dyn rustango::email::Mailer, &str)>,
) {
let fallback = crate::task_queue::default_mailer();
let mailer = mailer.or_else(|| fallback.as_ref().map(|(m, from)| (m.as_ref(), from.as_str())));
for page in &result.went_live {
let id = page.id.get().copied().unwrap_or_default();
crate::page_log::record_or_warn(
pool,
id,
crate::page_log::ACTION_PUBLISH,
None,
format!("Published “{}” on schedule.", page.title),
None,
)
.await;
if let Some((m, from)) = mailer {
crate::page_subscription::notify_publish(
Some(m),
from,
pool,
tenant_slug,
id,
&page.title,
&page.url_path,
None,
)
.await;
}
}
}
pub async fn apply_sweep_effects(pool: &rustango::sql::Pool, tenant_slug: &str, result: &ScheduleSweepResult) {
for page in &result.went_live {
went_live_effects(pool, tenant_slug, page, None).await;
}
for id in &result.taken_down {
crate::task_queue::remove_page_search(tenant_slug, *id).await;
}
}
pub async fn run_schedule_sweep(
pool: &rustango::sql::Pool,
) -> Result<ScheduleSweepResult, rustango::sql::ExecError> {
use rustango::core::Column as _;
use rustango::sql::FetcherPool as _;
let now = chrono::Utc::now();
let mut published = 0usize;
let mut expired = 0usize;
let mut changed_urls: Vec<String> = Vec::new();
let mut went_live: Vec<Page> = Vec::new();
let mut taken_down: Vec<i64> = Vec::new();
let due_publish: Vec<Page> = Page::objects()
.where_(Page::status.eq(PageStatus::Scheduled.as_str().to_owned()))
.where_(Page::go_live_at.lte(Some(now)))
.fetch(pool)
.await?;
for p in due_publish {
let mut set = vec![
("status", PageStatus::Published.as_str().into()),
("last_published_at", now.into()),
];
if p.published_at.is_none() {
set.push(("published_at", now.into()));
}
if flip(pool, &p, PageStatus::Scheduled, set).await? {
changed_urls.push(p.url_path.clone());
published += 1;
let mut live = p;
live.status = PageStatus::Published.as_str().to_owned();
went_live.push(live);
}
}
let due_expire: Vec<Page> = Page::objects()
.where_(Page::status.eq(PageStatus::Published.as_str().to_owned()))
.where_(Page::expire_at.lte(Some(now)))
.fetch(pool)
.await?;
for p in due_expire {
let set = vec![("status", PageStatus::Expired.as_str().into())];
if flip(pool, &p, PageStatus::Published, set).await? {
changed_urls.push(p.url_path.clone());
expired += 1;
taken_down.extend(p.id.get().copied());
}
}
Ok(ScheduleSweepResult {
published,
expired,
changed_urls,
went_live,
taken_down,
})
}
async fn flip(
pool: &rustango::sql::Pool,
page: &Page,
from: PageStatus,
set: Vec<(&'static str, rustango::core::SqlValue)>,
) -> Result<bool, rustango::sql::ExecError> {
use rustango::core::Column as _;
use rustango::sql::UpdaterPool as _;
let id = page.id.get().copied().unwrap_or_default();
let mut update = Page::objects()
.where_(Page::id.eq(id))
.where_(Page::status.eq(from.as_str().to_owned()))
.update();
for (column, value) in set {
update = update.set(column, value);
}
Ok(update.execute_pool(pool).await? == 1)
}
pub async fn run_schedule_sweep_and_purge(
pool: &rustango::sql::Pool,
tenant: &rustango::tenancy::TenantSlug,
invalidator: std::sync::Arc<dyn crate::cache_invalidate::PageCacheInvalidator>,
) -> Result<ScheduleSweepResult, rustango::sql::ExecError> {
let result = run_schedule_sweep(pool).await?;
if !result.changed_urls.is_empty() {
crate::task_queue::purge_urls(invalidator, tenant.clone(), result.changed_urls.clone())
.await;
}
apply_sweep_effects(pool, &tenant.slug, &result).await;
record_sweep_publishes(pool, &tenant.slug, &result, None).await;
Ok(result)
}
pub async fn run_schedule_sweep_with_mailer(
pool: &rustango::sql::Pool,
mailer: Option<&dyn rustango::email::Mailer>,
from: &str,
tenant_slug: &str,
) -> Result<ScheduleSweepResult, rustango::sql::ExecError> {
use rustango::core::Column as _;
use rustango::sql::FetcherPool as _;
if let Some(m) = mailer {
let now = chrono::Utc::now();
let horizon = now + chrono::Duration::hours(1);
let scheduled: Vec<Page> = Page::objects()
.where_(Page::status.eq(PageStatus::Scheduled.as_str().to_owned()))
.where_(Page::notification_pre_published_sent.eq(false))
.fetch(pool)
.await?;
for mut p in scheduled {
let Some(go_live) = p.go_live_at else {
continue;
};
if go_live <= now || go_live > horizon {
continue;
}
let page_id = p.id.get().copied().unwrap_or(0);
crate::page_subscription::notify_pre_publish(
Some(m),
from,
pool,
tenant_slug,
page_id,
&p.title,
&p.url_path,
go_live,
)
.await;
p.notification_pre_published_sent = true;
p.save(pool)
.await
.log_warn("pre-publish notification flag not saved; it may be sent again");
}
}
let result = run_schedule_sweep(pool).await?;
apply_sweep_effects(pool, tenant_slug, &result).await;
record_sweep_publishes(pool, tenant_slug, &result, mailer.map(|m| (m, from))).await;
Ok(result)
}
#[derive(Debug, Default)]
pub struct ArchivePlan {
pub to_flip: Vec<Page>,
pub changed_urls: Vec<String>,
}
pub async fn plan_archive(
pool: &rustango::sql::Pool,
selected: &[Page],
archive: bool,
cascade: bool,
) -> Result<ArchivePlan, rustango::sql::ExecError> {
let now = chrono::Utc::now();
let archived = PageStatus::Archived.as_str();
let published = PageStatus::Published.as_str();
let republish = |p: &mut Page| {
p.status = published.to_owned();
if p.published_at.is_none() {
p.published_at = Some(now);
}
p.last_published_at = Some(now);
};
let mut plan = ArchivePlan::default();
for p in selected {
if archive {
if p.status != archived {
let mut np = p.clone();
np.status = archived.to_owned();
plan.to_flip.push(np);
}
plan.changed_urls.push(p.url_path.clone());
} else if p.status == archived {
let mut np = p.clone();
republish(&mut np);
plan.to_flip.push(np);
plan.changed_urls.push(p.url_path.clone());
}
let descendants = p.descendants(pool).await.unwrap_or_default();
for d in descendants {
let is_public = d.status == published || d.status == archived;
if archive {
if cascade && d.status == published {
let mut nd = d.clone();
nd.status = archived.to_owned();
plan.to_flip.push(nd);
}
} else if cascade && d.status == archived {
let mut nd = d.clone();
republish(&mut nd);
plan.to_flip.push(nd);
}
if is_public {
plan.changed_urls.push(d.url_path.clone());
}
}
}
plan.to_flip
.sort_by_key(|p| p.id.get().copied().unwrap_or_default());
plan.to_flip
.dedup_by_key(|p| p.id.get().copied().unwrap_or_default());
plan.changed_urls.sort();
plan.changed_urls.dedup();
Ok(plan)
}
impl Page {
#[must_use]
pub fn page_status(&self) -> Option<PageStatus> {
PageStatus::parse(&self.status)
}
pub fn set_page_status(&mut self, status: PageStatus) {
self.status = status.as_str().to_owned();
}
#[must_use]
pub fn is_public(&self) -> bool {
PageStatus::str_is_public(&self.status)
}
}
#[cfg(all(test, feature = "sqlite"))]
mod archive_tests {
use super::*;
use rustango::core::{Column as _, Model as _};
use rustango::sql::Pool;
async fn mem_pool() -> Pool {
let pool = Pool::connect("sqlite::memory:").await.expect("mem pool");
for schema in [
&crate::page_type_model::PageType::SCHEMA,
&crate::media::Media::SCHEMA,
&crate::theme::Theme::SCHEMA,
&Page::SCHEMA,
] {
let ddl = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(
pool.dialect(),
schema,
);
for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
.await
.expect("ddl");
}
}
let mut pt = crate::page_type_model::PageType {
id: Auto::Unset,
app_label: "cms".to_owned(),
type_name: "TestPage".to_owned(),
verbose_name: "Test page".to_owned(),
default_template: "page.html".to_owned(),
view_mode: "auto".to_owned(),
is_creatable: true,
allowed_parent_types: serde_json::json!([]),
allowed_child_types: serde_json::json!([]),
workflow: String::new(),
created_at: Auto::Unset,
updated_at: Auto::Unset,
};
pt.insert(&pool).await.expect("insert pt");
pool
}
async fn mk_page(
pool: &Pool,
slug: &str,
path: &str,
parent_id: Option<i64>,
status: &str,
expire_at: Option<chrono::DateTime<chrono::Utc>>,
) -> Page {
let mut page = Page {
id: Auto::Unset,
page_type_id: 1,
title: format!("Page {slug}"),
slug: slug.to_owned(),
path: path.to_owned(),
url_path: format!("/{slug}"),
preview_path: String::new(),
template_override: String::new(),
depth: path.matches('/').count() as i32,
parent_id,
locale_variant_of: None,
alias_of: None,
theme_id: None,
sort_order: 0,
status: status.to_owned(),
published_at: Some(chrono::Utc::now()),
last_published_at: Some(chrono::Utc::now()),
go_live_at: None,
expire_at,
seo_title: String::new(),
seo_description: String::new(),
robots_index: true,
sitemap_priority: 0.5,
show_in_menus: false,
og_title: String::new(),
og_description: String::new(),
og_image_media_id: None,
twitter_card: "summary_large_image".to_owned(),
notification_pre_published_sent: false,
created_at: Auto::Unset,
updated_at: Auto::Unset,
};
page.insert(pool).await.expect("insert page");
page
}
async fn status_of(pool: &Pool, id: i64) -> String {
Page::objects()
.where_(Page::id.eq(id))
.first(pool)
.await
.expect("fetch")
.expect("row")
.status
}
#[test]
fn parse_round_trips_every_status_and_rejects_others() {
for s in PageStatus::ALL {
assert_eq!(PageStatus::parse(s.as_str()), Some(s));
}
assert_eq!(PageStatus::parse("Published"), None);
assert_eq!(PageStatus::parse(""), None);
assert_eq!(PageStatus::public_strings(), ["published", "archived"]);
assert!(PageStatus::PUBLIC.iter().all(|s| s.is_public()));
}
#[test]
fn going_live_is_any_change_into_a_public_or_scheduled_status() {
let goes = PageStatus::str_goes_live;
assert!(goes("draft", "published"));
assert!(goes("draft", "archived"), "archived is served (#761)");
assert!(goes("draft", "scheduled"), "the sweep publishes it");
assert!(goes("published", "archived"));
assert!(!goes("draft", "draft"));
assert!(!goes("published", "published"), "re-saving a live page");
assert!(!goes("published", "draft"), "unpublishing is not going live");
}
#[test]
fn is_public_covers_published_and_archived_only() {
assert!(PageStatus::Published.is_public());
assert!(PageStatus::Archived.is_public());
assert!(!PageStatus::Draft.is_public());
assert!(!PageStatus::Scheduled.is_public());
assert!(!PageStatus::Expired.is_public());
}
#[test]
fn str_is_public_agrees_with_the_typed_form() {
for st in [
PageStatus::Draft,
PageStatus::Scheduled,
PageStatus::Published,
PageStatus::Archived,
PageStatus::Expired,
] {
assert_eq!(
PageStatus::str_is_public(st.as_str()),
st.is_public(),
"{}", st.as_str(),
);
}
assert!(!PageStatus::str_is_public("nonsense"));
}
#[tokio::test]
async fn sweep_expires_not_archives_past_expire_at() {
let pool = mem_pool().await;
let past = chrono::Utc::now() - chrono::Duration::hours(1);
let p = mk_page(&pool, "gone", "0001/", None, "published", Some(past)).await;
let id = p.id.get().copied().unwrap();
let res = run_schedule_sweep(&pool).await.expect("sweep");
assert_eq!(res.expired, 1, "one page taken down");
assert_eq!(
status_of(&pool, id).await,
PageStatus::Expired.as_str(),
"expire_at flips to expired (takedown), NOT archived (serve-able)"
);
}
#[tokio::test]
async fn plan_archive_marks_self_and_purges_subtree_without_cascade() {
let pool = mem_pool().await;
let parent = mk_page(&pool, "docs", "0001/", None, "published", None).await;
let child = mk_page(
&pool,
"v1",
"0001/0002/",
parent.id.get().copied(),
"published",
None,
)
.await;
let draft = mk_page(
&pool,
"wip",
"0001/0003/",
parent.id.get().copied(),
"draft",
None,
)
.await;
let plan = plan_archive(&pool, std::slice::from_ref(&parent), true, false)
.await
.expect("plan");
let flip_ids: Vec<i64> = plan
.to_flip
.iter()
.map(|p| p.id.get().copied().unwrap())
.collect();
assert_eq!(
flip_ids,
vec![parent.id.get().copied().unwrap()],
"only parent flips"
);
assert!(plan.changed_urls.contains(&"/docs".to_owned()));
assert!(
plan.changed_urls.contains(&"/v1".to_owned()),
"published child purged"
);
assert!(
!plan.changed_urls.contains(&"/wip".to_owned()),
"draft child not purged"
);
let _ = (child, draft);
}
#[tokio::test]
async fn plan_archive_cascade_flips_published_descendants() {
let pool = mem_pool().await;
let parent = mk_page(&pool, "docs", "0001/", None, "published", None).await;
let child = mk_page(
&pool,
"v1",
"0001/0002/",
parent.id.get().copied(),
"published",
None,
)
.await;
let draft = mk_page(
&pool,
"wip",
"0001/0003/",
parent.id.get().copied(),
"draft",
None,
)
.await;
let plan = plan_archive(&pool, std::slice::from_ref(&parent), true, true)
.await
.expect("plan");
let flip_ids: std::collections::HashSet<i64> = plan
.to_flip
.iter()
.map(|p| p.id.get().copied().unwrap())
.collect();
assert!(flip_ids.contains(&parent.id.get().copied().unwrap()));
assert!(
flip_ids.contains(&child.id.get().copied().unwrap()),
"published child flips under cascade"
);
assert!(
!flip_ids.contains(&draft.id.get().copied().unwrap()),
"draft child left untouched"
);
assert!(plan
.to_flip
.iter()
.all(|p| p.status == PageStatus::Archived.as_str()));
}
#[tokio::test]
async fn plan_unarchive_symmetric_revives_archived() {
let pool = mem_pool().await;
let parent = mk_page(&pool, "docs", "0001/", None, "archived", None).await;
let child = mk_page(
&pool,
"v1",
"0001/0002/",
parent.id.get().copied(),
"archived",
None,
)
.await;
let plan = plan_archive(&pool, std::slice::from_ref(&parent), false, true)
.await
.expect("plan");
assert!(plan
.to_flip
.iter()
.all(|p| p.status == PageStatus::Published.as_str()));
let ids: std::collections::HashSet<i64> = plan
.to_flip
.iter()
.map(|p| p.id.get().copied().unwrap())
.collect();
assert!(ids.contains(&parent.id.get().copied().unwrap()));
assert!(
ids.contains(&child.id.get().copied().unwrap()),
"cascade unarchive revives archived descendant"
);
}
}
#[must_use]
pub fn alias_hybrid(alias: &Page, source: &Page) -> Page {
let mut hybrid = alias.clone();
hybrid.title = source.title.clone();
hybrid.page_type_id = source.page_type_id;
hybrid.seo_title = source.seo_title.clone();
hybrid.seo_description = source.seo_description.clone();
hybrid.status = source.status.clone();
hybrid.published_at = source.published_at;
hybrid.last_published_at = source.last_published_at;
hybrid.go_live_at = source.go_live_at;
hybrid.expire_at = source.expire_at;
hybrid.theme_id = source.theme_id;
hybrid.robots_index = source.robots_index;
hybrid.sitemap_priority = source.sitemap_priority;
hybrid.show_in_menus = source.show_in_menus;
hybrid
}
#[cfg(test)]
mod status_accessor_tests {
use super::*;
#[test]
fn typed_status_accessors_round_trip_and_know_public() {
let mut p: Page = serde_json::from_value(serde_json::json!({
"id": 1, "page_type_id": 1, "title": "T", "slug": "t", "path": "0001/",
"url_path": "/t", "preview_path": "", "template_override": "", "depth": 1,
"parent_id": null, "locale_variant_of": null, "alias_of": null, "theme_id": null,
"sort_order": 0, "status": "draft", "published_at": null, "last_published_at": null,
"go_live_at": null, "expire_at": null, "seo_title": "", "seo_description": "",
"robots_index": true, "sitemap_priority": 0.5, "show_in_menus": true, "og_title": "",
"og_description": "", "og_image_media_id": null, "twitter_card": "summary",
"notification_pre_published_sent": false,
"created_at": "2026-11-06T00:00:00Z", "updated_at": "2026-11-06T00:00:00Z"
}))
.unwrap();
assert_eq!(p.page_status(), Some(PageStatus::Draft));
assert!(!p.is_public());
p.set_page_status(PageStatus::Archived);
assert_eq!(p.status, "archived");
assert!(p.is_public(), "archived pages are served");
p.status = "bogus".into();
assert_eq!(p.page_status(), None);
assert!(!p.is_public());
}
}