1use crate::ids::WorkspaceId;
2use anyhow::Result;
3use sqlx::{Row, SqliteConnection};
4
5use crate::refs::DisplayRefContext;
6use crate::task_fields::TaskField;
7use crate::types::Task;
8
9use super::{
10 SortDirection, TaskDependencySummary, TaskFilters, TaskListItem, TaskQueryMode, TaskSort,
11 list_task_items_with_display_refs, task_dependency_summary_with_display_refs,
12};
13
14#[derive(Debug)]
15pub struct TaskDetail {
16 pub item: TaskListItem,
17 pub project_name: String,
18 pub dependencies: TaskDependencySummary,
19 pub notes: Vec<TaskDetailNote>,
20 pub conflicts: Vec<TaskDetailConflict>,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct TaskDetailNote {
25 pub id: String,
26 pub body: String,
27 pub created_at: String,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct TaskDetailConflict {
32 pub field: String,
33 pub variant_a: String,
34 pub local_value: String,
35 pub variant_b: String,
36 pub remote_value: String,
37}
38
39pub async fn task_detail(conn: &mut SqliteConnection, task: &Task) -> Result<TaskDetail> {
40 let display_refs = DisplayRefContext::for_workspace(conn, &task.workspace_id).await?;
41 task_detail_with_display_refs(conn, task, &display_refs).await
42}
43
44pub async fn task_detail_with_display_refs(
45 conn: &mut SqliteConnection,
46 task: &Task,
47 display_refs: &DisplayRefContext,
48) -> Result<TaskDetail> {
49 let item = list_task_items_with_display_refs(
50 conn,
51 &task.workspace_id,
52 TaskFilters {
53 task_ids: vec![task.id.clone()],
54 ..TaskFilters::default().include_deleted(task.deleted)
55 },
56 TaskQueryMode::Flat,
57 TaskSort::Updated,
58 SortDirection::Desc,
59 display_refs,
60 )
61 .await?
62 .into_iter()
63 .next()
64 .expect("task must exist after resolve");
65 let project_name = sqlx::query_scalar::<_, String>(
66 "SELECT name FROM projects WHERE workspace_id = ? AND id = ?",
67 )
68 .bind(&task.workspace_id)
69 .bind(&task.project_id)
70 .fetch_one(&mut *conn)
71 .await?;
72 let dependencies =
73 task_dependency_summary_with_display_refs(conn, &task.workspace_id, &task.id, display_refs)
74 .await?;
75 let notes = task_detail_notes(conn, &task.workspace_id, &task.id).await?;
76 let conflicts = task_detail_conflicts(conn, &task.workspace_id, &task.id).await?;
77
78 Ok(TaskDetail {
79 item,
80 project_name,
81 dependencies,
82 notes,
83 conflicts,
84 })
85}
86
87async fn task_detail_notes(
88 conn: &mut SqliteConnection,
89 workspace_id: &WorkspaceId,
90 task_id: &crate::ids::TaskId,
91) -> Result<Vec<TaskDetailNote>> {
92 let rows = sqlx::query(
93 "SELECT id, body, created_at FROM notes
94 WHERE workspace_id = ? AND task_id = ? ORDER BY created_at, id",
95 )
96 .bind(workspace_id)
97 .bind(task_id)
98 .fetch_all(&mut *conn)
99 .await?;
100
101 Ok(rows
102 .into_iter()
103 .map(|row| TaskDetailNote {
104 id: row.get("id"),
105 body: row.get("body"),
106 created_at: row.get("created_at"),
107 })
108 .collect())
109}
110
111async fn task_detail_conflicts(
112 conn: &mut SqliteConnection,
113 workspace_id: &WorkspaceId,
114 task_id: &crate::ids::TaskId,
115) -> Result<Vec<TaskDetailConflict>> {
116 let rows = sqlx::query(
117 "SELECT field, variant_a, local_value, variant_b, remote_value
118 FROM conflicts
119 WHERE workspace_id = ? AND task_id = ? AND resolved = 0
120 ORDER BY field, id",
121 )
122 .bind(workspace_id)
123 .bind(task_id)
124 .fetch_all(&mut *conn)
125 .await?;
126
127 Ok(rows
128 .into_iter()
129 .map(|row| TaskDetailConflict {
130 field: row.get("field"),
131 variant_a: row.get("variant_a"),
132 local_value: row.get("local_value"),
133 variant_b: row.get("variant_b"),
134 remote_value: row.get("remote_value"),
135 })
136 .collect())
137}
138
139pub async fn conflict_display_value(
140 conn: &mut SqliteConnection,
141 workspace_id: &WorkspaceId,
142 field: &str,
143 value: &str,
144) -> Result<String> {
145 match TaskField::parse(field) {
146 Some(TaskField::Project) => display_project_conflict_value(conn, workspace_id, value).await,
147 Some(TaskField::IsEpic) => Ok(match value {
148 "1" => "on".to_string(),
149 "0" => "off".to_string(),
150 other => other.to_string(),
151 }),
152 _ => Ok(value.to_string()),
153 }
154}
155
156async fn display_project_conflict_value(
157 conn: &mut SqliteConnection,
158 workspace_id: &WorkspaceId,
159 value: &str,
160) -> Result<String> {
161 if let Some((key, prefix)) = sqlx::query_as::<_, (String, String)>(
162 "SELECT key, prefix FROM projects WHERE workspace_id = ? AND id = ?",
163 )
164 .bind(workspace_id)
165 .bind(value)
166 .fetch_optional(&mut *conn)
167 .await?
168 {
169 return Ok(format!("{key} prefix={prefix}"));
170 }
171 Ok(value.to_string())
172}
173
174#[cfg(test)]
175mod tests {
176 use super::*;
177
178 #[tokio::test]
179 async fn task_detail_loads_enriched_fields_in_stable_order() {
180 let (_temp, mut conn) = crate::test_support::test_conn().await;
181 let workspace = crate::workspaces::Workspace::default();
182 let workspace_id = workspace.id.clone();
183 sqlx::query(
184 "INSERT INTO projects(id, key, name, prefix, created_at, updated_at)
185 VALUES ('00000000000000D1', 'detail', 'Detail Project', 'DTL', 't', 't')",
186 )
187 .execute(&mut *conn)
188 .await
189 .unwrap();
190 for (id, title) in [
191 ("D3TA100000000001", "detailed task"),
192 ("D3TA100000000002", "blocker task"),
193 ] {
194 sqlx::query(
195 "INSERT INTO tasks(id, title, description, project_id, status, priority, created_at, updated_at, queue_activity_at)
196 VALUES (?, ?, 'description', '00000000000000D1', 'todo', 'high', 't', 't', 't')",
197 )
198 .bind(id)
199 .bind(title)
200 .execute(&mut *conn)
201 .await
202 .unwrap();
203 }
204 sqlx::query(
205 "INSERT INTO notes(workspace_id, id, task_id, body, created_at, change_id)
206 VALUES (?, 'note-b', 'D3TA100000000001', 'second', '002', 'change-b'),
207 (?, 'note-a', 'D3TA100000000001', 'first', '001', 'change-a')",
208 )
209 .bind(&workspace_id)
210 .bind(&workspace_id)
211 .execute(&mut *conn)
212 .await
213 .unwrap();
214 sqlx::query(
215 "INSERT INTO task_dependencies(workspace_id, task_id, depends_on_task_id, created_at)
216 VALUES (?, 'D3TA100000000001', 'D3TA100000000002', '003')",
217 )
218 .bind(&workspace_id)
219 .execute(&mut *conn)
220 .await
221 .unwrap();
222 for (field, resolved) in [("title", 0), ("priority", 1)] {
223 sqlx::query(
224 "INSERT INTO conflicts(workspace_id, task_id, field, local_value, remote_value,
225 remote_change_id, variant_a, variant_b, created_at, resolved)
226 VALUES (?, 'D3TA100000000001', ?, 'local', 'remote', ?, 'a', 'b', '004', ?)",
227 )
228 .bind(&workspace_id)
229 .bind(field)
230 .bind(format!("remote-{field}"))
231 .bind(resolved)
232 .execute(&mut *conn)
233 .await
234 .unwrap();
235 }
236
237 let task =
238 crate::refs::resolve_task_ref_in_workspace(&mut conn, &workspace, "D3TA100000000001")
239 .await
240 .unwrap();
241 let detail = task_detail(&mut conn, &task).await.unwrap();
242
243 assert_eq!(detail.item.task.title, "detailed task");
244 assert_eq!(detail.project_name, "Detail Project");
245 assert_eq!(
246 detail
247 .notes
248 .iter()
249 .map(|note| (note.id.as_str(), note.body.as_str()))
250 .collect::<Vec<_>>(),
251 [("note-a", "first"), ("note-b", "second")]
252 );
253 assert_eq!(detail.dependencies.depends_on.len(), 1);
254 assert_eq!(detail.dependencies.depends_on[0].task.title, "blocker task");
255 assert_eq!(detail.conflicts.len(), 1);
256 assert_eq!(detail.conflicts[0].field, "title");
257 }
258}