rustango-cms 0.4.0

A page-tree content management system for Rust, built on rustango
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! Page-builder storage models — migration-tracked, versioned.
//!
//! No DDL runs when a Developer edits a schema: a structure change writes
//! a new **draft** row, and publishing flips draft→published (version+1)
//! while archiving the prior published row. Page values live in one stable
//! JSON store ([`PageBuilderData`]) and upgrade lazily. Tables are created
//! once by the generated `0006_page_builder` migration, never altered by
//! the builder.

use chrono::{DateTime, Utc};
use rustango::core::Column as _;
use rustango::sql::{Auto, FetcherPool as _, Pool};
use rustango::Model;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

use crate::page_builder::schema::{ComponentDoc, ComponentEntry};

/// Lifecycle of a schema row. Exactly one `draft` and one `published`
/// per page type at a time (code-enforced); `archived` rows are history.
pub const STATUS_DRAFT: &str = "draft";
pub const STATUS_PUBLISHED: &str = "published";
pub const STATUS_ARCHIVED: &str = "archived";

/// A versioned body-schema document attached to a page type.
#[derive(Model, Debug, Clone, Serialize, Deserialize)]
#[rustango(
    table = "cms_page_type_schema",
    app = "cms",
    display = "status",
    admin(
        list_display = "page_type_id, status, version, updated_at",
        ordering = "page_type_id, version",
        list_filter = "status",
    )
)]
pub struct PageTypeSchema {
    #[rustango(primary_key)]
    pub id: Auto<i64>,

    #[rustango(fk = "cms_page_type", on = "id", index)]
    pub page_type_id: i64,

    /// `draft` | `published` | `archived`.
    #[rustango(max_length = 16, index)]
    pub status: String,

    /// Monotonic per page type; the published version pages record.
    #[rustango(default = "1")]
    pub version: i32,

    /// The authored node tree ([`crate::page_builder::schema::Document`]).
    #[rustango(default = "'{}'::jsonb")]
    pub document: Value,

    pub created_by: Option<i64>,

    #[rustango(auto_now_add)]
    pub created_at: Auto<DateTime<Utc>>,
    #[rustango(auto_now)]
    pub updated_at: Auto<DateTime<Utc>>,
}

/// A reusable field-group (a component), referenced from
/// schemas by slug (`c_<slug>`).
#[derive(Model, Debug, Clone, Serialize, Deserialize)]
#[rustango(
    table = "cms_component",
    app = "cms",
    display = "label",
    admin(
        list_display = "slug, label, version, updated_at",
        search_fields = "slug, label",
        ordering = "slug",
    )
)]
pub struct Component {
    #[rustango(primary_key)]
    pub id: Auto<i64>,

    #[rustango(max_length = 100, unique)]
    pub slug: String,

    #[rustango(max_length = 200)]
    pub label: String,

    #[rustango(max_length = 80, default = "''")]
    pub icon: String,

    #[rustango(max_length = 255, default = "''")]
    pub description: String,

    /// Bumped on every save; stamped onto instances for lazy upgrade.
    #[rustango(default = "1")]
    pub version: i32,

    /// [`crate::page_builder::schema::ComponentDoc`].
    #[rustango(default = "'{}'::jsonb")]
    pub document: Value,

    #[rustango(auto_now_add)]
    pub created_at: Auto<DateTime<Utc>>,
    #[rustango(auto_now)]
    pub updated_at: Auto<DateTime<Utc>>,
}

/// The filled builder values for one page (additive to any code page
/// type's own extension table). One row per page.
#[derive(Model, Debug, Clone, Serialize, Deserialize)]
#[rustango(
    table = "cms_page_builder_data",
    app = "cms",
    display = "page_id",
    admin(
        list_display = "page_id, schema_version, updated_at",
        ordering = "page_id"
    )
)]
pub struct PageBuilderData {
    #[rustango(primary_key)]
    pub id: Auto<i64>,

    #[rustango(fk = "cms_page", on = "id", unique)]
    pub page_id: i64,

    /// Published schema version the data was last saved against.
    #[rustango(default = "0")]
    pub schema_version: i32,

    /// `{ "<component_slug>": <version> }` snapshot for lazy upgrade.
    #[rustango(default = "'{}'::jsonb")]
    pub component_versions: Value,

    /// The filled values (scalars + nested groups + stream arrays +
    /// `_orphaned`).
    #[rustango(default = "'{}'::jsonb")]
    pub data: Value,

    #[rustango(auto_now)]
    pub updated_at: Auto<DateTime<Utc>>,
}

// ---- schema row helpers -------------------------------------------------

/// The published schema row for a page type, if any.
///
/// # Errors
/// Propagates query failures.
pub async fn published_for(
    pool: &Pool,
    page_type_id: i64,
) -> Result<Option<PageTypeSchema>, rustango::sql::ExecError> {
    PageTypeSchema::objects()
        .where_(PageTypeSchema::page_type_id.eq(page_type_id))
        .where_(PageTypeSchema::status.eq(STATUS_PUBLISHED.to_owned()))
        .first(pool)
        .await
}

/// The draft schema row for a page type, if any.
///
/// # Errors
/// Propagates query failures.
pub async fn draft_for(
    pool: &Pool,
    page_type_id: i64,
) -> Result<Option<PageTypeSchema>, rustango::sql::ExecError> {
    PageTypeSchema::objects()
        .where_(PageTypeSchema::page_type_id.eq(page_type_id))
        .where_(PageTypeSchema::status.eq(STATUS_DRAFT.to_owned()))
        .first(pool)
        .await
}

/// Published + archived rows for a page type, newest version first — the
/// version history.
///
/// # Errors
/// Propagates query failures.
pub async fn list_versions(
    pool: &Pool,
    page_type_id: i64,
) -> Result<Vec<PageTypeSchema>, rustango::sql::ExecError> {
    let mut rows: Vec<PageTypeSchema> = PageTypeSchema::objects()
        .where_(PageTypeSchema::page_type_id.eq(page_type_id))
        .fetch(pool)
        .await?;
    rows.retain(|r| r.status != STATUS_DRAFT);
    rows.sort_by(|a, b| b.version.cmp(&a.version));
    Ok(rows)
}

/// Upsert the single draft for a page type with `document`. Creates the
/// draft (version = published+1) if none exists.
///
/// # Errors
/// Propagates query / write failures.
pub async fn save_draft(
    pool: &Pool,
    page_type_id: i64,
    document: Value,
    created_by: Option<i64>,
) -> Result<PageTypeSchema, rustango::sql::ExecError> {
    if let Some(mut draft) = draft_for(pool, page_type_id).await? {
        draft.document = document;
        draft.save(pool).await?;
        return Ok(draft);
    }
    let next = published_for(pool, page_type_id)
        .await?
        .map_or(1, |p| p.version + 1);
    let mut row = PageTypeSchema {
        id: Auto::Unset,
        page_type_id,
        status: STATUS_DRAFT.to_owned(),
        version: next,
        document,
        created_by,
        created_at: Auto::Unset,
        updated_at: Auto::Unset,
    };
    row.insert(pool).await?;
    Ok(row)
}

/// Publish the draft: archive the current published row, flip the draft
/// to published with version = prev_published + 1. Returns the new
/// published row, or `None` when there is no draft to publish.
///
/// # Errors
/// Propagates query / write failures.
pub async fn publish(
    pool: &Pool,
    page_type_id: i64,
) -> Result<Option<PageTypeSchema>, rustango::sql::ExecError> {
    let Some(mut draft) = draft_for(pool, page_type_id).await? else {
        return Ok(None);
    };
    let prev = published_for(pool, page_type_id).await?;
    // Archive and flip in one transaction (#649): committed separately, a
    // failed flip left the old schema archived and no schema published, so
    // every page of the type rendered an empty builder body. Both rows are
    // read above, on the pool, before the transaction takes a connection.
    let mut tx = rustango::sql::transaction_pool(pool).await?;
    let prev_version = match prev {
        Some(mut prev) => {
            prev.status = STATUS_ARCHIVED.to_owned();
            prev.save_tx(&mut tx).await?;
            prev.version
        }
        None => 0,
    };
    draft.status = STATUS_PUBLISHED.to_owned();
    draft.version = prev_version + 1;
    draft.save_tx(&mut tx).await?;
    tx.commit().await?;
    Ok(Some(draft))
}

// ---- component helpers --------------------------------------------------

/// Every reusable component, ordered by slug.
///
/// # Errors
/// Propagates query failures.
pub async fn all_components(pool: &Pool) -> Result<Vec<Component>, rustango::sql::ExecError> {
    Component::objects()
        .order_by(&[("slug", false)])
        .fetch(pool)
        .await
}

/// Component library as a `slug → entry` map for [`crate::page_builder::validate_schema`]
/// / [`crate::page_builder::compile()`]. Malformed component docs are skipped.
///
/// # Errors
/// Propagates query failures.
pub async fn component_map(
    pool: &Pool,
) -> Result<HashMap<String, ComponentEntry>, rustango::sql::ExecError> {
    let rows = all_components(pool).await?;
    let mut map = HashMap::new();
    for c in rows {
        let doc: ComponentDoc = serde_json::from_value(c.document.clone()).unwrap_or_default();
        map.insert(
            c.slug.clone(),
            ComponentEntry {
                doc,
                version: c.version.max(1) as u32,
            },
        );
    }
    Ok(map)
}

/// One component by id.
///
/// # Errors
/// Propagates query failures.
pub async fn component_by_id(
    pool: &Pool,
    id: i64,
) -> Result<Option<Component>, rustango::sql::ExecError> {
    Component::objects()
        .where_(Component::id.eq(id))
        .first(pool)
        .await
}

/// Create a component (version 1). `document` is a [`ComponentDoc`] JSON.
///
/// # Errors
/// Propagates the insert failure (incl. the unique-slug violation).
pub async fn create_component(
    pool: &Pool,
    slug: &str,
    label: &str,
    icon: &str,
    description: &str,
    document: Value,
) -> Result<Component, rustango::sql::ExecError> {
    let mut row = Component {
        id: Auto::Unset,
        slug: slug.to_owned(),
        label: label.to_owned(),
        icon: icon.to_owned(),
        description: description.to_owned(),
        version: 1,
        document,
        created_at: Auto::Unset,
        updated_at: Auto::Unset,
    };
    row.insert(pool).await?;
    Ok(row)
}

/// Update a component's metadata + document and bump its version so
/// referencing schemas pick the change up lazily (next open / render).
/// The slug is immutable (it's the reference key).
///
/// # Errors
/// Propagates query / write failures.
pub async fn update_component(
    pool: &Pool,
    id: i64,
    label: &str,
    icon: &str,
    description: &str,
    document: Value,
) -> Result<Option<Component>, rustango::sql::ExecError> {
    let Some(mut row) = component_by_id(pool, id).await? else {
        return Ok(None);
    };
    row.label = label.to_owned();
    row.icon = icon.to_owned();
    row.description = description.to_owned();
    row.document = document;
    row.version += 1;
    row.save(pool).await?;
    Ok(Some(row))
}

/// Delete a component by id (no-op if it's already gone).
///
/// # Errors
/// Propagates the delete failure.
pub async fn delete_component(pool: &Pool, id: i64) -> Result<(), rustango::sql::ExecError> {
    if let Some(row) = component_by_id(pool, id).await? {
        row.delete(pool).await?;
    }
    Ok(())
}

/// Page types whose non-archived (draft or published) schema references
/// a component slug — returns `(page_type_id, status)` pairs. Used to
/// block deletion of an in-use component.
///
/// # Errors
/// Propagates query failures.
pub async fn component_references(
    pool: &Pool,
    slug: &str,
) -> Result<Vec<(i64, String)>, rustango::sql::ExecError> {
    let rows: Vec<PageTypeSchema> = PageTypeSchema::objects().fetch(pool).await?;
    let mut out = Vec::new();
    for row in rows {
        if row.status == STATUS_ARCHIVED {
            continue;
        }
        if let Ok(doc) = crate::page_builder::schema::parse(&row.document) {
            if crate::page_builder::schema::references_component(&doc, slug) {
                out.push((row.page_type_id, row.status));
            }
        }
    }
    Ok(out)
}

/// How many live page-type schemas reference each of `slugs`, from one
/// scan of the schemas (what [`component_references`] would count, for
/// every slug at once).
///
/// # Errors
/// Propagates query failures.
pub async fn component_reference_counts<'a>(
    pool: &Pool,
    slugs: &[&'a str],
) -> Result<HashMap<&'a str, usize>, rustango::sql::ExecError> {
    let rows: Vec<PageTypeSchema> = PageTypeSchema::objects().fetch(pool).await?;
    let mut out: HashMap<&'a str, usize> = HashMap::new();
    for row in rows {
        if row.status == STATUS_ARCHIVED {
            continue;
        }
        if let Ok(doc) = crate::page_builder::schema::parse(&row.document) {
            for slug in slugs {
                if crate::page_builder::schema::references_component(&doc, slug) {
                    *out.entry(*slug).or_default() += 1;
                }
            }
        }
    }
    Ok(out)
}

// ---- page value helpers -------------------------------------------------

/// The stored builder values for a page, if any.
///
/// # Errors
/// Propagates query failures.
pub async fn data_for_page(
    pool: &Pool,
    page_id: i64,
) -> Result<Option<PageBuilderData>, rustango::sql::ExecError> {
    PageBuilderData::objects()
        .where_(PageBuilderData::page_id.eq(page_id))
        .first(pool)
        .await
}

/// Upsert a page's builder values.
///
/// # Errors
/// Propagates query / write failures.
pub async fn upsert_data(
    pool: &Pool,
    page_id: i64,
    schema_version: i32,
    component_versions: Value,
    data: Value,
) -> Result<(), rustango::sql::ExecError> {
    if let Some(mut row) = data_for_page(pool, page_id).await? {
        row.schema_version = schema_version;
        row.component_versions = component_versions;
        row.data = data;
        row.save(pool).await?;
    } else {
        let mut row = PageBuilderData {
            id: Auto::Unset,
            page_id,
            schema_version,
            component_versions,
            data,
            updated_at: Auto::Unset,
        };
        row.insert(pool).await?;
    }
    Ok(())
}

#[cfg(all(test, feature = "sqlite"))]
mod tests {
    use super::*;
    use rustango::core::Model as _;
    use rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect;

    async fn mem_pool() -> Pool {
        let pool = Pool::connect("sqlite::memory:").await.expect("mem pool");
        // Only the schema table is needed for these unit tests (no FK
        // enforcement target rows involved — page_type_id is a bare int
        // here; sqlite in-memory has FKs off unless a target exists).
        for schema in [
            &crate::page_type_model::PageType::SCHEMA,
            &PageTypeSchema::SCHEMA,
            &Component::SCHEMA,
        ] {
            let 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");
            }
        }
        pool
    }

    async fn mk_page_type(pool: &Pool, type_name: &str) -> i64 {
        let mut pt = crate::page_type_model::PageType {
            id: Auto::Unset,
            app_label: "cms".to_owned(),
            type_name: type_name.to_owned(),
            verbose_name: type_name.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 page type");
        pt.id.get().copied().unwrap()
    }

    #[tokio::test]
    async fn reference_counts_match_per_slug_lookups() {
        let pool = mem_pool().await;
        let a = mk_page_type(&pool, "A").await;
        let b = mk_page_type(&pool, "B").await;
        let direct = |slug: &str| serde_json::json!({"nodes": [{"kind": "component", "ref": slug}]});
        save_draft(&pool, a, direct("cta"), None).await.unwrap();
        publish(&pool, a).await.unwrap();
        save_draft(
            &pool,
            a,
            serde_json::json!({"nodes": [{"kind": "flex", "key": "z", "allowed": ["c_cta", "c_hero"]}]}),
            None,
        )
        .await
        .unwrap();
        save_draft(&pool, b, direct("hero"), None).await.unwrap();
        publish(&pool, b).await.unwrap();
        save_draft(&pool, b, serde_json::json!({"nodes": []}), None).await.unwrap();
        publish(&pool, b).await.unwrap(); // archives the version naming `hero`

        let slugs = ["cta", "hero", "unused"];
        let counts = component_reference_counts(&pool, &slugs).await.unwrap();
        for slug in slugs {
            let one = component_references(&pool, slug).await.unwrap().len();
            assert_eq!(counts.get(slug).copied().unwrap_or(0), one, "{slug}");
        }
        assert_eq!(counts.get("cta"), Some(&2));
        assert_eq!(counts.get("hero"), Some(&1));
    }

    #[tokio::test]
    async fn draft_publish_versions_flow() {
        let pool = mem_pool().await;
        let ptid = mk_page_type(&pool, "Standard").await;
        // First draft → publish → v1.
        save_draft(&pool, ptid, serde_json::json!({"nodes": []}), None)
            .await
            .unwrap();
        assert!(draft_for(&pool, ptid).await.unwrap().is_some());
        let p1 = publish(&pool, ptid).await.unwrap().expect("published");
        assert_eq!(p1.version, 1);
        assert_eq!(p1.status, STATUS_PUBLISHED);
        assert!(
            draft_for(&pool, ptid).await.unwrap().is_none(),
            "draft consumed"
        );

        // Edit → new draft carries v2 preview → publish → v2, v1 archived.
        let d2 = save_draft(&pool, ptid, serde_json::json!({"nodes": [1]}), None)
            .await
            .unwrap();
        assert_eq!(d2.version, 2);
        let p2 = publish(&pool, ptid).await.unwrap().expect("published v2");
        assert_eq!(p2.version, 2);
        let hist = list_versions(&pool, ptid).await.unwrap();
        assert_eq!(hist.len(), 2, "v2 published + v1 archived");
        assert_eq!(hist[0].version, 2);
        assert_eq!(hist[0].status, STATUS_PUBLISHED);
        assert_eq!(hist[1].status, STATUS_ARCHIVED);

        // Publish with no draft → None.
        assert!(publish(&pool, ptid).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn re_saving_draft_updates_in_place() {
        let pool = mem_pool().await;
        let ptid = mk_page_type(&pool, "Standard").await;
        save_draft(&pool, ptid, serde_json::json!({"nodes": [1]}), None)
            .await
            .unwrap();
        save_draft(&pool, ptid, serde_json::json!({"nodes": [1, 2]}), None)
            .await
            .unwrap();
        let drafts: Vec<PageTypeSchema> = PageTypeSchema::objects()
            .where_(PageTypeSchema::page_type_id.eq(ptid))
            .where_(PageTypeSchema::status.eq(STATUS_DRAFT.to_owned()))
            .fetch(&pool)
            .await
            .unwrap();
        assert_eq!(drafts.len(), 1, "one draft, updated in place");
    }
}