1use chrono::{DateTime, Utc};
11use rustango::core::Column as _;
12use rustango::sql::{Auto, FetcherPool as _, Pool};
13use rustango::Model;
14use serde::{Deserialize, Serialize};
15use serde_json::Value;
16use std::collections::HashMap;
17
18use crate::page_builder::schema::{ComponentDoc, ComponentEntry};
19
20pub const STATUS_DRAFT: &str = "draft";
23pub const STATUS_PUBLISHED: &str = "published";
24pub const STATUS_ARCHIVED: &str = "archived";
25
26#[derive(Model, Debug, Clone, Serialize, Deserialize)]
28#[rustango(
29 table = "cms_page_type_schema",
30 app = "cms",
31 display = "status",
32 admin(
33 list_display = "page_type_id, status, version, updated_at",
34 ordering = "page_type_id, version",
35 list_filter = "status",
36 )
37)]
38pub struct PageTypeSchema {
39 #[rustango(primary_key)]
40 pub id: Auto<i64>,
41
42 #[rustango(fk = "cms_page_type", on = "id", index)]
43 pub page_type_id: i64,
44
45 #[rustango(max_length = 16, index)]
47 pub status: String,
48
49 #[rustango(default = "1")]
51 pub version: i32,
52
53 #[rustango(default = "'{}'::jsonb")]
55 pub document: Value,
56
57 pub created_by: Option<i64>,
58
59 #[rustango(auto_now_add)]
60 pub created_at: Auto<DateTime<Utc>>,
61 #[rustango(auto_now)]
62 pub updated_at: Auto<DateTime<Utc>>,
63}
64
65#[derive(Model, Debug, Clone, Serialize, Deserialize)]
68#[rustango(
69 table = "cms_component",
70 app = "cms",
71 display = "label",
72 admin(
73 list_display = "slug, label, version, updated_at",
74 search_fields = "slug, label",
75 ordering = "slug",
76 )
77)]
78pub struct Component {
79 #[rustango(primary_key)]
80 pub id: Auto<i64>,
81
82 #[rustango(max_length = 100, unique)]
83 pub slug: String,
84
85 #[rustango(max_length = 200)]
86 pub label: String,
87
88 #[rustango(max_length = 80, default = "''")]
89 pub icon: String,
90
91 #[rustango(max_length = 255, default = "''")]
92 pub description: String,
93
94 #[rustango(default = "1")]
96 pub version: i32,
97
98 #[rustango(default = "'{}'::jsonb")]
100 pub document: Value,
101
102 #[rustango(auto_now_add)]
103 pub created_at: Auto<DateTime<Utc>>,
104 #[rustango(auto_now)]
105 pub updated_at: Auto<DateTime<Utc>>,
106}
107
108#[derive(Model, Debug, Clone, Serialize, Deserialize)]
111#[rustango(
112 table = "cms_page_builder_data",
113 app = "cms",
114 display = "page_id",
115 admin(
116 list_display = "page_id, schema_version, updated_at",
117 ordering = "page_id"
118 )
119)]
120pub struct PageBuilderData {
121 #[rustango(primary_key)]
122 pub id: Auto<i64>,
123
124 #[rustango(fk = "cms_page", on = "id", unique)]
125 pub page_id: i64,
126
127 #[rustango(default = "0")]
129 pub schema_version: i32,
130
131 #[rustango(default = "'{}'::jsonb")]
133 pub component_versions: Value,
134
135 #[rustango(default = "'{}'::jsonb")]
138 pub data: Value,
139
140 #[rustango(auto_now)]
141 pub updated_at: Auto<DateTime<Utc>>,
142}
143
144pub async fn published_for(
151 pool: &Pool,
152 page_type_id: i64,
153) -> Result<Option<PageTypeSchema>, rustango::sql::ExecError> {
154 PageTypeSchema::objects()
155 .where_(PageTypeSchema::page_type_id.eq(page_type_id))
156 .where_(PageTypeSchema::status.eq(STATUS_PUBLISHED.to_owned()))
157 .first(pool)
158 .await
159}
160
161pub async fn draft_for(
166 pool: &Pool,
167 page_type_id: i64,
168) -> Result<Option<PageTypeSchema>, rustango::sql::ExecError> {
169 PageTypeSchema::objects()
170 .where_(PageTypeSchema::page_type_id.eq(page_type_id))
171 .where_(PageTypeSchema::status.eq(STATUS_DRAFT.to_owned()))
172 .first(pool)
173 .await
174}
175
176pub async fn list_versions(
182 pool: &Pool,
183 page_type_id: i64,
184) -> Result<Vec<PageTypeSchema>, rustango::sql::ExecError> {
185 let mut rows: Vec<PageTypeSchema> = PageTypeSchema::objects()
186 .where_(PageTypeSchema::page_type_id.eq(page_type_id))
187 .fetch(pool)
188 .await?;
189 rows.retain(|r| r.status != STATUS_DRAFT);
190 rows.sort_by(|a, b| b.version.cmp(&a.version));
191 Ok(rows)
192}
193
194pub async fn save_draft(
200 pool: &Pool,
201 page_type_id: i64,
202 document: Value,
203 created_by: Option<i64>,
204) -> Result<PageTypeSchema, rustango::sql::ExecError> {
205 if let Some(mut draft) = draft_for(pool, page_type_id).await? {
206 draft.document = document;
207 draft.save_pool(pool).await?;
208 return Ok(draft);
209 }
210 let next = published_for(pool, page_type_id)
211 .await?
212 .map_or(1, |p| p.version + 1);
213 let mut row = PageTypeSchema {
214 id: Auto::Unset,
215 page_type_id,
216 status: STATUS_DRAFT.to_owned(),
217 version: next,
218 document,
219 created_by,
220 created_at: Auto::Unset,
221 updated_at: Auto::Unset,
222 };
223 row.insert_pool(pool).await?;
224 Ok(row)
225}
226
227pub async fn publish(
234 pool: &Pool,
235 page_type_id: i64,
236) -> Result<Option<PageTypeSchema>, rustango::sql::ExecError> {
237 let Some(mut draft) = draft_for(pool, page_type_id).await? else {
238 return Ok(None);
239 };
240 let prev = published_for(pool, page_type_id).await?;
241 let mut tx = rustango::sql::transaction_pool(pool).await?;
246 let prev_version = match prev {
247 Some(mut prev) => {
248 prev.status = STATUS_ARCHIVED.to_owned();
249 prev.save_tx(&mut tx).await?;
250 prev.version
251 }
252 None => 0,
253 };
254 draft.status = STATUS_PUBLISHED.to_owned();
255 draft.version = prev_version + 1;
256 draft.save_tx(&mut tx).await?;
257 tx.commit().await?;
258 Ok(Some(draft))
259}
260
261pub async fn all_components(pool: &Pool) -> Result<Vec<Component>, rustango::sql::ExecError> {
268 Component::objects()
269 .order_by(&[("slug", false)])
270 .fetch(pool)
271 .await
272}
273
274pub async fn component_map(
280 pool: &Pool,
281) -> Result<HashMap<String, ComponentEntry>, rustango::sql::ExecError> {
282 let rows = all_components(pool).await?;
283 let mut map = HashMap::new();
284 for c in rows {
285 let doc: ComponentDoc = serde_json::from_value(c.document.clone()).unwrap_or_default();
286 map.insert(
287 c.slug.clone(),
288 ComponentEntry {
289 doc,
290 version: c.version.max(1) as u32,
291 },
292 );
293 }
294 Ok(map)
295}
296
297pub async fn component_by_id(
302 pool: &Pool,
303 id: i64,
304) -> Result<Option<Component>, rustango::sql::ExecError> {
305 Component::objects()
306 .where_(Component::id.eq(id))
307 .first(pool)
308 .await
309}
310
311pub async fn create_component(
316 pool: &Pool,
317 slug: &str,
318 label: &str,
319 icon: &str,
320 description: &str,
321 document: Value,
322) -> Result<Component, rustango::sql::ExecError> {
323 let mut row = Component {
324 id: Auto::Unset,
325 slug: slug.to_owned(),
326 label: label.to_owned(),
327 icon: icon.to_owned(),
328 description: description.to_owned(),
329 version: 1,
330 document,
331 created_at: Auto::Unset,
332 updated_at: Auto::Unset,
333 };
334 row.insert_pool(pool).await?;
335 Ok(row)
336}
337
338pub async fn update_component(
345 pool: &Pool,
346 id: i64,
347 label: &str,
348 icon: &str,
349 description: &str,
350 document: Value,
351) -> Result<Option<Component>, rustango::sql::ExecError> {
352 let Some(mut row) = component_by_id(pool, id).await? else {
353 return Ok(None);
354 };
355 row.label = label.to_owned();
356 row.icon = icon.to_owned();
357 row.description = description.to_owned();
358 row.document = document;
359 row.version += 1;
360 row.save_pool(pool).await?;
361 Ok(Some(row))
362}
363
364pub async fn delete_component(pool: &Pool, id: i64) -> Result<(), rustango::sql::ExecError> {
369 if let Some(row) = component_by_id(pool, id).await? {
370 row.delete_pool(pool).await?;
371 }
372 Ok(())
373}
374
375pub async fn component_references(
382 pool: &Pool,
383 slug: &str,
384) -> Result<Vec<(i64, String)>, rustango::sql::ExecError> {
385 let rows: Vec<PageTypeSchema> = PageTypeSchema::objects().fetch(pool).await?;
386 let mut out = Vec::new();
387 for row in rows {
388 if row.status == STATUS_ARCHIVED {
389 continue;
390 }
391 if let Ok(doc) = crate::page_builder::schema::parse(&row.document) {
392 if crate::page_builder::schema::references_component(&doc, slug) {
393 out.push((row.page_type_id, row.status));
394 }
395 }
396 }
397 Ok(out)
398}
399
400pub async fn data_for_page(
407 pool: &Pool,
408 page_id: i64,
409) -> Result<Option<PageBuilderData>, rustango::sql::ExecError> {
410 PageBuilderData::objects()
411 .where_(PageBuilderData::page_id.eq(page_id))
412 .first(pool)
413 .await
414}
415
416pub async fn upsert_data(
421 pool: &Pool,
422 page_id: i64,
423 schema_version: i32,
424 component_versions: Value,
425 data: Value,
426) -> Result<(), rustango::sql::ExecError> {
427 if let Some(mut row) = data_for_page(pool, page_id).await? {
428 row.schema_version = schema_version;
429 row.component_versions = component_versions;
430 row.data = data;
431 row.save_pool(pool).await?;
432 } else {
433 let mut row = PageBuilderData {
434 id: Auto::Unset,
435 page_id,
436 schema_version,
437 component_versions,
438 data,
439 updated_at: Auto::Unset,
440 };
441 row.insert_pool(pool).await?;
442 }
443 Ok(())
444}
445
446#[cfg(all(test, feature = "sqlite"))]
447mod tests {
448 use super::*;
449 use rustango::core::Model as _;
450 use rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect;
451
452 async fn mem_pool() -> Pool {
453 let pool = Pool::connect("sqlite::memory:").await.expect("mem pool");
454 for schema in [
458 &crate::page_type_model::PageType::SCHEMA,
459 &PageTypeSchema::SCHEMA,
460 &Component::SCHEMA,
461 ] {
462 let ddl = create_table_if_not_exists_sql_with_dialect(pool.dialect(), schema);
463 for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
464 rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
465 .await
466 .expect("ddl");
467 }
468 }
469 pool
470 }
471
472 async fn mk_page_type(pool: &Pool, type_name: &str) -> i64 {
473 let mut pt = crate::page_type_model::PageType {
474 id: Auto::Unset,
475 app_label: "cms".to_owned(),
476 type_name: type_name.to_owned(),
477 verbose_name: type_name.to_owned(),
478 default_template: "page.html".to_owned(),
479 view_mode: "auto".to_owned(),
480 is_creatable: true,
481 allowed_parent_types: serde_json::json!([]),
482 allowed_child_types: serde_json::json!([]),
483 workflow: String::new(),
484 created_at: Auto::Unset,
485 updated_at: Auto::Unset,
486 };
487 pt.insert_pool(pool).await.expect("insert page type");
488 pt.id.get().copied().unwrap()
489 }
490
491 #[tokio::test]
492 async fn draft_publish_versions_flow() {
493 let pool = mem_pool().await;
494 let ptid = mk_page_type(&pool, "Standard").await;
495 save_draft(&pool, ptid, serde_json::json!({"nodes": []}), None)
497 .await
498 .unwrap();
499 assert!(draft_for(&pool, ptid).await.unwrap().is_some());
500 let p1 = publish(&pool, ptid).await.unwrap().expect("published");
501 assert_eq!(p1.version, 1);
502 assert_eq!(p1.status, STATUS_PUBLISHED);
503 assert!(
504 draft_for(&pool, ptid).await.unwrap().is_none(),
505 "draft consumed"
506 );
507
508 let d2 = save_draft(&pool, ptid, serde_json::json!({"nodes": [1]}), None)
510 .await
511 .unwrap();
512 assert_eq!(d2.version, 2);
513 let p2 = publish(&pool, ptid).await.unwrap().expect("published v2");
514 assert_eq!(p2.version, 2);
515 let hist = list_versions(&pool, ptid).await.unwrap();
516 assert_eq!(hist.len(), 2, "v2 published + v1 archived");
517 assert_eq!(hist[0].version, 2);
518 assert_eq!(hist[0].status, STATUS_PUBLISHED);
519 assert_eq!(hist[1].status, STATUS_ARCHIVED);
520
521 assert!(publish(&pool, ptid).await.unwrap().is_none());
523 }
524
525 #[tokio::test]
526 async fn re_saving_draft_updates_in_place() {
527 let pool = mem_pool().await;
528 let ptid = mk_page_type(&pool, "Standard").await;
529 save_draft(&pool, ptid, serde_json::json!({"nodes": [1]}), None)
530 .await
531 .unwrap();
532 save_draft(&pool, ptid, serde_json::json!({"nodes": [1, 2]}), None)
533 .await
534 .unwrap();
535 let drafts: Vec<PageTypeSchema> = PageTypeSchema::objects()
536 .where_(PageTypeSchema::page_type_id.eq(ptid))
537 .where_(PageTypeSchema::status.eq(STATUS_DRAFT.to_owned()))
538 .fetch(&pool)
539 .await
540 .unwrap();
541 assert_eq!(drafts.len(), 1, "one draft, updated in place");
542 }
543}