Skip to main content

rustango_cms/
comment.rs

1//! Inline comments on the page editor.
2//!
3//! Editors can leave a per-field comment thread on any page they're
4//! editing — `TODO: confirm date with marketing` on the body field,
5//! a reviewer reply, a resolve action when the concern is addressed.
6//!
7//! Each comment is anchored to a field (`field_path`) and surfaces in
8//! the editor's side panel, with a reply-thread API.
9//!
10//! ## Shape
11//!
12//! - One [`Comment`] row per thread root (pinned to a `field_path`)
13//! - N [`CommentReply`] rows per thread (chronological)
14//! - Threads resolve at the root via `Comment.resolved_at`
15//!
16//! ## Field-path shape
17//!
18//! Same shape `cms_translation.field_path` uses — dotted path into
19//! a page's scalar columns or its StreamField blocks. Examples:
20//! `title`, `body.<block-uuid>.heading`, `seo_description`.
21//! Resilient to field renames at the StreamField level (block UUIDs
22//! survive); scalar renames invalidate the thread until manually
23//! moved.
24
25use chrono::{DateTime, Utc};
26use rustango::sql::Auto;
27use rustango::Model;
28use serde::{Deserialize, Serialize};
29
30#[derive(Model, Debug, Clone, Serialize, Deserialize)]
31#[rustango(
32    table = "cms_comment",
33    app = "cms",
34    display = "id",
35    admin(
36        list_display = "page_id, field_path, author_id, resolved_at, created_at",
37        ordering = "-created_at",
38        list_filter = "page_id, resolved_at",
39    )
40)]
41pub struct Comment {
42    #[rustango(primary_key)]
43    pub id: Auto<i64>,
44
45    #[rustango(fk = "cms_page", on = "id", index)]
46    pub page_id: i64,
47
48    /// Same shape as `cms_translation.field_path`. Indexed so the
49    /// per-field annotation badge can count threads in one query.
50    #[rustango(max_length = 255, index)]
51    pub field_path: String,
52
53    #[rustango(fk = "rustango_users", on = "id", index)]
54    pub author_id: i64,
55
56    /// Free-form text. No markdown rendering for v1 — kept plain so
57    /// rendering can't be a security surface. Multi-line wraps in
58    /// the side panel via `white-space: pre-wrap`.
59    pub body: String,
60
61    /// Set when an editor (typically the original author or any
62    /// reviewer) marks the thread resolved. `None` while open.
63    pub resolved_at: Option<DateTime<Utc>>,
64
65    /// User id who clicked Resolve. `None` while open.
66    pub resolved_by: Option<i64>,
67
68    #[rustango(auto_now_add)]
69    pub created_at: Auto<DateTime<Utc>>,
70}
71
72#[derive(Model, Debug, Clone, Serialize, Deserialize)]
73#[rustango(
74    table = "cms_comment_reply",
75    app = "cms",
76    display = "id",
77    admin(
78        list_display = "comment_id, author_id, created_at",
79        ordering = "comment_id, created_at",
80        list_filter = "comment_id",
81    )
82)]
83pub struct CommentReply {
84    #[rustango(primary_key)]
85    pub id: Auto<i64>,
86
87    /// FK to the thread root.
88    #[rustango(fk = "cms_comment", on = "id", index)]
89    pub comment_id: i64,
90
91    #[rustango(fk = "rustango_users", on = "id", index)]
92    pub author_id: i64,
93
94    pub body: String,
95
96    #[rustango(auto_now_add)]
97    pub created_at: Auto<DateTime<Utc>>,
98}
99
100/// Fetch every open + resolved thread for a page, in newest-first
101/// order. The side panel filters resolved threads to a separate
102/// "Resolved" bucket client-side.
103///
104/// # Errors
105/// Driver / query failures.
106pub async fn threads_for_page(
107    pool: &rustango::sql::Pool,
108    page_id: i64,
109) -> Result<Vec<Comment>, rustango::sql::ExecError> {
110    use rustango::core::Column as _;
111    use rustango::sql::FetcherPool as _;
112    Comment::objects()
113        .where_(Comment::page_id.eq(page_id))
114        .order_by(&[("created_at", true)]) // desc
115        .fetch(pool)
116        .await
117}
118
119/// Fetch every reply for a list of thread ids in one query, then
120/// bucket per thread. Returns `comment_id → Vec<replies>`.
121///
122/// # Errors
123/// Driver / query failures.
124pub async fn replies_for_threads(
125    pool: &rustango::sql::Pool,
126    thread_ids: &[i64],
127) -> Result<std::collections::HashMap<i64, Vec<CommentReply>>, rustango::sql::ExecError> {
128    use rustango::core::Column as _;
129    use rustango::sql::FetcherPool as _;
130    if thread_ids.is_empty() {
131        return Ok(std::collections::HashMap::new());
132    }
133    let all: Vec<CommentReply> = CommentReply::objects()
134        .where_(CommentReply::comment_id.is_in(thread_ids.iter().copied()))
135        .order_by(&[("created_at", false), ("id", false)])
136        .fetch(pool)
137        .await?;
138    let mut out: std::collections::HashMap<i64, Vec<CommentReply>> =
139        std::collections::HashMap::new();
140    for r in all {
141        out.entry(r.comment_id).or_default().push(r);
142    }
143    Ok(out)
144}