Skip to main content

rustango_cms/
page.rs

1//! [`Page`] — the tenant-scoped `cms_page` row every page shares,
2//! whatever its type: tree position (`path`, `depth`, `parent_id`),
3//! slug and `url_path`, [`PageStatus`] lifecycle, SEO fields and the
4//! `page_type_id` that selects its [`PageTypeHandler`](crate::PageTypeHandler).
5//! Type-specific fields live in the handler's extension table.
6
7use rustango::sql::Auto;
8use crate::log_err::LogErr as _;
9use rustango::Model;
10use serde::{Deserialize, Serialize};
11
12/// Lifecycle state of a page. Stored as a short string column so it survives
13/// migrations cleanly and is grep-able in the DB.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "lowercase")]
16pub enum PageStatus {
17    Draft,
18    Scheduled,
19    Published,
20    /// Superseded but preserved: served publicly at 200, stays searchable
21    /// and in the sitemap (capped priority), frozen against unpublish/
22    /// delete. Archiving prevents content from becoming *unavailable* —
23    /// it is a preservation lock, not a step toward deletion.
24    Archived,
25    /// Terminal takedown state reached when `expire_at` passes.
26    /// Unlike [`Self::Archived`] it is NOT served — it 404s
27    /// exactly as an expired page did before archived became serve-able.
28    /// Sweep-set only; not selectable in the editor.
29    Expired,
30}
31
32impl PageStatus {
33    /// Every status, for parsing and choice lists.
34    pub const ALL: [Self; 5] = [
35        Self::Draft,
36        Self::Scheduled,
37        Self::Published,
38        Self::Archived,
39        Self::Expired,
40    ];
41
42    /// The statuses [`is_public`](Self::is_public) accepts.
43    pub const PUBLIC: [Self; 2] = [Self::Published, Self::Archived];
44
45    /// The statuses an editor (the page form, an MCP agent) may set;
46    /// `expired` is reached only by the schedule sweep.
47    pub const EDITABLE: [Self; 4] = [Self::Draft, Self::Scheduled, Self::Published, Self::Archived];
48
49    /// A status an editor may set, or `None` — the one parser for every
50    /// write path (#763), so they can't accept different sets again.
51    #[must_use]
52    pub fn parse_editable(s: &str) -> Option<Self> {
53        Self::EDITABLE.into_iter().find(|v| v.as_str() == s)
54    }
55
56    /// [`Self::PUBLIC`] as owned strings, for an `is_in` filter on
57    /// `Page::status`.
58    #[must_use]
59    pub fn public_strings() -> [String; 2] {
60        Self::PUBLIC.map(|s| s.as_str().to_owned())
61    }
62
63    /// The status a stored or submitted string names; `None` for any
64    /// other string.
65    #[must_use]
66    pub fn parse(s: &str) -> Option<Self> {
67        Self::ALL.into_iter().find(|v| v.as_str() == s)
68    }
69
70    pub fn as_str(self) -> &'static str {
71        match self {
72            Self::Draft => "draft",
73            Self::Scheduled => "scheduled",
74            Self::Published => "published",
75            Self::Archived => "archived",
76            Self::Expired => "expired",
77        }
78    }
79
80    /// Statuses served to anonymous visitors (200). `archived` joins
81    /// `published`; `expired` stays excluded so takedown still
82    /// 404s.
83    #[must_use]
84    pub fn is_public(self) -> bool {
85        matches!(self, Self::Published | Self::Archived)
86    }
87
88    /// [`is_public`](Self::is_public) for a status read off a row.
89    ///
90    /// `Page::status` is a `String`, so every caller was comparing
91    /// against two `as_str()` literals by hand — and the one that
92    /// compared against `Published` alone (`api::pages::find`) silently
93    /// disagreed with the rest of the API about archived pages. One
94    /// place to be wrong is better than four.
95    #[must_use]
96    pub fn str_is_public(status: &str) -> bool {
97        status == Self::Published.as_str() || status == Self::Archived.as_str()
98    }
99
100    /// Whether a save moving a page from `from` to `to` puts it live —
101    /// now, or on a schedule the sweep will publish. That takes the
102    /// publish right whichever status gets there: archived is served like
103    /// published, so gating on the `published` literal alone let an
104    /// edit-only user make a draft public.
105    #[must_use]
106    pub fn str_goes_live(from: &str, to: &str) -> bool {
107        from != to && (Self::str_is_public(to) || to == Self::Scheduled.as_str())
108    }
109}
110
111/// The abstract page record. Each row points at a `cms_page_type` registry
112/// row via `page_type_id`; per-type extension data lives in a separate
113/// table authored by user code (multi-table inheritance).
114///
115/// Tree shape: `path` is a materialized path (e.g. `0001/0003/`), `depth` is
116/// the number of segments, `parent_id` is the immediate parent (nullable for
117/// roots). Siblings share `parent_id` and order by `sort_order` then `id`.
118#[derive(Model, Debug, Clone, Serialize, Deserialize)]
119#[rustango(
120    table = "cms_page",
121    app = "cms",
122    display = "title",
123    admin(
124        list_display = "title, slug, page_type_id, status, depth, published_at",
125        search_fields = "title, slug",
126        ordering = "path",
127        list_filter = "page_type_id, status",
128    )
129)]
130pub struct Page {
131    #[rustango(primary_key)]
132    pub id: Auto<i64>,
133
134    /// FK to `cms_page_type.id` — the registry row that names the
135    /// handler responsible for this page.
136    #[rustango(fk = "cms_page_type", on = "id", index)]
137    pub page_type_id: i64,
138
139    #[rustango(max_length = 255)]
140    pub title: String,
141
142    /// URL slug, meant to be unique per parent. Not enforced by a DB
143    /// constraint; page create / copy / alias dedup against siblings.
144    #[rustango(max_length = 255)]
145    pub slug: String,
146
147    /// Materialized path of zero-padded segment ids, trailing slash.
148    /// Example: `0001/0003/0008/`. Indexed for prefix lookups.
149    #[rustango(max_length = 510, index)]
150    pub path: String,
151
152    /// Materialized public URL path, indexed for
153    /// single-query lookup. Leading slash, no trailing slash for
154    /// non-root pages: `/`, `/about`, `/about/team`. Maintained by
155    /// `tree_ops` whenever a page is created or its slug / parent
156    /// changes. The resolver short-circuits via this column instead
157    /// of walking ancestor-by-ancestor, turning N queries into 1.
158    ///
159    /// Default `''` so AddColumn on existing tables doesn't need a
160    /// backfill — older rows fall through to the slug-walk
161    /// resolver until their next save populates the column.
162    #[rustango(max_length = 510, index, default = "''")]
163    pub url_path: String,
164
165    /// Cached number of `/`-separated segments in `path` (root = 1).
166    pub depth: i32,
167
168    /// Self-FK. Null means this is a root page.
169    #[rustango(fk = "self", on = "id")]
170    pub parent_id: Option<i64>,
171
172    /// **DEPRECATED** — the structural-variant escape hatch was
173    /// retired in favor of per-field translations. The supported path
174    /// for localizing a page is the `cms_translation` table (one row
175    /// per `(page_id, locale_id, field_path)` override); see
176    /// [`crate::translation`].
177    ///
178    /// The column itself is retained so existing tenant rows that
179    /// already carried a variant pointer don't 500 the loader. Sitemap
180    /// + feed builders still dedup on this column for back-compat;
181    /// `api/pages.rs` still filters by it for legacy API consumers.
182    /// No new rows should set this field — the admin UI no longer
183    /// surfaces the action and the POST handler is gone.
184    #[rustango(fk = "self", on = "id")]
185    pub locale_variant_of: Option<i64>,
186
187    /// Live alias. When set, this row contributes only the
188    /// URL (slug / url_path / sort_order / parent_id); content
189    /// fields (title, seo_*, status, page-type extension data) come
190    /// from the row this FK points at. Edits via the page editor
191    /// proxy to the source; the alias row stays read-only. Deleting
192    /// the source demotes every alias into a standalone copy with
193    /// the source's last-known content frozen in place.
194    ///
195    /// Differentiation from neighbouring features:
196    ///   * Clone is a deep copy — divergent edits, separate
197    ///     revisions, no link back to the original.
198    ///   * Redirect is a 301 from old path to new path with
199    ///     no separate page row at all.
200    ///   * Alias is one row, two (or more) URLs, content always in
201    ///     sync because there's only one source-of-truth.
202    #[rustango(fk = "self", on = "id")]
203    pub alias_of: Option<i64>,
204
205    /// Per-page visual theme override. When set, this page (and its
206    /// descendants, unless they override too) renders against the
207    /// referenced `cms_theme` row's design tokens. NULL = inherit
208    /// from ancestors / site default / admin default.
209    #[rustango(fk = "cms_theme", on = "id")]
210    pub theme_id: Option<i64>,
211
212    /// Ordering among siblings (lowest first).
213    pub sort_order: i32,
214
215    /// Lifecycle. Stored as the `PageStatus::as_str()` value.
216    #[rustango(max_length = 16, index)]
217    pub status: String,
218
219    /// Set when status transitions to `Published`. Null otherwise.
220    ///
221    /// Note: semantically this is
222    /// `first_published_at` — the renderer + sweep set it once on
223    /// the first published transition and never touch it again, so
224    /// `order_by('-published_at')` is the canonical chronological
225    /// post-card ordering. For "most-recently-edited" timestamps
226    /// see [`Self::last_published_at`].
227    pub published_at: Option<chrono::DateTime<chrono::Utc>>,
228
229    /// Refreshed every time the page is saved while `status =
230    /// published`. Sitemap `<lastmod>` and edge-cache
231    /// invalidation use this — `published_at` (the first-publish
232    /// timestamp) is too stable for those.
233    ///
234    /// Initialized to the same value as `published_at` when the
235    /// first-publish happens; subsequent edits bump just this
236    /// field. Null for never-published rows.
237    ///
238    /// `#[serde(default)]` so revision snapshots captured before
239    /// this column landed deserialize cleanly (the field arrives
240    /// as `None`, which matches the column's nullable default).
241    #[serde(default)]
242    pub last_published_at: Option<chrono::DateTime<chrono::Utc>>,
243
244    /// Optional schedule — when set with `status = scheduled`, a worker flips
245    /// status to `published` once `now() >= go_live_at`.
246    pub go_live_at: Option<chrono::DateTime<chrono::Utc>>,
247
248    /// Opposite of `go_live_at` — auto-archive at this time.
249    pub expire_at: Option<chrono::DateTime<chrono::Utc>>,
250
251    /// SEO metadata.
252    #[rustango(max_length = 70)]
253    pub seo_title: String,
254    #[rustango(max_length = 200)]
255    pub seo_description: String,
256
257    /// Whether search engines should index this page. `false` makes
258    /// the renderer emit `<meta name="robots" content="noindex">`
259    /// and excludes the page from the generated [`/sitemap.xml`].
260    /// Default `true`.
261    ///
262    /// [`/sitemap.xml`]: crate::sitemap
263    #[rustango(default = "true")]
264    pub robots_index: bool,
265
266    /// Sitemap priority hint, 0.0–1.0 per the sitemaps.org spec.
267    /// 1.0 = homepage / top of hierarchy; 0.5 = ordinary content
268    /// page (the spec's default); 0.0–0.3 = low-value pages
269    /// (terms, archive listings). Communicated to crawlers via the
270    /// generated [`/sitemap.xml`]'s `<priority>` element.
271    ///
272    /// [`/sitemap.xml`]: crate::sitemap
273    #[rustango(default = "0.5")]
274    pub sitemap_priority: f32,
275
276    /// Where this page lives on a **decoupled frontend**, when that
277    /// differs from `url_path`.
278    ///
279    /// The site-wide "Headless preview" template substitutes `{path}`
280    /// with `url_path`, which silently assumes the frontend mirrors the
281    /// CMS's URL structure. Plenty of them do not: a page at
282    /// `/features/ai-engine` here may be `/product/ai-engine` there, or
283    /// `/p/9`, or on another host entirely.
284    ///
285    /// Three behaviours, chosen by what the editor types:
286    ///
287    /// * **empty** — use `url_path`, i.e. today's behaviour;
288    /// * **a path** (`/product/ai-engine`) — substituted for `{path}`
289    ///   in the site-wide template, so the token and host stay in one
290    ///   place;
291    /// * **an absolute URL** (`https://other.example.com/x`) — used as
292    ///   the whole preview URL, placeholders and all, for the page that
293    ///   a different app renders.
294    ///
295    /// Default `''` so adding the column needs no backfill: every
296    /// existing page keeps resolving through `url_path`.
297    ///
298    /// Deliberately **not** carried by clone or alias: a copy has its own
299    /// `url_path`, and inheriting the original's frontend route would
300    /// point two pages at one place.
301    #[rustango(max_length = 510, default = "''")]
302    pub preview_path: String,
303
304    /// Template this page renders through, overriding its page type's
305    /// `default_template`.
306    ///
307    /// The type's template is the right default: pages of a type
308    /// normally look alike, and that is what makes a type worth having.
309    /// But a type is a *content* shape, and presentation does not always
310    /// follow it — a set of pages under one root can want their own
311    /// layout without becoming a separate type with a duplicate field
312    /// list. Rather than making authors choose between a type per
313    /// variation and no variation at all, the page names the template.
314    ///
315    /// Default `''` (use the type's template) so adding the column needs
316    /// no backfill and every existing page renders exactly as before.
317    ///
318    /// The name resolves against the tenant's template set, so an
319    /// override can point at a file the template editor (or the
320    /// `write_template` MCP tool) created without a deploy. A name that
321    /// resolves to nothing falls back to the type's template rather than
322    /// 500ing — a typo should not take the page down.
323    #[rustango(max_length = 255, default = "''")]
324    pub template_override: String,
325
326    /// Opt-in flag — the navigation-menu editor shows this page
327    /// in its picker as a suggested entry. Editors flip it in the
328    /// Promote tab; defaults to `false` so the suggestion list stays
329    /// curated and doesn't surface every page in the tree.
330    #[rustango(default = "false")]
331    pub show_in_menus: bool,
332
333    /// Social-sharing fields. All optional;
334    /// the renderer falls back to title / seo_description / first
335    /// body image when empty.
336    #[rustango(max_length = 120, default = "''")]
337    pub og_title: String,
338    #[rustango(max_length = 300, default = "''")]
339    pub og_description: String,
340    #[rustango(fk = "cms_media", on = "id")]
341    pub og_image_media_id: Option<i64>,
342    /// Twitter card variant. Accepted values: `summary`,
343    /// `summary_large_image`. Default `summary_large_image`.
344    #[rustango(max_length = 32, default = "'summary_large_image'")]
345    pub twitter_card: String,
346
347    /// Pre-publish reminder flag. Set by
348    /// [`run_schedule_sweep_with_mailer`] when the sweep sends a
349    /// "publishes in N minutes" notification to subscribers; cleared
350    /// when an editor moves the `go_live_at`. Prevents duplicate
351    /// reminders if the sweep tick rate exceeds 1/hour.
352    #[rustango(default = "false")]
353    pub notification_pre_published_sent: bool,
354
355    #[rustango(auto_now_add)]
356    pub created_at: Auto<chrono::DateTime<chrono::Utc>>,
357    #[rustango(auto_now)]
358    pub updated_at: Auto<chrono::DateTime<chrono::Utc>>,
359}
360
361/// Outcome of one [`run_schedule_sweep`] tick.
362#[derive(Debug, Clone, Default)]
363pub struct ScheduleSweepResult {
364    pub published: usize,
365    /// Pages taken down this tick (`published → expired` at
366    /// `expire_at`). Named `expired` since archiving is now a *manual*,
367    /// content-preserving action, distinct from expiry-as-takedown.
368    pub expired: usize,
369    /// `url_path`s of every page whose public visibility flipped
370    /// this tick (published or expired). The caller purges these from
371    /// the frontend cache (see [`run_schedule_sweep_and_purge`]).
372    pub changed_urls: Vec<String>,
373    /// The pages that went live this tick, as read before the flip.
374    pub went_live: Vec<Page>,
375    /// Ids of the pages taken down this tick.
376    pub taken_down: Vec<i64>,
377}
378
379/// What must happen once a page has gone live, whichever path put it there:
380/// the search index learns about it and the host's after-publish
381/// hooks run. An editor's save, a bulk publish, a workflow finish and the
382/// schedule sweep each did their own subset — the sweep did neither, so a
383/// scheduled page never reached an external search index.
384pub async fn went_live_effects(pool: &rustango::sql::Pool, tenant_slug: &str, page: &Page, user_id: Option<i64>) {
385    crate::task_queue::sync_page_search(tenant_slug, page).await;
386    crate::hooks::fire_after_publish_page(crate::hooks::HookCtx::new(pool, tenant_slug, user_id), page).await;
387}
388
389/// What a manual publish records that the sweep skipped (#945): a
390/// "Published" page-log entry and the subscriber emails, for every page
391/// the sweep took live. Emails use `mailer` (a mailer and its `From:`),
392/// else the process-wide one ([`crate::task_queue::default_mailer`]);
393/// without either only the log is written.
394pub async fn record_sweep_publishes(
395    pool: &rustango::sql::Pool,
396    tenant_slug: &str,
397    result: &ScheduleSweepResult,
398    mailer: Option<(&dyn rustango::email::Mailer, &str)>,
399) {
400    let fallback = crate::task_queue::default_mailer();
401    let mailer = mailer.or_else(|| fallback.as_ref().map(|(m, from)| (m.as_ref(), from.as_str())));
402    for page in &result.went_live {
403        let id = page.id.get().copied().unwrap_or_default();
404        crate::page_log::record_or_warn(
405            pool,
406            id,
407            crate::page_log::ACTION_PUBLISH,
408            None,
409            format!("Published “{}” on schedule.", page.title),
410            None,
411        )
412        .await;
413        if let Some((m, from)) = mailer {
414            crate::page_subscription::notify_publish(
415                Some(m),
416                from,
417                pool,
418                tenant_slug,
419                id,
420                &page.title,
421                &page.url_path,
422                None,
423            )
424            .await;
425        }
426    }
427}
428
429/// [`went_live_effects`] for every page a sweep published, and the search
430/// removal for every page it took down.
431pub async fn apply_sweep_effects(pool: &rustango::sql::Pool, tenant_slug: &str, result: &ScheduleSweepResult) {
432    for page in &result.went_live {
433        went_live_effects(pool, tenant_slug, page, None).await;
434    }
435    for id in &result.taken_down {
436        crate::task_queue::remove_page_search(tenant_slug, *id).await;
437    }
438}
439
440/// Flip the status of any page whose `go_live_at` has passed (draft
441/// or scheduled → published) and any page whose `expire_at` has
442/// passed (published → **expired** — a terminal 404 takedown,
443/// no longer conflated with the serve-able `archived` state).
444/// Idempotent — running it twice in a row produces zero changes on
445/// the second call.
446///
447/// Called opportunistically from the page-list handler so editors
448/// always see current state. Production deployments should also wire
449/// it into a cron / sweeper task so public traffic sees flipped
450/// pages without an admin visit.
451///
452/// # Errors
453/// Propagates driver / query failures. Successfully-flipped rows
454/// before a later failure stay flipped (the function does one update
455/// per row, not a tx — partial progress is safe and idempotent).
456pub async fn run_schedule_sweep(
457    pool: &rustango::sql::Pool,
458) -> Result<ScheduleSweepResult, rustango::sql::ExecError> {
459    use rustango::core::Column as _;
460    use rustango::sql::FetcherPool as _;
461    let now = chrono::Utc::now();
462    let mut published = 0usize;
463    let mut expired = 0usize;
464    let mut changed_urls: Vec<String> = Vec::new();
465    let mut went_live: Vec<Page> = Vec::new();
466    let mut taken_down: Vec<i64> = Vec::new();
467
468    // Only the rows that are due, filtered in SQL — a sweep runs on a timer
469    // and on every admin page list, so it must not load every published
470    // page to find the few that expired (#680).
471    //
472    // Each flip is a conditional UPDATE of the status columns alone, keyed
473    // on the status the row was read with. An editor who saved the page in
474    // between keeps their edit, and a page moved meanwhile keeps its new
475    // path — the old full-row save wrote the stale copy back over both.
476
477    // 1) scheduled → published once go_live_at has passed. Drafts are
478    //    intentionally NOT flipped — an editor opts in by picking
479    //    "scheduled" alongside the go-live datetime.
480    let due_publish: Vec<Page> = Page::objects()
481        .where_(Page::status.eq(PageStatus::Scheduled.as_str().to_owned()))
482        .where_(Page::go_live_at.lte(Some(now)))
483        .fetch(pool)
484        .await?;
485    for p in due_publish {
486        let mut set = vec![
487            ("status", PageStatus::Published.as_str().into()),
488            // #251 — every publish transition bumps last_published_at.
489            ("last_published_at", now.into()),
490        ];
491        if p.published_at.is_none() {
492            set.push(("published_at", now.into()));
493        }
494        if flip(pool, &p, PageStatus::Scheduled, set).await? {
495            changed_urls.push(p.url_path.clone());
496            published += 1;
497            let mut live = p;
498            live.status = PageStatus::Published.as_str().to_owned();
499            went_live.push(live);
500        }
501    }
502
503    // 2) published → expired once expire_at has passed (#556). Expiry is
504    //    takedown: the page 404s afterward (the resolver serves only
505    //    published + archived). Archiving is a separate, manual action.
506    let due_expire: Vec<Page> = Page::objects()
507        .where_(Page::status.eq(PageStatus::Published.as_str().to_owned()))
508        .where_(Page::expire_at.lte(Some(now)))
509        .fetch(pool)
510        .await?;
511    for p in due_expire {
512        let set = vec![("status", PageStatus::Expired.as_str().into())];
513        if flip(pool, &p, PageStatus::Published, set).await? {
514            changed_urls.push(p.url_path.clone());
515            expired += 1;
516            taken_down.extend(p.id.get().copied());
517        }
518    }
519
520    Ok(ScheduleSweepResult {
521        published,
522        expired,
523        changed_urls,
524        went_live,
525        taken_down,
526    })
527}
528
529/// Apply `set` to `page` only while it still has status `from`. Returns
530/// whether this call flipped it (false when someone changed it first).
531async fn flip(
532    pool: &rustango::sql::Pool,
533    page: &Page,
534    from: PageStatus,
535    set: Vec<(&'static str, rustango::core::SqlValue)>,
536) -> Result<bool, rustango::sql::ExecError> {
537    use rustango::core::Column as _;
538    use rustango::sql::UpdaterPool as _;
539    let id = page.id.get().copied().unwrap_or_default();
540    let mut update = Page::objects()
541        .where_(Page::id.eq(id))
542        .where_(Page::status.eq(from.as_str().to_owned()))
543        .update();
544    for (column, value) in set {
545        update = update.set(column, value);
546    }
547    Ok(update.execute_pool(pool).await? == 1)
548}
549
550/// [`run_schedule_sweep`] + a frontend-cache purge of every page whose
551/// visibility flipped this tick. A scheduled page going live (or
552/// an expired one going away) must evict its previously-cached
553/// 404/draft/live entry; the bare sweep can't, since it has no cache
554/// context. The purge routes through [`crate::task_queue::purge_urls`],
555/// so it's queued + retried when a task sink is installed, inline
556/// otherwise.
557///
558/// # Errors
559/// Propagates the sweep's driver / query failures (the purge itself is
560/// best-effort and never errors the call).
561pub async fn run_schedule_sweep_and_purge(
562    pool: &rustango::sql::Pool,
563    tenant: &rustango::tenancy::TenantSlug,
564    invalidator: std::sync::Arc<dyn crate::cache_invalidate::PageCacheInvalidator>,
565) -> Result<ScheduleSweepResult, rustango::sql::ExecError> {
566    let result = run_schedule_sweep(pool).await?;
567    if !result.changed_urls.is_empty() {
568        crate::task_queue::purge_urls(invalidator, tenant.clone(), result.changed_urls.clone())
569            .await;
570    }
571    apply_sweep_effects(pool, &tenant.slug, &result).await;
572    record_sweep_publishes(pool, &tenant.slug, &result, None).await;
573    Ok(result)
574}
575
576/// Sweep with a mailer attached — adds a pre-publish reminder pass.
577/// Every page with `status = scheduled` and `go_live_at` in
578/// (now, now + 1h] that hasn't already received the reminder gets a
579/// notification to subscribers + the flag set so future ticks within
580/// the same window don't duplicate.
581///
582/// The publish + archive passes are identical to
583/// [`run_schedule_sweep`]; this variant just layers the reminder on
584/// top so production deployments with a wired mailer get the
585/// notification path for free.
586///
587/// # Errors
588/// Driver / query failures.
589pub async fn run_schedule_sweep_with_mailer(
590    pool: &rustango::sql::Pool,
591    mailer: Option<&dyn rustango::email::Mailer>,
592    from: &str,
593    tenant_slug: &str,
594) -> Result<ScheduleSweepResult, rustango::sql::ExecError> {
595    use rustango::core::Column as _;
596    use rustango::sql::FetcherPool as _;
597
598    // 1) Pre-publish reminder pass. Runs FIRST so a reminder is sent
599    //    before the actual publish flip later in this same call.
600    if let Some(m) = mailer {
601        let now = chrono::Utc::now();
602        let horizon = now + chrono::Duration::hours(1);
603        let scheduled: Vec<Page> = Page::objects()
604            .where_(Page::status.eq(PageStatus::Scheduled.as_str().to_owned()))
605            .where_(Page::notification_pre_published_sent.eq(false))
606            .fetch(pool)
607            .await?;
608        for mut p in scheduled {
609            let Some(go_live) = p.go_live_at else {
610                continue;
611            };
612            if go_live <= now || go_live > horizon {
613                continue;
614            }
615            let page_id = p.id.get().copied().unwrap_or(0);
616            // Best-effort fan-out; on failure leave the flag unset
617            // so a future tick can retry (a retry that succeeds is
618            // strictly better than a permanent miss).
619            crate::page_subscription::notify_pre_publish(
620                Some(m),
621                from,
622                pool,
623                tenant_slug,
624                page_id,
625                &p.title,
626                &p.url_path,
627                go_live,
628            )
629            .await;
630            p.notification_pre_published_sent = true;
631            p.save(pool)
632                .await
633                .log_warn("pre-publish notification flag not saved; it may be sent again");
634        }
635    }
636
637    // 2) — delegate to the standard sweep for the publish + expiry
638    //      flips. Idempotent.
639    let result = run_schedule_sweep(pool).await?;
640    apply_sweep_effects(pool, tenant_slug, &result).await;
641    record_sweep_publishes(pool, tenant_slug, &result, mailer.map(|m| (m, from))).await;
642    Ok(result)
643}
644
645/// A planned archive / unarchive of a selection and (optionally) its
646/// subtree. Pure read output — the caller applies `to_flip`
647/// inside its own transaction, then purges `changed_urls`.
648#[derive(Debug, Default)]
649pub struct ArchivePlan {
650    /// Rows whose `status` must change, with the new status (and any
651    /// republish stamps) already applied — save them as-is.
652    pub to_flip: Vec<Page>,
653    /// Every `url_path` whose *public treatment* changes — the selection
654    /// plus every currently-public descendant (they inherit / lose the
655    /// archived banner at render time even when their own row is
656    /// untouched). The caller purges these from the frontend cache.
657    pub changed_urls: Vec<String>,
658}
659
660/// Plan an archive (`archive = true`) or unarchive of the already-loaded
661/// `selected` rows.
662///
663/// - **Archive**: the selected pages flip to `archived`. Descendants
664///   inherit the archived treatment at render time, so ALL currently-
665///   public descendants are added to `changed_urls` for a cache purge;
666///   when `cascade`, published descendants additionally flip their own
667///   row to `archived` (so the subtree stays archived even if later
668///   reparented). Drafts / scheduled / expired descendants are left
669///   untouched — they're already hidden.
670/// - **Unarchive**: archived selected pages flip back to `published`
671///   (republish stamps refreshed); non-archived selections are skipped.
672///   When `cascade`, archived descendants flip back to `published`.
673///
674/// Reads descendants per selected page; the caller applies the plan.
675///
676/// # Errors
677/// Propagates descendant-query failures.
678pub async fn plan_archive(
679    pool: &rustango::sql::Pool,
680    selected: &[Page],
681    archive: bool,
682    cascade: bool,
683) -> Result<ArchivePlan, rustango::sql::ExecError> {
684    let now = chrono::Utc::now();
685    let archived = PageStatus::Archived.as_str();
686    let published = PageStatus::Published.as_str();
687    let republish = |p: &mut Page| {
688        p.status = published.to_owned();
689        if p.published_at.is_none() {
690            p.published_at = Some(now);
691        }
692        p.last_published_at = Some(now);
693    };
694
695    let mut plan = ArchivePlan::default();
696    for p in selected {
697        if archive {
698            if p.status != archived {
699                let mut np = p.clone();
700                np.status = archived.to_owned();
701                plan.to_flip.push(np);
702            }
703            plan.changed_urls.push(p.url_path.clone());
704        } else if p.status == archived {
705            let mut np = p.clone();
706            republish(&mut np);
707            plan.to_flip.push(np);
708            plan.changed_urls.push(p.url_path.clone());
709        }
710
711        // Descendants: fetch by materialized path (excludes self).
712        // Best-effort — a failed subtree read degrades to "no cascade /
713        // purge for this branch" rather than aborting the whole action.
714        let descendants = p.descendants(pool).await.unwrap_or_default();
715        for d in descendants {
716            let is_public = d.status == published || d.status == archived;
717            if archive {
718                if cascade && d.status == published {
719                    let mut nd = d.clone();
720                    nd.status = archived.to_owned();
721                    plan.to_flip.push(nd);
722                }
723            } else if cascade && d.status == archived {
724                let mut nd = d.clone();
725                republish(&mut nd);
726                plan.to_flip.push(nd);
727            }
728            if is_public {
729                plan.changed_urls.push(d.url_path.clone());
730            }
731        }
732    }
733
734    // A parent + child both selected (or a cascade overlap) can enqueue
735    // the same row / URL twice — dedupe so the caller's writes + purge
736    // each run once.
737    plan.to_flip
738        .sort_by_key(|p| p.id.get().copied().unwrap_or_default());
739    plan.to_flip
740        .dedup_by_key(|p| p.id.get().copied().unwrap_or_default());
741    plan.changed_urls.sort();
742    plan.changed_urls.dedup();
743    Ok(plan)
744}
745
746/// Typed access to [`Page::status`] (#763). The column stays a string —
747/// changing the field's type would break every host that reads or writes
748/// it — so code goes through these instead of comparing literals, and
749/// the public-visibility rule lives in one place.
750impl Page {
751    /// The page's status, or `None` for a stored value no
752    /// [`PageStatus`] names (an old import, a typo).
753    #[must_use]
754    pub fn page_status(&self) -> Option<PageStatus> {
755        PageStatus::parse(&self.status)
756    }
757
758    /// Set the status from the enum, so only a value every reader
759    /// understands is ever written.
760    pub fn set_page_status(&mut self, status: PageStatus) {
761        self.status = status.as_str().to_owned();
762    }
763
764    /// Whether visitors may see this page: published **or** archived.
765    /// Use this, not `status == "published"`, which misses archived pages.
766    #[must_use]
767    pub fn is_public(&self) -> bool {
768        PageStatus::str_is_public(&self.status)
769    }
770}
771
772#[cfg(all(test, feature = "sqlite"))]
773mod archive_tests {
774    use super::*;
775    use rustango::core::{Column as _, Model as _};
776    use rustango::sql::Pool;
777
778    async fn mem_pool() -> Pool {
779        let pool = Pool::connect("sqlite::memory:").await.expect("mem pool");
780        for schema in [
781            &crate::page_type_model::PageType::SCHEMA,
782            &crate::media::Media::SCHEMA,
783            &crate::theme::Theme::SCHEMA,
784            &Page::SCHEMA,
785        ] {
786            let ddl = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(
787                pool.dialect(),
788                schema,
789            );
790            for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
791                rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
792                    .await
793                    .expect("ddl");
794            }
795        }
796        let mut pt = crate::page_type_model::PageType {
797            id: Auto::Unset,
798            app_label: "cms".to_owned(),
799            type_name: "TestPage".to_owned(),
800            verbose_name: "Test page".to_owned(),
801            default_template: "page.html".to_owned(),
802            view_mode: "auto".to_owned(),
803            is_creatable: true,
804            allowed_parent_types: serde_json::json!([]),
805            allowed_child_types: serde_json::json!([]),
806            workflow: String::new(),
807            created_at: Auto::Unset,
808            updated_at: Auto::Unset,
809        };
810        pt.insert(&pool).await.expect("insert pt");
811        pool
812    }
813
814    async fn mk_page(
815        pool: &Pool,
816        slug: &str,
817        path: &str,
818        parent_id: Option<i64>,
819        status: &str,
820        expire_at: Option<chrono::DateTime<chrono::Utc>>,
821    ) -> Page {
822        let mut page = Page {
823            id: Auto::Unset,
824            page_type_id: 1,
825            title: format!("Page {slug}"),
826            slug: slug.to_owned(),
827            path: path.to_owned(),
828            url_path: format!("/{slug}"),
829            preview_path: String::new(),
830            template_override: String::new(),
831            depth: path.matches('/').count() as i32,
832            parent_id,
833            locale_variant_of: None,
834            alias_of: None,
835            theme_id: None,
836            sort_order: 0,
837            status: status.to_owned(),
838            published_at: Some(chrono::Utc::now()),
839            last_published_at: Some(chrono::Utc::now()),
840            go_live_at: None,
841            expire_at,
842            seo_title: String::new(),
843            seo_description: String::new(),
844            robots_index: true,
845            sitemap_priority: 0.5,
846            show_in_menus: false,
847            og_title: String::new(),
848            og_description: String::new(),
849            og_image_media_id: None,
850            twitter_card: "summary_large_image".to_owned(),
851            notification_pre_published_sent: false,
852            created_at: Auto::Unset,
853            updated_at: Auto::Unset,
854        };
855        page.insert(pool).await.expect("insert page");
856        page
857    }
858
859    async fn status_of(pool: &Pool, id: i64) -> String {
860        Page::objects()
861            .where_(Page::id.eq(id))
862            .first(pool)
863            .await
864            .expect("fetch")
865            .expect("row")
866            .status
867    }
868
869    #[test]
870    fn parse_round_trips_every_status_and_rejects_others() {
871        for s in PageStatus::ALL {
872            assert_eq!(PageStatus::parse(s.as_str()), Some(s));
873        }
874        assert_eq!(PageStatus::parse("Published"), None);
875        assert_eq!(PageStatus::parse(""), None);
876        assert_eq!(PageStatus::public_strings(), ["published", "archived"]);
877        assert!(PageStatus::PUBLIC.iter().all(|s| s.is_public()));
878    }
879
880    #[test]
881    fn going_live_is_any_change_into_a_public_or_scheduled_status() {
882        let goes = PageStatus::str_goes_live;
883        assert!(goes("draft", "published"));
884        assert!(goes("draft", "archived"), "archived is served (#761)");
885        assert!(goes("draft", "scheduled"), "the sweep publishes it");
886        assert!(goes("published", "archived"));
887        assert!(!goes("draft", "draft"));
888        assert!(!goes("published", "published"), "re-saving a live page");
889        assert!(!goes("published", "draft"), "unpublishing is not going live");
890    }
891
892    #[test]
893    fn is_public_covers_published_and_archived_only() {
894        assert!(PageStatus::Published.is_public());
895        assert!(PageStatus::Archived.is_public());
896        assert!(!PageStatus::Draft.is_public());
897        assert!(!PageStatus::Scheduled.is_public());
898        assert!(!PageStatus::Expired.is_public());
899    }
900
901    #[test]
902    fn str_is_public_agrees_with_the_typed_form() {
903        // The string form is what rows carry, and it drifting from the
904        // typed one is exactly how `find` came to 404 an archived page
905        // the rest of the API served.
906        for st in [
907            PageStatus::Draft,
908            PageStatus::Scheduled,
909            PageStatus::Published,
910            PageStatus::Archived,
911            PageStatus::Expired,
912        ] {
913            assert_eq!(
914                PageStatus::str_is_public(st.as_str()),
915                st.is_public(),
916                "{}", st.as_str(),
917            );
918        }
919        assert!(!PageStatus::str_is_public("nonsense"));
920    }
921
922    #[tokio::test]
923    async fn sweep_expires_not_archives_past_expire_at() {
924        let pool = mem_pool().await;
925        let past = chrono::Utc::now() - chrono::Duration::hours(1);
926        let p = mk_page(&pool, "gone", "0001/", None, "published", Some(past)).await;
927        let id = p.id.get().copied().unwrap();
928        let res = run_schedule_sweep(&pool).await.expect("sweep");
929        assert_eq!(res.expired, 1, "one page taken down");
930        assert_eq!(
931            status_of(&pool, id).await,
932            PageStatus::Expired.as_str(),
933            "expire_at flips to expired (takedown), NOT archived (serve-able)"
934        );
935    }
936
937    #[tokio::test]
938    async fn plan_archive_marks_self_and_purges_subtree_without_cascade() {
939        let pool = mem_pool().await;
940        let parent = mk_page(&pool, "docs", "0001/", None, "published", None).await;
941        let child = mk_page(
942            &pool,
943            "v1",
944            "0001/0002/",
945            parent.id.get().copied(),
946            "published",
947            None,
948        )
949        .await;
950        let draft = mk_page(
951            &pool,
952            "wip",
953            "0001/0003/",
954            parent.id.get().copied(),
955            "draft",
956            None,
957        )
958        .await;
959
960        // No cascade: only the parent's own row flips; the published child
961        // is purged (inherits at render) but keeps its own status; the
962        // draft is neither flipped nor purged (already hidden).
963        let plan = plan_archive(&pool, std::slice::from_ref(&parent), true, false)
964            .await
965            .expect("plan");
966        let flip_ids: Vec<i64> = plan
967            .to_flip
968            .iter()
969            .map(|p| p.id.get().copied().unwrap())
970            .collect();
971        assert_eq!(
972            flip_ids,
973            vec![parent.id.get().copied().unwrap()],
974            "only parent flips"
975        );
976        assert!(plan.changed_urls.contains(&"/docs".to_owned()));
977        assert!(
978            plan.changed_urls.contains(&"/v1".to_owned()),
979            "published child purged"
980        );
981        assert!(
982            !plan.changed_urls.contains(&"/wip".to_owned()),
983            "draft child not purged"
984        );
985        let _ = (child, draft);
986    }
987
988    #[tokio::test]
989    async fn plan_archive_cascade_flips_published_descendants() {
990        let pool = mem_pool().await;
991        let parent = mk_page(&pool, "docs", "0001/", None, "published", None).await;
992        let child = mk_page(
993            &pool,
994            "v1",
995            "0001/0002/",
996            parent.id.get().copied(),
997            "published",
998            None,
999        )
1000        .await;
1001        let draft = mk_page(
1002            &pool,
1003            "wip",
1004            "0001/0003/",
1005            parent.id.get().copied(),
1006            "draft",
1007            None,
1008        )
1009        .await;
1010
1011        let plan = plan_archive(&pool, std::slice::from_ref(&parent), true, true)
1012            .await
1013            .expect("plan");
1014        let flip_ids: std::collections::HashSet<i64> = plan
1015            .to_flip
1016            .iter()
1017            .map(|p| p.id.get().copied().unwrap())
1018            .collect();
1019        assert!(flip_ids.contains(&parent.id.get().copied().unwrap()));
1020        assert!(
1021            flip_ids.contains(&child.id.get().copied().unwrap()),
1022            "published child flips under cascade"
1023        );
1024        assert!(
1025            !flip_ids.contains(&draft.id.get().copied().unwrap()),
1026            "draft child left untouched"
1027        );
1028        assert!(plan
1029            .to_flip
1030            .iter()
1031            .all(|p| p.status == PageStatus::Archived.as_str()));
1032    }
1033
1034    #[tokio::test]
1035    async fn plan_unarchive_symmetric_revives_archived() {
1036        let pool = mem_pool().await;
1037        let parent = mk_page(&pool, "docs", "0001/", None, "archived", None).await;
1038        let child = mk_page(
1039            &pool,
1040            "v1",
1041            "0001/0002/",
1042            parent.id.get().copied(),
1043            "archived",
1044            None,
1045        )
1046        .await;
1047
1048        // Non-archived selection is a no-op; archived selection revives.
1049        let plan = plan_archive(&pool, std::slice::from_ref(&parent), false, true)
1050            .await
1051            .expect("plan");
1052        assert!(plan
1053            .to_flip
1054            .iter()
1055            .all(|p| p.status == PageStatus::Published.as_str()));
1056        let ids: std::collections::HashSet<i64> = plan
1057            .to_flip
1058            .iter()
1059            .map(|p| p.id.get().copied().unwrap())
1060            .collect();
1061        assert!(ids.contains(&parent.id.get().copied().unwrap()));
1062        assert!(
1063            ids.contains(&child.id.get().copied().unwrap()),
1064            "cascade unarchive revives archived descendant"
1065        );
1066    }
1067}
1068
1069/// Merge an alias row with its source into the page the site actually
1070/// serves.
1071///
1072/// An alias is a real, distinct URL whose *content* belongs to another
1073/// page. The row keeps its own identity — id, slug, path, url_path,
1074/// parent_id — and borrows everything readers see: title, SEO, type,
1075/// publication dates, theme, and the promote flags. The stored `title`
1076/// on an alias is a copy taken at creation and goes stale the moment the
1077/// source is renamed, which is exactly why nothing should read it.
1078///
1079/// Shared by the renderer and `GET /api/v2/pages/{id}/` so the two cannot
1080/// disagree. They did: the tree resolved alias titles from the source
1081/// while detail returned the stale copy with no `extension` and no
1082/// `builder`, which quietly falsified the "the editor's JSON preview is
1083/// the real response" promise for every alias.
1084#[must_use]
1085pub fn alias_hybrid(alias: &Page, source: &Page) -> Page {
1086    let mut hybrid = alias.clone();
1087    hybrid.title = source.title.clone();
1088    hybrid.page_type_id = source.page_type_id;
1089    hybrid.seo_title = source.seo_title.clone();
1090    hybrid.seo_description = source.seo_description.clone();
1091    hybrid.status = source.status.clone();
1092    hybrid.published_at = source.published_at;
1093    hybrid.last_published_at = source.last_published_at;
1094    hybrid.go_live_at = source.go_live_at;
1095    hybrid.expire_at = source.expire_at;
1096    hybrid.theme_id = source.theme_id;
1097    hybrid.robots_index = source.robots_index;
1098    hybrid.sitemap_priority = source.sitemap_priority;
1099    hybrid.show_in_menus = source.show_in_menus;
1100    hybrid
1101}
1102
1103#[cfg(test)]
1104mod status_accessor_tests {
1105    use super::*;
1106
1107    #[test]
1108    fn typed_status_accessors_round_trip_and_know_public() {
1109        let mut p: Page = serde_json::from_value(serde_json::json!({
1110            "id": 1, "page_type_id": 1, "title": "T", "slug": "t", "path": "0001/",
1111            "url_path": "/t", "preview_path": "", "template_override": "", "depth": 1,
1112            "parent_id": null, "locale_variant_of": null, "alias_of": null, "theme_id": null,
1113            "sort_order": 0, "status": "draft", "published_at": null, "last_published_at": null,
1114            "go_live_at": null, "expire_at": null, "seo_title": "", "seo_description": "",
1115            "robots_index": true, "sitemap_priority": 0.5, "show_in_menus": true, "og_title": "",
1116            "og_description": "", "og_image_media_id": null, "twitter_card": "summary",
1117            "notification_pre_published_sent": false,
1118            "created_at": "2026-11-06T00:00:00Z", "updated_at": "2026-11-06T00:00:00Z"
1119        }))
1120        .unwrap();
1121        assert_eq!(p.page_status(), Some(PageStatus::Draft));
1122        assert!(!p.is_public());
1123        p.set_page_status(PageStatus::Archived);
1124        assert_eq!(p.status, "archived");
1125        assert!(p.is_public(), "archived pages are served");
1126        p.status = "bogus".into();
1127        assert_eq!(p.page_status(), None);
1128        assert!(!p.is_public());
1129    }
1130}