From b660c8ba2e88389ffc2dd49e5ebebf65cdcee4ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 26 Aug 2026 09:25:25 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(core):=20one=20task,=20whole?= =?UTF-8?q?=20=E2=80=94=20detail,=20cycles=20refused,=20deletion=20that=20?= =?UTF-8?q?frees?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The detail screen's vocabulary and its read half. `DetailReads` is split out the way `BoardReads` is, so the round trips one task costs are tested by their effect: seven, whether the task carries nothing or twenty comments, twenty assignees, twenty activity lines and twenty tasks waiting on it. A task id from another workspace loads as `None`, not `Forbidden`: the asker is told nothing about a board they cannot see. `add_dependency` refuses an edge that would close a circle, and the walk runs inside the same transaction as the insert — two writers racing to add the two halves of a loop cannot both pass a check that was true when they read it. A cleared edge still counts: it is a link that is satisfied, not one that is gone. Deleting a task drops the edges it stood in; tasks left with nothing in front of them become unblocked, and that is written to their activity with no actor, because the rules engine will want to mail about it. `save_task` records one activity line per field that actually changed, decided from the row it is replacing. --- crates/dizey-core/src/detail.rs | 357 ++++++++++++++ crates/dizey-core/src/lib.rs | 4 + crates/dizey-core/src/store/mod.rs | 48 +- crates/dizey-core/src/store/turso_store.rs | 512 ++++++++++++++++++++- crates/dizey-core/tests/store.rs | 352 ++++++++++++++ 5 files changed, 1264 insertions(+), 9 deletions(-) create mode 100644 crates/dizey-core/src/detail.rs diff --git a/crates/dizey-core/src/detail.rs b/crates/dizey-core/src/detail.rs new file mode 100644 index 0000000..e5ecf1a --- /dev/null +++ b/crates/dizey-core/src/detail.rs @@ -0,0 +1,357 @@ +//! The task detail vocabulary: one task with everything hung off it — status, +//! assignees, deadline, description, both directions of its dependencies, its +//! comments and its activity trail. +//! +//! Like [`board`](crate::board), this module compiles to wasm: the browser +//! renders these exact types. + +use serde::{Deserialize, Serialize}; +use time::{Date, OffsetDateTime}; + +use crate::board::{Column, Person, day_label}; + +/// The stored task, plus the two ids the reader needs to know it is allowed to +/// see it. The description lives here rather than on +/// [`TaskRow`](crate::board::TaskRow) so a board sweep does not carry every +/// task's prose to the browser. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TaskFacts { + pub row: crate::board::TaskRow, + pub description: String, + pub board_id: String, + pub workspace_id: String, +} + +/// One end of a dependency, seen from the task being looked at. +/// +/// `cleared_at` is set when the blocking task finished; the row stays so the +/// history — and the "you can start now" rule — has something to read. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct DependencyEdge { + pub task_id: String, + pub task_key: String, + pub title: String, + pub cleared_at: Option, + pub done_at: Option, +} + +impl DependencyEdge { + pub fn is_cleared(&self) -> bool { + self.cleared_at.is_some() || self.done_at.is_some() + } + + /// The right-hand note on a `BLOCKED BY` row: `cleared Aug 16`, or what is + /// still in the way. + pub fn blocked_by_label(&self) -> String { + match (self.cleared_at, self.done_at) { + (Some(at), _) => format!("cleared {}", day_label(at.date())), + (None, Some(at)) => format!("done {}", day_label(at.date())), + (None, None) => "blocking this task".to_string(), + } + } + + /// The same note on a `BLOCKS` row. + pub fn blocks_label(&self) -> String { + if self.is_cleared() { + "no longer waiting".to_string() + } else { + "waiting on this task".to_string() + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Comment { + pub id: String, + pub author: Person, + pub at: OffsetDateTime, + pub body: String, +} + +/// What happened to a task. The kind is the machine's word for it; the sentence +/// the strip shows is built here rather than stored, so wording is not frozen +/// into the database. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ActivityKind { + Created, + Retitled, + Described, + DeadlineSet, + DeadlineCleared, + Assigned, + Unassigned, + Linked, + Unlinked, + Moved, + Unblocked, + Deleted, + /// A kind written by a newer version than the one reading it. The stored + /// detail is shown as-is rather than dropping the row. + Other(String), +} + +impl ActivityKind { + pub fn as_str(&self) -> &str { + match self { + ActivityKind::Created => "created", + ActivityKind::Retitled => "retitled", + ActivityKind::Described => "described", + ActivityKind::DeadlineSet => "deadline_set", + ActivityKind::DeadlineCleared => "deadline_cleared", + ActivityKind::Assigned => "assigned", + ActivityKind::Unassigned => "unassigned", + ActivityKind::Linked => "linked", + ActivityKind::Unlinked => "unlinked", + ActivityKind::Moved => "moved", + ActivityKind::Unblocked => "unblocked", + ActivityKind::Deleted => "deleted", + ActivityKind::Other(raw) => raw, + } + } + + pub fn parse(raw: &str) -> Self { + match raw { + "created" => ActivityKind::Created, + "retitled" => ActivityKind::Retitled, + "described" => ActivityKind::Described, + "deadline_set" => ActivityKind::DeadlineSet, + "deadline_cleared" => ActivityKind::DeadlineCleared, + "assigned" => ActivityKind::Assigned, + "unassigned" => ActivityKind::Unassigned, + "linked" => ActivityKind::Linked, + "unlinked" => ActivityKind::Unlinked, + "moved" => ActivityKind::Moved, + "unblocked" => ActivityKind::Unblocked, + "deleted" => ActivityKind::Deleted, + other => ActivityKind::Other(other.to_string()), + } + } +} + +/// One line of the activity strip. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ActivityEntry { + pub id: String, + /// Absent when the system did it rather than a person — the rules engine + /// clearing a dependency, for one. + pub actor: Option, + pub kind: ActivityKind, + /// The variable half: the deadline that was set, the key that was linked. + pub detail: String, + pub at: OffsetDateTime, +} + +impl ActivityEntry { + /// The sentence after the name: `created this task`, `set deadline Aug 21`. + pub fn sentence(&self) -> String { + let detail = self.detail.trim(); + match &self.kind { + ActivityKind::Created => "created this task".to_string(), + ActivityKind::Retitled => "renamed this task".to_string(), + ActivityKind::Described => "edited the description".to_string(), + ActivityKind::DeadlineSet => format!("set deadline {detail}"), + ActivityKind::DeadlineCleared => "removed the deadline".to_string(), + ActivityKind::Assigned => format!("assigned {detail}"), + ActivityKind::Unassigned => format!("unassigned {detail}"), + ActivityKind::Linked => format!("linked {detail}"), + ActivityKind::Unlinked => format!("unlinked {detail}"), + ActivityKind::Moved => format!("moved {detail}"), + ActivityKind::Unblocked => format!("unblocked this task — {detail}"), + ActivityKind::Deleted => "deleted this task".to_string(), + ActivityKind::Other(_) => detail.to_string(), + } + } + + /// `Aug 19 11:04`, the stamp the strip puts in front of the sentence. + pub fn moment(&self) -> String { + moment_label(self.at) + } +} + +/// `Aug 19 11:04`. Times are UTC, as everything stored is. +pub fn moment_label(at: OffsetDateTime) -> String { + format!( + "{} {:02}:{:02}", + day_label(at.date()), + at.hour(), + at.minute() + ) +} + +/// Everything one task detail needs, in one value. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TaskDetail { + pub id: String, + pub task_key: String, + pub title: String, + pub description: String, + /// The column the task is in — the artboard's STATUS field. + pub column: Column, + /// Every column on the board, so the status control has its options + /// without a second call. + pub columns: Vec, + pub deadline: Option, + pub done_at: Option, + pub assignees: Vec, + /// Who may be assigned: the workspace's writers. Viewers are never here — + /// a viewer cannot be given work. + pub assignable: Vec, + /// Tasks that must finish before this one can start. + pub blocked_by: Vec, + /// Tasks waiting on this one. + pub blocks: Vec, + pub comments: Vec, + pub activity: Vec, +} + +impl TaskDetail { + pub fn is_done(&self) -> bool { + self.done_at.is_some() + } + + /// Blocked means something unfinished is in front of it. + pub fn is_blocked(&self) -> bool { + !self.is_done() && self.blocked_by.iter().any(|edge| !edge.is_cleared()) + } + + pub fn is_overdue(&self, today: Date) -> bool { + match self.deadline { + Some(day) => !self.is_done() && day < today, + None => false, + } + } + + /// The DEADLINE field's text: `Aug 21 · overdue`, `Sep 12`, `no deadline`. + pub fn deadline_label(&self, today: Date) -> String { + match self.deadline { + Some(day) if !self.is_done() && day < today => { + format!("{} · overdue", day_label(day)) + } + Some(day) => day_label(day), + None => "no deadline".to_string(), + } + } + + /// `YYYY-MM-DD` for the date input, or an empty string. + pub fn deadline_input(&self) -> String { + self.deadline + .map(|day| { + format!( + "{:04}-{:02}-{:02}", + day.year(), + day.month() as u8, + day.day() + ) + }) + .unwrap_or_default() + } + + /// Who is not on this task yet — the picker's contents. + pub fn unassigned(&self) -> impl Iterator { + self.assignable + .iter() + .filter(|person| !self.assignees.iter().any(|on| on.id == person.id)) + } +} + +#[cfg(feature = "server")] +pub use reads::{DetailReads, load}; + +#[cfg(feature = "server")] +mod reads { + use async_trait::async_trait; + + use super::{ActivityEntry, Comment, DependencyEdge, TaskDetail, TaskFacts}; + use crate::board::{Column, Person}; + use crate::store::Result; + + /// One task's read half, split out the way [`BoardReads`](crate::BoardReads) + /// is, so a test can wrap it and count the round trips a detail costs. + /// + /// Every method here is one sweep of one thing. There is deliberately no + /// "the person who wrote this comment" call: authors arrive joined. + #[async_trait] + pub trait DetailReads: Send + Sync { + /// The task and the board it belongs to, or `None` if it is gone. + async fn task(&self, task_id: &str) -> Result>; + + async fn columns_for_board(&self, board_id: &str) -> Result>; + + async fn assignees_for_task(&self, task_id: &str) -> Result>; + + /// Everyone in the workspace who may be given work. + async fn assignable_people(&self, workspace_id: &str) -> Result>; + + /// Both directions at once: `(is_blocked_by, edge)`. `true` means the + /// other task blocks this one. + async fn dependencies_for_task(&self, task_id: &str) + -> Result>; + + async fn comments_for_task(&self, task_id: &str) -> Result>; + + async fn activity_for_task(&self, task_id: &str) -> Result>; + } + + /// Loads one task detail in seven queries — the task, the board's columns, + /// its assignees, the workspace's writers, both directions of its + /// dependencies, its comments and its activity. + /// + /// Seven, not seven-plus-one-per-comment: `a_task_detail_costs_seven_ + /// queries_whatever_it_carries` in `tests/store.rs` holds that line. + pub async fn load( + reads: &dyn DetailReads, + workspace_id: &str, + task_id: &str, + ) -> Result> { + let Some(facts) = reads.task(task_id).await? else { + return Ok(None); + }; + // A task id from another workspace is not found, not forbidden: the + // asker is told nothing about a board they cannot see. + if facts.workspace_id != workspace_id { + return Ok(None); + } + let task = facts.row; + let columns = reads.columns_for_board(&facts.board_id).await?; + let assignees = reads.assignees_for_task(task_id).await?; + let assignable = reads.assignable_people(workspace_id).await?; + let edges = reads.dependencies_for_task(task_id).await?; + let comments = reads.comments_for_task(task_id).await?; + let activity = reads.activity_for_task(task_id).await?; + + let Some(column) = columns + .iter() + .find(|column| column.id == task.column_id) + .cloned() + else { + return Ok(None); + }; + let mut blocked_by = Vec::new(); + let mut blocks = Vec::new(); + for (is_blocked_by, edge) in edges { + if is_blocked_by { + blocked_by.push(edge); + } else { + blocks.push(edge); + } + } + + Ok(Some(TaskDetail { + id: task.id, + task_key: task.task_key, + title: task.title, + description: facts.description, + column, + columns, + deadline: task.deadline, + done_at: task.done_at, + assignees, + assignable, + blocked_by, + blocks, + comments, + activity, + })) + } +} diff --git a/crates/dizey-core/src/lib.rs b/crates/dizey-core/src/lib.rs index 67710f0..7b66b7e 100644 --- a/crates/dizey-core/src/lib.rs +++ b/crates/dizey-core/src/lib.rs @@ -6,8 +6,10 @@ //! token minting. pub mod board; +pub mod detail; pub mod role; pub use board::{BoardView, Column, TaskCard}; +pub use detail::TaskDetail; pub use role::Role; #[cfg(feature = "server")] @@ -22,4 +24,6 @@ pub use accounts::{AccountError, Accounts}; #[cfg(feature = "server")] pub use board::{BoardReads, load as load_board}; #[cfg(feature = "server")] +pub use detail::{DetailReads, load as load_detail}; +#[cfg(feature = "server")] pub use store::{Store, StoreError, TursoStore}; diff --git a/crates/dizey-core/src/store/mod.rs b/crates/dizey-core/src/store/mod.rs index 7b99a88..8a09856 100644 --- a/crates/dizey-core/src/store/mod.rs +++ b/crates/dizey-core/src/store/mod.rs @@ -9,6 +9,7 @@ use serde::{Deserialize, Serialize}; use time::OffsetDateTime; use crate::board::{BoardReads, TaskRow}; +use crate::detail::{ActivityKind, DetailReads}; use crate::Role; pub mod turso_store; @@ -27,6 +28,9 @@ pub enum StoreError { Conflict(&'static str), #[error("stored value is not valid: {0}")] Corrupt(String), + /// The dependency asked for would put a task behind itself. + #[error("that link would make a circle")] + Cycle, } pub type Result = std::result::Result; @@ -156,7 +160,7 @@ pub struct NewTask<'a> { /// The board's reads live in [`BoardReads`], so the sweep-per-board shape is a /// trait a test can wrap and count. #[async_trait] -pub trait Store: BoardReads + 'static { +pub trait Store: BoardReads + DetailReads + 'static { // -- workspace --------------------------------------------------------- /// Claims an empty database: writes the workspace, its first account and @@ -312,6 +316,11 @@ pub trait Store: BoardReads + 'static { async fn unassign_task(&self, task_id: &str, user_id: &str) -> Result<()>; /// `blocked` cannot start until `blocking` is finished. + /// + /// Refuses with [`StoreError::Cycle`] if the edge would close a loop. The + /// check runs inside the same transaction as the insert, so two writers + /// racing to add the two halves of a circle cannot both pass a check that + /// was true when they read it. async fn add_dependency( &self, blocked_task_id: &str, @@ -326,6 +335,8 @@ pub trait Store: BoardReads + 'static { at: OffsetDateTime, ) -> Result<()>; + /// The author is the session's user, decided by the handler. There is no + /// author field on the form. async fn add_comment( &self, task_id: &str, @@ -333,4 +344,39 @@ pub trait Store: BoardReads + 'static { body: &str, at: OffsetDateTime, ) -> Result; + + /// Writes the title, description and deadline the detail screen saved, and + /// records one activity line per field that actually changed. + async fn save_task( + &self, + task_id: &str, + title: &str, + description: &str, + deadline: Option, + actor_id: &str, + at: OffsetDateTime, + ) -> Result<()>; + + /// Removes a task and every dependency edge it stood in. Tasks that were + /// waiting only on this one become unblocked, and that is recorded in + /// their activity — the rules engine will want to mail about it. + /// + /// Returns the ids of the tasks that were freed. + async fn delete_task( + &self, + task_id: &str, + actor_id: &str, + at: OffsetDateTime, + ) -> Result>; + + /// Appends one line to a task's activity trail. `actor_id` is `None` when + /// the system did it rather than a person. + async fn record_activity( + &self, + task_id: &str, + actor_id: Option<&str>, + kind: &ActivityKind, + detail: &str, + at: OffsetDateTime, + ) -> Result<()>; } diff --git a/crates/dizey-core/src/store/turso_store.rs b/crates/dizey-core/src/store/turso_store.rs index 0b668bd..d779730 100644 --- a/crates/dizey-core/src/store/turso_store.rs +++ b/crates/dizey-core/src/store/turso_store.rs @@ -17,6 +17,7 @@ use super::{ }; use crate::Role; use crate::board::{BoardMeta, BoardReads, Column, Person, TaskRow}; +use crate::detail::{ActivityEntry, ActivityKind, Comment, DependencyEdge, DetailReads, TaskFacts}; use time::Date; use time::format_description::BorrowedFormatItem; use time::macros::format_description; @@ -856,6 +857,18 @@ impl Store for TursoStore { ], ) .await?; + tx.execute( + "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ + VALUES (?1, ?2, ?3, ?4, '', ?5)", + params![ + Uuid::new_v4().to_string(), + id.clone(), + new.created_by, + ActivityKind::Created.as_str(), + now.clone() + ], + ) + .await?; Ok::<_, turso::Error>(Some((task_key, position))) } .await; @@ -913,19 +926,87 @@ impl Store for TursoStore { blocking_task_id: &str, at: OffsetDateTime, ) -> Result<()> { - // Re-adding a dependency that was cleared puts it back in force rather - // than leaving the cleared row to hide it. - self.conn - .execute( + if blocked_task_id == blocking_task_id { + return Err(StoreError::Cycle); + } + let stamp = stamp(at)?; + + let mut conn = self.tx_conn().await?; + // IMMEDIATE: the reachability read and the insert that invalidates it + // must not be interleaved with another writer's pair, or two adds each + // pass a check that was true when they read it and the pair closes a + // circle neither of them could see. + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + + let written = async { + // Every edge, cleared or not: a cleared edge is a link that is + // satisfied, not a link that is gone, and re-adding its other half + // would still be a circle on the screen. + let mut rows = tx + .query( + "SELECT d.blocked_task_id, d.blocking_task_id FROM task_dependency d \ + JOIN task b ON b.id = d.blocked_task_id \ + JOIN task k ON k.id = d.blocking_task_id \ + WHERE b.deleted_at IS NULL AND k.deleted_at IS NULL", + (), + ) + .await?; + // blocked -> [what blocks it] + let mut edges: std::collections::HashMap> = + std::collections::HashMap::new(); + while let Some(row) = rows.next().await? { + edges + .entry(row.get::(0)?) + .or_default() + .push(row.get::(1)?); + } + drop(rows); + + // Walking "what blocks it" from the proposed blocker: if that walk + // reaches the task being blocked, the new edge closes the loop. + let mut seen = std::collections::HashSet::new(); + let mut queue = std::collections::VecDeque::new(); + queue.push_back(blocking_task_id.to_string()); + while let Some(node) = queue.pop_front() { + if node == blocked_task_id { + return Ok(false); + } + if !seen.insert(node.clone()) { + continue; + } + for next in edges.get(&node).into_iter().flatten() { + queue.push_back(next.clone()); + } + } + + // Re-adding a dependency that was cleared puts it back in force + // rather than leaving the cleared row to hide it. + tx.execute( "INSERT INTO task_dependency (blocked_task_id, blocking_task_id, created_at) \ VALUES (?1, ?2, ?3) \ ON CONFLICT (blocked_task_id, blocking_task_id) \ DO UPDATE SET created_at = ?3, cleared_at = NULL", - params![blocked_task_id, blocking_task_id, stamp(at)?], + params![blocked_task_id, blocking_task_id, stamp.clone()], ) - .await - .map_err(backend)?; - Ok(()) + .await?; + Ok::<_, turso::Error>(true) + } + .await; + + match written { + Ok(true) => tx.commit().await.map_err(backend), + Ok(false) => { + let _ = tx.rollback().await; + Err(StoreError::Cycle) + } + Err(e) => { + let _ = tx.rollback().await; + Err(backend(e)) + } + } } async fn clear_dependency( @@ -963,6 +1044,421 @@ impl Store for TursoStore { .map_err(backend)?; Ok(id) } + + async fn save_task( + &self, + task_id: &str, + title: &str, + description: &str, + deadline: Option, + actor_id: &str, + at: OffsetDateTime, + ) -> Result<()> { + let deadline = deadline.map(day_text).transpose()?; + let stamp = stamp(at)?; + + let mut conn = self.tx_conn().await?; + // IMMEDIATE: the activity lines say what changed, so they are decided + // from the row this write is replacing and must see it unchanged. + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + + let written = async { + let mut rows = tx + .query( + "SELECT title, description, deadline FROM task \ + WHERE id = ?1 AND deleted_at IS NULL", + params![task_id], + ) + .await?; + let Some(row) = rows.next().await? else { + return Ok(false); + }; + let was_title = row.get::(0)?; + let was_description = row.get::(1)?; + let was_deadline = row.get::>(2)?; + drop(rows); + + tx.execute( + "UPDATE task SET title = ?2, description = ?3, deadline = ?4, updated_at = ?5 \ + WHERE id = ?1", + params![task_id, title, description, deadline.clone(), stamp.clone()], + ) + .await?; + + let mut lines: Vec<(&'static str, String)> = Vec::new(); + if was_title != title { + lines.push((ActivityKind::Retitled.as_str(), title.to_string())); + } + if was_description != description { + lines.push((ActivityKind::Described.as_str(), String::new())); + } + if was_deadline != deadline { + match &deadline { + Some(day) => lines.push((ActivityKind::DeadlineSet.as_str(), day.clone())), + None => lines.push((ActivityKind::DeadlineCleared.as_str(), String::new())), + } + } + for (kind, detail) in lines { + tx.execute( + "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![ + Uuid::new_v4().to_string(), + task_id, + actor_id, + kind, + detail, + stamp.clone() + ], + ) + .await?; + } + Ok::<_, turso::Error>(true) + } + .await; + + match written { + Ok(true) => tx.commit().await.map_err(backend), + Ok(false) => { + let _ = tx.rollback().await; + Err(StoreError::NotFound) + } + Err(e) => { + let _ = tx.rollback().await; + Err(backend(e)) + } + } + } + + async fn delete_task( + &self, + task_id: &str, + actor_id: &str, + at: OffsetDateTime, + ) -> Result> { + let stamp = stamp(at)?; + + let mut conn = self.tx_conn().await?; + // IMMEDIATE: whether a task is freed depends on the edges that are + // left after this one's are dropped. Reading them outside the write + // would let a concurrent link make the answer wrong. + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + + let written = async { + let mut rows = tx + .query( + "SELECT task_key FROM task WHERE id = ?1 AND deleted_at IS NULL", + params![task_id], + ) + .await?; + let Some(row) = rows.next().await? else { + return Ok(None); + }; + let task_key = row.get::(0)?; + drop(rows); + + // Everyone this task was standing in front of, before the edges go. + let mut rows = tx + .query( + "SELECT d.blocked_task_id FROM task_dependency d \ + JOIN task t ON t.id = d.blocked_task_id \ + WHERE d.blocking_task_id = ?1 AND d.cleared_at IS NULL \ + AND t.deleted_at IS NULL", + params![task_id], + ) + .await?; + let mut waiting = Vec::new(); + while let Some(row) = rows.next().await? { + waiting.push(row.get::(0)?); + } + drop(rows); + + tx.execute( + "DELETE FROM task_dependency \ + WHERE blocked_task_id = ?1 OR blocking_task_id = ?1", + params![task_id], + ) + .await?; + tx.execute( + "UPDATE task SET deleted_at = ?2, updated_at = ?2 WHERE id = ?1", + params![task_id, stamp.clone()], + ) + .await?; + tx.execute( + "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ + VALUES (?1, ?2, ?3, ?4, '', ?5)", + params![ + Uuid::new_v4().to_string(), + task_id, + actor_id, + ActivityKind::Deleted.as_str(), + stamp.clone() + ], + ) + .await?; + + // Freed only if nothing else is still in front of them. + let mut freed = Vec::new(); + for blocked in waiting { + let mut rows = tx + .query( + "SELECT COUNT(*) FROM task_dependency d \ + JOIN task t ON t.id = d.blocking_task_id \ + WHERE d.blocked_task_id = ?1 AND d.cleared_at IS NULL \ + AND t.deleted_at IS NULL", + params![blocked.clone()], + ) + .await?; + let left = match rows.next().await? { + Some(row) => row.get::(0)?, + None => 0, + }; + drop(rows); + if left > 0 { + continue; + } + tx.execute( + "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ + VALUES (?1, ?2, NULL, ?3, ?4, ?5)", + params![ + Uuid::new_v4().to_string(), + blocked.clone(), + ActivityKind::Unblocked.as_str(), + format!("{task_key} was deleted"), + stamp.clone() + ], + ) + .await?; + freed.push(blocked); + } + Ok::<_, turso::Error>(Some(freed)) + } + .await; + + match written { + Ok(Some(freed)) => { + tx.commit().await.map_err(backend)?; + Ok(freed) + } + Ok(None) => { + let _ = tx.rollback().await; + Err(StoreError::NotFound) + } + Err(e) => { + let _ = tx.rollback().await; + Err(backend(e)) + } + } + } + + async fn record_activity( + &self, + task_id: &str, + actor_id: Option<&str>, + kind: &ActivityKind, + detail: &str, + at: OffsetDateTime, + ) -> Result<()> { + self.conn + .execute( + "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![ + Uuid::new_v4().to_string(), + task_id, + actor_id, + kind.as_str(), + detail, + stamp(at)? + ], + ) + .await + .map_err(backend)?; + Ok(()) + } +} + +#[async_trait] +impl DetailReads for TursoStore { + async fn task(&self, task_id: &str) -> Result> { + let row = self + .one_row( + "SELECT t.id, t.task_key, t.title, t.column_id, t.deadline, t.position, \ + t.done_at, t.description, t.board_id, b.workspace_id \ + FROM task t JOIN board b ON b.id = t.board_id \ + WHERE t.id = ?1 AND t.deleted_at IS NULL", + params![task_id], + ) + .await?; + let Some(row) = row else { return Ok(None) }; + Ok(Some(TaskFacts { + row: TaskRow { + id: text(&row, 0)?, + task_key: text(&row, 1)?, + title: text(&row, 2)?, + column_id: text(&row, 3)?, + deadline: opt_day(&row, 4)?, + position: row.get::(5).map_err(backend)?, + done_at: opt_stamp(&row, 6)?, + }, + description: text(&row, 7)?, + board_id: text(&row, 8)?, + workspace_id: text(&row, 9)?, + })) + } + + async fn columns_for_board(&self, board_id: &str) -> Result> { + BoardReads::columns(self, board_id).await + } + + async fn assignees_for_task(&self, task_id: &str) -> Result> { + let mut rows = self + .conn + .query( + "SELECT u.id, u.display_name, u.photo_path FROM task_assignee a \ + JOIN user u ON u.id = a.user_id \ + WHERE a.task_id = ?1 ORDER BY u.display_name", + params![task_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(Person { + id: text(&row, 0)?, + display_name: text(&row, 1)?, + photo_path: opt_text(&row, 2)?, + }); + } + Ok(out) + } + + async fn assignable_people(&self, workspace_id: &str) -> Result> { + // Id, name and photo only: the picker shows no addresses and no roles, + // so neither leaves the server for this screen. + let mut rows = self + .conn + .query( + "SELECT id, display_name, photo_path FROM user \ + WHERE workspace_id = ?1 AND role <> ?2 ORDER BY display_name", + params![workspace_id, Role::Viewer.as_str()], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(Person { + id: text(&row, 0)?, + display_name: text(&row, 1)?, + photo_path: opt_text(&row, 2)?, + }); + } + Ok(out) + } + + async fn dependencies_for_task( + &self, + task_id: &str, + ) -> Result> { + // Both directions in one round trip: the leading column says which. + let mut rows = self + .conn + .query( + "SELECT 1, t.id, t.task_key, t.title, d.cleared_at, t.done_at \ + FROM task_dependency d JOIN task t ON t.id = d.blocking_task_id \ + WHERE d.blocked_task_id = ?1 AND t.deleted_at IS NULL \ + UNION ALL \ + SELECT 0, t.id, t.task_key, t.title, d.cleared_at, t.done_at \ + FROM task_dependency d JOIN task t ON t.id = d.blocked_task_id \ + WHERE d.blocking_task_id = ?2 AND t.deleted_at IS NULL", + params![task_id, task_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + let is_blocked_by = row.get::(0).map_err(backend)? != 0; + out.push(( + is_blocked_by, + DependencyEdge { + task_id: text(&row, 1)?, + task_key: text(&row, 2)?, + title: text(&row, 3)?, + cleared_at: opt_stamp(&row, 4)?, + done_at: opt_stamp(&row, 5)?, + }, + )); + } + Ok(out) + } + + async fn comments_for_task(&self, task_id: &str) -> Result> { + let mut rows = self + .conn + .query( + "SELECT c.id, c.body, c.created_at, u.id, u.display_name, u.photo_path \ + FROM comment c JOIN user u ON u.id = c.author_id \ + WHERE c.task_id = ?1 ORDER BY c.created_at, c.rowid", + params![task_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(Comment { + id: text(&row, 0)?, + body: text(&row, 1)?, + at: parse_stamp(&text(&row, 2)?)?, + author: Person { + id: text(&row, 3)?, + display_name: text(&row, 4)?, + photo_path: opt_text(&row, 5)?, + }, + }); + } + Ok(out) + } + + async fn activity_for_task(&self, task_id: &str) -> Result> { + // LEFT JOIN: a line the system wrote has no actor, and dropping it + // would hide exactly the events the rules engine causes. + let mut rows = self + .conn + .query( + "SELECT a.id, a.kind, a.detail, a.created_at, u.id, u.display_name, \ + u.photo_path \ + FROM activity a LEFT JOIN user u ON u.id = a.actor_id \ + WHERE a.task_id = ?1 ORDER BY a.created_at, a.rowid", + params![task_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + let actor = match opt_text(&row, 4)? { + Some(id) => Some(Person { + id, + display_name: text(&row, 5)?, + photo_path: opt_text(&row, 6)?, + }), + None => None, + }; + out.push(ActivityEntry { + id: text(&row, 0)?, + kind: ActivityKind::parse(&text(&row, 1)?), + detail: text(&row, 2)?, + at: parse_stamp(&text(&row, 3)?)?, + actor, + }); + } + Ok(out) + } } #[async_trait] diff --git a/crates/dizey-core/tests/store.rs b/crates/dizey-core/tests/store.rs index 29b9050..4ea099d 100644 --- a/crates/dizey-core/tests/store.rs +++ b/crates/dizey-core/tests/store.rs @@ -1542,3 +1542,355 @@ fn initials_fall_back_to_two_letters() { assert_eq!(person("Ada").initials(), "A"); assert_eq!(person(" ").initials(), "?"); } + +// -- task detail ------------------------------------------------------------ + +use dizey_core::detail::{ + ActivityEntry, ActivityKind, Comment, DependencyEdge, DetailReads, TaskFacts, + load as load_detail, +}; + +/// The same trick as [`CountingReads`], for the detail screen: the round trips +/// one task costs must not follow how much it carries. +struct CountingDetail<'a> { + inner: &'a TursoStore, + calls: AtomicUsize, +} + +impl<'a> CountingDetail<'a> { + fn new(inner: &'a TursoStore) -> Self { + Self { + inner, + calls: AtomicUsize::new(0), + } + } + + fn count(&self) -> usize { + self.calls.load(Ordering::Relaxed) + } + + fn tick(&self) { + self.calls.fetch_add(1, Ordering::Relaxed); + } +} + +#[async_trait::async_trait] +impl DetailReads for CountingDetail<'_> { + async fn task(&self, task_id: &str) -> Result, StoreError> { + self.tick(); + self.inner.task(task_id).await + } + + async fn columns_for_board( + &self, + board_id: &str, + ) -> Result, StoreError> { + self.tick(); + self.inner.columns_for_board(board_id).await + } + + async fn assignees_for_task(&self, task_id: &str) -> Result, StoreError> { + self.tick(); + self.inner.assignees_for_task(task_id).await + } + + async fn assignable_people(&self, workspace_id: &str) -> Result, StoreError> { + self.tick(); + self.inner.assignable_people(workspace_id).await + } + + async fn dependencies_for_task( + &self, + task_id: &str, + ) -> Result, StoreError> { + self.tick(); + self.inner.dependencies_for_task(task_id).await + } + + async fn comments_for_task(&self, task_id: &str) -> Result, StoreError> { + self.tick(); + self.inner.comments_for_task(task_id).await + } + + async fn activity_for_task(&self, task_id: &str) -> Result, StoreError> { + self.tick(); + self.inner.activity_for_task(task_id).await + } +} + +#[tokio::test] +async fn a_task_detail_carries_both_directions_of_its_dependencies() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + + let middle = add_task(store, &workspace, "Backlog", "middle", None, &admin).await; + let before = add_task(store, &workspace, "Backlog", "before", None, &admin).await; + let after = add_task(store, &workspace, "Backlog", "after", None, &admin).await; + store.add_dependency(&middle, &before, now).await.unwrap(); + store.add_dependency(&after, &middle, now).await.unwrap(); + + let detail = load_detail(store, &workspace, &middle) + .await + .unwrap() + .expect("the task is in this workspace"); + assert_eq!(detail.title, "middle"); + assert_eq!(detail.column.name, "Backlog"); + assert_eq!(detail.columns.len(), 4, "every column, for the picker"); + let blocked_by: Vec<&str> = detail + .blocked_by + .iter() + .map(|edge| edge.title.as_str()) + .collect(); + let blocks: Vec<&str> = detail.blocks.iter().map(|e| e.title.as_str()).collect(); + assert_eq!(blocked_by, ["before"]); + assert_eq!(blocks, ["after"]); + assert!(detail.is_blocked()); + assert_eq!(detail.blocked_by[0].blocked_by_label(), "blocking this task"); + assert_eq!(detail.blocks[0].blocks_label(), "waiting on this task"); +} + +#[tokio::test] +async fn a_viewer_is_never_offered_as_an_assignee() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let quiet = store + .create_user(NewUser { + workspace_id: workspace.clone(), + email: "quiet@dizey.sh".into(), + display_name: "Quiet Reader".into(), + role: Role::Viewer, + }) + .await + .unwrap(); + let task = add_task(store, &workspace, "Backlog", "a task", None, &admin).await; + + let detail = load_detail(store, &workspace, &task).await.unwrap().unwrap(); + assert!( + !detail.assignable.iter().any(|p| p.id == quiet.id), + "a viewer cannot be given work, so the picker never lists one" + ); + assert!(detail.assignable.iter().any(|p| p.id == admin)); +} + +#[tokio::test] +async fn a_task_in_another_workspace_is_not_found_rather_than_forbidden() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let task = add_task(store, &workspace, "Backlog", "a task", None, &admin).await; + + // Asking as a workspace that does not hold it says nothing about whether + // the id is real. + let answer = load_detail(store, "some-other-workspace", &task) + .await + .unwrap(); + assert!(answer.is_none()); +} + +#[tokio::test] +async fn a_dependency_that_would_close_a_circle_is_refused() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + + let a = add_task(store, &workspace, "Backlog", "a", None, &admin).await; + let b = add_task(store, &workspace, "Backlog", "b", None, &admin).await; + let c = add_task(store, &workspace, "Backlog", "c", None, &admin).await; + + // a waits on b, b waits on c. Now ask for c to wait on a: three nodes, not + // a self-edge, and the loop only shows up on the second hop. + store.add_dependency(&a, &b, now).await.unwrap(); + store.add_dependency(&b, &c, now).await.unwrap(); + assert!(matches!( + store.add_dependency(&c, &a, now).await, + Err(StoreError::Cycle) + )); + assert!(matches!( + store.add_dependency(&a, &a, now).await, + Err(StoreError::Cycle) + )); + + // The refusal wrote nothing. + let detail = load_detail(store, &workspace, &c).await.unwrap().unwrap(); + assert!(detail.blocked_by.is_empty()); +} + +#[tokio::test] +async fn a_cleared_dependency_still_counts_as_a_circle() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + + let a = add_task(store, &workspace, "Backlog", "a", None, &admin).await; + let b = add_task(store, &workspace, "Backlog", "b", None, &admin).await; + store.add_dependency(&a, &b, now).await.unwrap(); + store.clear_dependency(&a, &b, now).await.unwrap(); + + // A cleared edge is a link that is satisfied, not a link that is gone: the + // pair would still draw a circle on the screen. + assert!(matches!( + store.add_dependency(&b, &a, now).await, + Err(StoreError::Cycle) + )); +} + +#[tokio::test] +async fn deleting_a_task_frees_what_was_waiting_on_it() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + + let blocking = add_task(store, &workspace, "Backlog", "blocking", None, &admin).await; + let other = add_task(store, &workspace, "Backlog", "other", None, &admin).await; + let freed = add_task(store, &workspace, "Backlog", "freed", None, &admin).await; + let still_stuck = add_task(store, &workspace, "Backlog", "stuck", None, &admin).await; + store.add_dependency(&freed, &blocking, now).await.unwrap(); + store + .add_dependency(&still_stuck, &blocking, now) + .await + .unwrap(); + store.add_dependency(&still_stuck, &other, now).await.unwrap(); + + let unblocked = store.delete_task(&blocking, &admin, now).await.unwrap(); + assert_eq!(unblocked, vec![freed.clone()], "only the one with nothing else in front of it"); + + // The deleted task is gone from the board and from the edges it stood in. + let board = board_of(store, &workspace).await; + assert!(!board + .columns + .iter() + .flat_map(|column| column.cards.iter()) + .any(|card| card.id == blocking)); + let freed_detail = load_detail(store, &workspace, &freed).await.unwrap().unwrap(); + assert!(freed_detail.blocked_by.is_empty()); + assert!(!freed_detail.is_blocked()); + + // And the freeing is a recorded event, because the rules engine will want + // to mail about it. + let unblocked_line = freed_detail + .activity + .iter() + .find(|entry| entry.kind == ActivityKind::Unblocked) + .expect("the freeing is on the record"); + assert!(unblocked_line.actor.is_none(), "the system did this, not a person"); + assert!(unblocked_line.sentence().starts_with("unblocked this task")); + + let stuck_detail = load_detail(store, &workspace, &still_stuck) + .await + .unwrap() + .unwrap(); + assert!(stuck_detail.is_blocked(), "something else is still in front of it"); + assert!(!stuck_detail + .activity + .iter() + .any(|entry| entry.kind == ActivityKind::Unblocked)); + + // A second delete finds nothing to delete. + assert!(matches!( + store.delete_task(&blocking, &admin, now).await, + Err(StoreError::NotFound) + )); +} + +#[tokio::test] +async fn saving_a_task_records_only_what_changed() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let task = add_task(store, &workspace, "Backlog", "first title", None, &admin).await; + + store + .save_task( + &task, + "first title", + "", + None, + &admin, + OffsetDateTime::now_utc(), + ) + .await + .unwrap(); + let detail = load_detail(store, &workspace, &task).await.unwrap().unwrap(); + let kinds: Vec<&ActivityKind> = detail.activity.iter().map(|e| &e.kind).collect(); + assert_eq!(kinds, [&ActivityKind::Created], "a save that changed nothing says nothing"); + + store + .save_task( + &task, + "second title", + "some prose", + Some(date!(2026 - 09 - 12)), + &admin, + OffsetDateTime::now_utc(), + ) + .await + .unwrap(); + let detail = load_detail(store, &workspace, &task).await.unwrap().unwrap(); + assert_eq!(detail.title, "second title"); + assert_eq!(detail.description, "some prose"); + assert_eq!(detail.deadline_input(), "2026-09-12"); + let kinds: Vec<&ActivityKind> = detail.activity.iter().map(|e| &e.kind).collect(); + assert_eq!( + kinds, + [ + &ActivityKind::Created, + &ActivityKind::Retitled, + &ActivityKind::Described, + &ActivityKind::DeadlineSet + ] + ); +} + +#[tokio::test] +async fn a_task_detail_costs_seven_queries_whatever_it_carries() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + + let bare = add_task(store, &workspace, "Backlog", "bare", None, &admin).await; + let counted = CountingDetail::new(store); + load_detail(&counted, &workspace, &bare).await.unwrap(); + assert_eq!(counted.count(), 7, "a task with nothing hung off it"); + + // Twenty comments, twenty activity lines, twenty people who could be + // assigned and twenty tasks on the other end of a dependency — the four + // things a naive detail query fans out on. + let heavy = add_task(store, &workspace, "Backlog", "heavy", None, &admin).await; + for n in 0..20 { + let person = store + .create_user(NewUser { + workspace_id: workspace.clone(), + email: format!("member{n}@dizey.sh"), + display_name: format!("Member {n}"), + role: Role::Member, + }) + .await + .unwrap(); + store.assign_task(&heavy, &person.id).await.unwrap(); + store + .add_comment(&heavy, &person.id, "a note", now) + .await + .unwrap(); + store + .record_activity(&heavy, Some(&person.id), &ActivityKind::Moved, "to Review", now) + .await + .unwrap(); + let neighbour = add_task(store, &workspace, "Backlog", &format!("n{n}"), None, &admin).await; + store.add_dependency(&neighbour, &heavy, now).await.unwrap(); + } + + let counted = CountingDetail::new(store); + let detail = load_detail(&counted, &workspace, &heavy) + .await + .unwrap() + .unwrap(); + assert_eq!(detail.comments.len(), 20); + assert_eq!(detail.assignees.len(), 20); + assert_eq!(detail.blocks.len(), 20); + // Twenty moves plus the line create_task wrote. + assert_eq!(detail.activity.len(), 21); + assert_eq!( + counted.count(), + 7, + "the round trips a detail costs must not follow what it carries" + ); +}