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