diff --git a/crates/dizey-core/Cargo.toml b/crates/dizey-core/Cargo.toml index 4874fc3..02703c1 100644 --- a/crates/dizey-core/Cargo.toml +++ b/crates/dizey-core/Cargo.toml @@ -35,5 +35,6 @@ turso = { workspace = true, optional = true } uuid = { workspace = true, optional = true } [dev-dependencies] +async-trait = "0.1.92" serde_json.workspace = true tokio = { workspace = true } diff --git a/crates/dizey-core/src/board.rs b/crates/dizey-core/src/board.rs new file mode 100644 index 0000000..80fcd7e --- /dev/null +++ b/crates/dizey-core/src/board.rs @@ -0,0 +1,343 @@ +//! The board vocabulary: columns, cards and the numbers the Main artboard puts +//! in its chrome. +//! +//! This module is deliberately free of the `server` feature: the browser bundle +//! renders these exact types, so a card means the same thing on both sides and +//! nothing has to be re-derived from a wire format. + +use serde::{Deserialize, Serialize}; +use time::{Date, Month, OffsetDateTime}; + +/// A board and the key prefix its tasks carry (`DZ-14`). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct BoardMeta { + pub id: String, + pub name: String, + pub task_prefix: String, +} + +/// A column. `is_done` is what turns a card into the finished, greyed state +/// with a "done Aug 14" stamp rather than a deadline chip. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Column { + pub id: String, + pub name: String, + pub position: i64, + pub is_done: bool, +} + +/// One task as the store holds it, before assignees, comments and dependencies +/// are hung off it. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TaskRow { + pub id: String, + pub task_key: String, + pub title: String, + pub column_id: String, + pub deadline: Option, + pub position: f64, + pub done_at: Option, +} + +/// Whoever a card can point at. The address is not here: a board card never +/// shows one, so it never leaves the server for this screen. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Person { + pub id: String, + pub display_name: String, + pub photo_path: Option, +} + +impl Person { + /// The two-letter fallback the artboard uses when there is no photo (`MD`). + pub fn initials(&self) -> String { + let mut letters = self + .display_name + .split_whitespace() + .filter_map(|word| word.chars().next()) + .filter(|c| c.is_alphanumeric()); + let first = letters.next(); + let second = letters.next(); + match (first, second) { + (Some(a), Some(b)) => format!("{a}{b}").to_uppercase(), + (Some(a), None) => a.to_uppercase().to_string(), + _ => "?".to_string(), + } + } +} + +/// A card, assembled. Dependencies carry the *keys* of the tasks on the other +/// end, because that is what the card shows and it saves the UI a second lookup. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TaskCard { + pub id: String, + pub task_key: String, + pub title: String, + pub column_id: String, + pub deadline: Option, + pub done_at: Option, + pub position: f64, + pub assignees: Vec, + pub comment_count: u32, + /// Keys of the tasks that must finish before this one can start. + pub blocked_by: Vec, + /// Keys of the tasks waiting on this one. + pub blocks: Vec, +} + +impl TaskCard { + pub fn is_done(&self) -> bool { + self.done_at.is_some() + } + + /// Blocked means something unfinished is in front of it. A finished task is + /// never counted as blocked, whatever it still points at. + pub fn is_blocked(&self) -> bool { + !self.is_done() && !self.blocked_by.is_empty() + } + + /// Past its deadline and not finished. A deadline of today is not overdue. + pub fn is_overdue(&self, today: Date) -> bool { + match self.deadline { + Some(day) => !self.is_done() && day < today, + None => false, + } + } + + pub fn is_assigned_to(&self, user_id: &str) -> bool { + self.assignees.iter().any(|person| person.id == user_id) + } + + /// The chip the card shows where a deadline would go: `Sep 12`, + /// `Aug 21 · overdue`, `done Aug 14` or `no deadline`. + pub fn deadline_label(&self, today: Date) -> String { + if let Some(done) = self.done_at { + return format!("done {}", day_label(done.date())); + } + match self.deadline { + Some(day) if day < today => format!("{} · overdue", day_label(day)), + Some(day) => day_label(day), + None => "no deadline".to_string(), + } + } +} + +/// A column with its cards already in it. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ColumnView { + pub column: Column, + pub cards: Vec, +} + +/// Everything one board screen needs, in one value. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct BoardView { + pub board: BoardMeta, + pub columns: Vec, +} + +impl BoardView { + pub fn cards(&self) -> impl Iterator { + self.columns.iter().flat_map(|column| column.cards.iter()) + } + + pub fn task_count(&self) -> usize { + self.cards().count() + } + + pub fn is_empty(&self) -> bool { + self.task_count() == 0 + } + + /// The `1 overdue` chip in the filter bar. + pub fn overdue_count(&self, today: Date) -> usize { + self.cards().filter(|card| card.is_overdue(today)).count() + } + + /// The `2 blocked` chip beside it. + pub fn blocked_count(&self) -> usize { + self.cards().filter(|card| card.is_blocked()).count() + } +} + +/// `Sep 12` — the card chips are day-and-month, never a year. +pub fn day_label(day: Date) -> String { + let month = match day.month() { + Month::January => "Jan", + Month::February => "Feb", + Month::March => "Mar", + Month::April => "Apr", + Month::May => "May", + Month::June => "Jun", + Month::July => "Jul", + Month::August => "Aug", + Month::September => "Sep", + Month::October => "Oct", + Month::November => "Nov", + Month::December => "Dec", + }; + format!("{month} {:02}", day.day()) +} + +/// Builds the board from six flat sweeps. +/// +/// Every input is the whole board's worth of one thing, so the caller makes a +/// fixed number of queries no matter how many tasks there are — see +/// [`load`](crate::board::load). The joining happens here, in Rust. +pub fn assemble( + board: BoardMeta, + mut columns: Vec, + tasks: Vec, + assignees: Vec<(String, Person)>, + comment_counts: Vec<(String, u32)>, + dependencies: Vec<(String, String)>, +) -> BoardView { + use std::collections::HashMap; + + let key_of: HashMap<&str, &str> = tasks + .iter() + .map(|task| (task.id.as_str(), task.task_key.as_str())) + .collect(); + + let mut people: HashMap> = HashMap::new(); + for (task_id, person) in assignees { + people.entry(task_id).or_default().push(person); + } + let counts: HashMap = comment_counts.into_iter().collect(); + + let finished: HashMap<&str, bool> = tasks + .iter() + .map(|task| (task.id.as_str(), task.done_at.is_some())) + .collect(); + + let mut blocked_by: HashMap> = HashMap::new(); + let mut blocks: HashMap> = HashMap::new(); + for (blocked, blocking) in &dependencies { + // A dependency on a task from another board would have no key here; it + // is dropped rather than shown as a dangling chip. A dependency whose + // other end is finished is dropped too: nothing is waiting on a task + // that is done, whatever the row still says. + let done = |id: &str| finished.get(id).copied().unwrap_or(false); + if let Some(key) = key_of.get(blocking.as_str()) + && !done(blocking) + { + blocked_by + .entry(blocked.clone()) + .or_default() + .push((*key).to_string()); + } + if let Some(key) = key_of.get(blocked.as_str()) + && !done(blocked) + { + blocks + .entry(blocking.clone()) + .or_default() + .push((*key).to_string()); + } + } + + let mut cards: HashMap> = HashMap::new(); + for task in tasks { + let card = TaskCard { + comment_count: counts.get(&task.id).copied().unwrap_or(0), + assignees: people.remove(&task.id).unwrap_or_default(), + blocked_by: blocked_by.remove(&task.id).unwrap_or_default(), + blocks: blocks.remove(&task.id).unwrap_or_default(), + id: task.id, + task_key: task.task_key, + title: task.title, + deadline: task.deadline, + done_at: task.done_at, + position: task.position, + column_id: task.column_id, + }; + cards.entry(card.column_id.clone()).or_default().push(card); + } + + columns.sort_by_key(|column| column.position); + let columns = columns + .into_iter() + .map(|column| { + let mut cards = cards.remove(&column.id).unwrap_or_default(); + sort_cards(&mut cards); + ColumnView { column, cards } + }) + .collect(); + + BoardView { board, columns } +} + +/// The board's default order, which the artboard names "Sort: deadline": +/// soonest deadline first, cards without one after them, ties broken by the +/// hand-set position so a column never reshuffles on its own. +fn sort_cards(cards: &mut [TaskCard]) { + cards.sort_by(|a, b| { + (a.deadline.is_none(), a.deadline) + .cmp(&(b.deadline.is_none(), b.deadline)) + .then(a.position.total_cmp(&b.position)) + .then_with(|| a.task_key.cmp(&b.task_key)) + }); +} + +#[cfg(feature = "server")] +pub use reads::{BoardReads, load}; + +#[cfg(feature = "server")] +mod reads { + use async_trait::async_trait; + + use super::{BoardMeta, BoardView, Column, Person, TaskRow, assemble}; + use crate::store::Result; + + /// The board's read half, split out from [`Store`](crate::Store) so a test + /// can wrap it and count the round trips a board costs. + /// + /// Every method sweeps the whole board. There is deliberately no + /// "assignees for this task" here: one query per card is how a board with + /// fourteen tasks becomes sixty round trips against a single-writer file. + #[async_trait] + pub trait BoardReads: Send + Sync { + /// The workspace's board. There is one today; the type is ready for + /// more. + async fn board(&self, workspace_id: &str) -> Result>; + + async fn columns(&self, board_id: &str) -> Result>; + + /// Live tasks, deleted ones left out. + async fn tasks_for_board(&self, board_id: &str) -> Result>; + + /// `(task id, person)` for every assignment on the board. + async fn assignees_for_board(&self, board_id: &str) -> Result>; + + /// `(task id, comments)`, tasks with none left out. + async fn comment_counts_for_board(&self, board_id: &str) -> Result>; + + /// `(blocked task id, blocking task id)` for every dependency still in + /// force. + async fn dependencies_for_board(&self, board_id: &str) -> Result>; + } + + /// Loads a whole board in six queries — one for the board and one sweep per + /// thing a card carries — and joins them in Rust. + /// + /// The count does not move with the number of tasks; `board_costs_the_same_ + /// six_queries_at_any_size` in `tests/store.rs` holds that line. + pub async fn load(reads: &dyn BoardReads, workspace_id: &str) -> Result> { + let Some(board) = reads.board(workspace_id).await? else { + return Ok(None); + }; + let columns = reads.columns(&board.id).await?; + let tasks = reads.tasks_for_board(&board.id).await?; + let assignees = reads.assignees_for_board(&board.id).await?; + let comment_counts = reads.comment_counts_for_board(&board.id).await?; + let dependencies = reads.dependencies_for_board(&board.id).await?; + Ok(Some(assemble( + board, + columns, + tasks, + assignees, + comment_counts, + dependencies, + ))) + } +} diff --git a/crates/dizey-core/src/lib.rs b/crates/dizey-core/src/lib.rs index 9ef7dd1..67710f0 100644 --- a/crates/dizey-core/src/lib.rs +++ b/crates/dizey-core/src/lib.rs @@ -5,7 +5,9 @@ //! that must never reach the browser: the store, the password hashing and the //! token minting. +pub mod board; pub mod role; +pub use board::{BoardView, Column, TaskCard}; pub use role::Role; #[cfg(feature = "server")] @@ -18,4 +20,6 @@ pub mod store; #[cfg(feature = "server")] pub use accounts::{AccountError, Accounts}; #[cfg(feature = "server")] +pub use board::{BoardReads, load as load_board}; +#[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 b081fe8..7b99a88 100644 --- a/crates/dizey-core/src/store/mod.rs +++ b/crates/dizey-core/src/store/mod.rs @@ -8,6 +8,7 @@ use async_trait::async_trait; use serde::{Deserialize, Serialize}; use time::OffsetDateTime; +use crate::board::{BoardReads, TaskRow}; use crate::Role; pub mod turso_store; @@ -139,9 +140,23 @@ impl Session { } } +/// A task as it is written. The key (`DZ-14`) is not here: the store hands it +/// out from the board's counter, so two tasks created at once cannot collide. +pub struct NewTask<'a> { + pub board_id: &'a str, + pub column_id: &'a str, + pub title: &'a str, + pub description: &'a str, + pub deadline: Option, + pub created_by: &'a str, +} + /// The storage boundary. Dyn-safe on purpose: handlers hold `Arc`. +/// +/// 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: Send + Sync + 'static { +pub trait Store: BoardReads + 'static { // -- workspace --------------------------------------------------------- /// Claims an empty database: writes the workspace, its first account and @@ -275,4 +290,47 @@ pub trait Store: Send + Sync + 'static { /// Drops attempt rows older than `before`, so the ledger does not grow /// without bound. async fn prune_auth_attempts(&self, before: OffsetDateTime) -> Result; + + // -- board ------------------------------------------------------------- + + /// Adds a column to the end of a board. + async fn create_column( + &self, + board_id: &str, + name: &str, + position: i64, + is_done: bool, + ) -> Result; + + /// Writes a task and hands it the next key on its board, in one + /// transaction, so two writers cannot both take `DZ-14`. + async fn create_task(&self, new: NewTask<'_>) -> Result; + + /// Idempotent: assigning someone twice is not an error. + async fn assign_task(&self, task_id: &str, user_id: &str) -> Result<()>; + + async fn unassign_task(&self, task_id: &str, user_id: &str) -> Result<()>; + + /// `blocked` cannot start until `blocking` is finished. + async fn add_dependency( + &self, + blocked_task_id: &str, + blocking_task_id: &str, + at: OffsetDateTime, + ) -> Result<()>; + + async fn clear_dependency( + &self, + blocked_task_id: &str, + blocking_task_id: &str, + at: OffsetDateTime, + ) -> Result<()>; + + async fn add_comment( + &self, + task_id: &str, + author_id: &str, + body: &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 8c729ae..0b668bd 100644 --- a/crates/dizey-core/src/store/turso_store.rs +++ b/crates/dizey-core/src/store/turso_store.rs @@ -13,9 +13,13 @@ use turso::{Builder, Connection, Row, Value, params}; use uuid::Uuid; use super::{ - DeletePolicy, NewUser, Result, Session, SigninLink, Store, StoreError, User, Workspace, + DeletePolicy, NewTask, NewUser, Result, Session, SigninLink, Store, StoreError, User, Workspace, }; use crate::Role; +use crate::board::{BoardMeta, BoardReads, Column, Person, TaskRow}; +use time::Date; +use time::format_description::BorrowedFormatItem; +use time::macros::format_description; /// Every migration, in order. Adding one means appending a file and a line. const MIGRATIONS: &[(i64, &str)] = &[ @@ -23,6 +27,16 @@ const MIGRATIONS: &[(i64, &str)] = &[ (2, include_str!("../../migrations/0002_auth.sql")), ]; +/// The board a fresh workspace gets, and its columns. `Done` is the column +/// that stamps a card finished. +const DEFAULT_BOARD_NAME: &str = "Board"; +const DEFAULT_COLUMNS: &[(&str, bool)] = &[ + ("Backlog", false), + ("In Progress", false), + ("Review", false), + ("Done", true), +]; + pub struct TursoStore { /// Shared by every single-statement call. Turso serialises statements on a /// connection, so this is safe; transactions are the exception and take a @@ -142,6 +156,24 @@ fn parse_stamp(raw: &str) -> Result { .map_err(|e| StoreError::Corrupt(format!("timestamp {raw:?}: {e}"))) } +/// Deadlines are days, not instants: a deadline is the same day wherever the +/// person reading the card is. +const DAY: &[BorrowedFormatItem] = format_description!("[year]-[month]-[day]"); + +fn day_text(day: Date) -> Result { + day.format(&DAY) + .map_err(|e| StoreError::Corrupt(format!("deadline: {e}"))) +} + +fn opt_day(row: &Row, idx: usize) -> Result> { + match row.get::>(idx).map_err(backend)? { + Some(raw) => Date::parse(&raw, &DAY) + .map(Some) + .map_err(|e| StoreError::Corrupt(format!("deadline {raw:?}: {e}"))), + None => Ok(None), + } +} + fn opt_stamp(row: &Row, idx: usize) -> Result> { match row.get::>(idx).map_err(backend)? { Some(raw) => Ok(Some(parse_stamp(&raw)?)), @@ -247,6 +279,7 @@ impl Store for TursoStore { ) -> Result<(Workspace, User)> { let workspace_id = Uuid::new_v4().to_string(); let admin_id = Uuid::new_v4().to_string(); + let board_id = Uuid::new_v4().to_string(); let now = now_text()?; let email = fold_email(email); @@ -282,9 +315,36 @@ impl Store for TursoStore { tx.execute( "INSERT INTO workspace_owner (singleton, user_id, claimed_at) \ VALUES (1, ?1, ?2)", - params![admin_id.clone(), now], + params![admin_id.clone(), now.clone()], + ) + .await?; + // A claimed workspace is never boardless: the EmptyBoard screen is + // four named columns waiting for a first card, not a setup step. + tx.execute( + "INSERT INTO board (id, workspace_id, name, task_prefix, created_at) \ + VALUES (?1, ?2, ?3, 'DZ', ?4)", + params![ + board_id.clone(), + workspace_id.clone(), + DEFAULT_BOARD_NAME, + now + ], ) .await?; + for (position, (name, is_done)) in DEFAULT_COLUMNS.iter().enumerate() { + tx.execute( + "INSERT INTO board_column (id, board_id, name, position, is_done) \ + VALUES (?1, ?2, ?3, ?4, ?5)", + params![ + Uuid::new_v4().to_string(), + board_id.clone(), + *name, + position as i64, + i64::from(*is_done) + ], + ) + .await?; + } Ok::<_, turso::Error>(()) } .await; @@ -703,6 +763,340 @@ impl Store for TursoStore { .await .map_err(backend) } + + // -- board ------------------------------------------------------------- + + async fn create_column( + &self, + board_id: &str, + name: &str, + position: i64, + is_done: bool, + ) -> Result { + let id = Uuid::new_v4().to_string(); + self.conn + .execute( + "INSERT INTO board_column (id, board_id, name, position, is_done) \ + VALUES (?1, ?2, ?3, ?4, ?5)", + params![id.clone(), board_id, name, position, i64::from(is_done)], + ) + .await + .map_err(backend)?; + Ok(Column { + id, + name: name.to_string(), + position, + is_done, + }) + } + + async fn create_task(&self, new: NewTask<'_>) -> Result { + let id = Uuid::new_v4().to_string(); + let now = now_text()?; + let deadline = new.deadline.map(day_text).transpose()?; + + let mut conn = self.tx_conn().await?; + // IMMEDIATE: the key comes off a counter, so the read of next_task_no + // and the write that bumps it must not be interleaved with another + // writer's pair. + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + + let written = async { + let mut rows = tx + .query( + "SELECT task_prefix, next_task_no FROM board WHERE id = ?1", + params![new.board_id], + ) + .await?; + let Some(row) = rows.next().await? else { + return Ok(None); + }; + let prefix = row.get::(0)?; + let number = row.get::(1)?; + drop(rows); + tx.execute( + "UPDATE board SET next_task_no = ?1 WHERE id = ?2", + params![number + 1, new.board_id], + ) + .await?; + + // New cards land at the end of their column. + let mut rows = tx + .query( + "SELECT COALESCE(MAX(position), 0) FROM task WHERE column_id = ?1", + params![new.column_id], + ) + .await?; + let last = match rows.next().await? { + Some(row) => row.get::(0).unwrap_or(0.0), + None => 0.0, + }; + drop(rows); + let position = last + 1.0; + + let task_key = format!("{prefix}-{number:02}"); + tx.execute( + "INSERT INTO task (id, board_id, task_key, title, description, column_id, \ + deadline, position, created_by, created_at, updated_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?10)", + params![ + id.clone(), + new.board_id, + task_key.clone(), + new.title, + new.description, + new.column_id, + deadline.clone(), + position, + new.created_by, + now.clone() + ], + ) + .await?; + Ok::<_, turso::Error>(Some((task_key, position))) + } + .await; + + let written = match written { + Ok(Some(written)) => written, + Ok(None) => { + let _ = tx.rollback().await; + return Err(StoreError::NotFound); + } + Err(e) => { + let _ = tx.rollback().await; + return Err(backend(e)); + } + }; + tx.commit().await.map_err(backend)?; + + let (task_key, position) = written; + Ok(TaskRow { + id, + task_key, + title: new.title.to_string(), + column_id: new.column_id.to_string(), + deadline: new.deadline, + position, + done_at: None, + }) + } + + async fn assign_task(&self, task_id: &str, user_id: &str) -> Result<()> { + self.conn + .execute( + "INSERT OR IGNORE INTO task_assignee (task_id, user_id) VALUES (?1, ?2)", + params![task_id, user_id], + ) + .await + .map_err(backend)?; + Ok(()) + } + + async fn unassign_task(&self, task_id: &str, user_id: &str) -> Result<()> { + self.conn + .execute( + "DELETE FROM task_assignee WHERE task_id = ?1 AND user_id = ?2", + params![task_id, user_id], + ) + .await + .map_err(backend)?; + Ok(()) + } + + async fn add_dependency( + &self, + blocked_task_id: &str, + 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( + "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)?], + ) + .await + .map_err(backend)?; + Ok(()) + } + + async fn clear_dependency( + &self, + blocked_task_id: &str, + blocking_task_id: &str, + at: OffsetDateTime, + ) -> Result<()> { + self.conn + .execute( + "UPDATE task_dependency SET cleared_at = ?3 \ + WHERE blocked_task_id = ?1 AND blocking_task_id = ?2 AND cleared_at IS NULL", + params![blocked_task_id, blocking_task_id, stamp(at)?], + ) + .await + .map_err(backend)?; + Ok(()) + } + + async fn add_comment( + &self, + task_id: &str, + author_id: &str, + body: &str, + at: OffsetDateTime, + ) -> Result { + let id = Uuid::new_v4().to_string(); + self.conn + .execute( + "INSERT INTO comment (id, task_id, author_id, body, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5)", + params![id.clone(), task_id, author_id, body, stamp(at)?], + ) + .await + .map_err(backend)?; + Ok(id) + } +} + +#[async_trait] +impl BoardReads for TursoStore { + async fn board(&self, workspace_id: &str) -> Result> { + let row = self + .one_row( + "SELECT id, name, task_prefix FROM board WHERE workspace_id = ?1 \ + ORDER BY created_at LIMIT 1", + params![workspace_id], + ) + .await?; + match row { + Some(row) => Ok(Some(BoardMeta { + id: text(&row, 0)?, + name: text(&row, 1)?, + task_prefix: text(&row, 2)?, + })), + None => Ok(None), + } + } + + async fn columns(&self, board_id: &str) -> Result> { + let mut rows = self + .conn + .query( + "SELECT id, name, position, is_done FROM board_column WHERE board_id = ?1 \ + ORDER BY position", + params![board_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(Column { + id: text(&row, 0)?, + name: text(&row, 1)?, + position: row.get::(2).map_err(backend)?, + is_done: row.get::(3).map_err(backend)? != 0, + }); + } + Ok(out) + } + + async fn tasks_for_board(&self, board_id: &str) -> Result> { + let mut rows = self + .conn + .query( + "SELECT id, task_key, title, column_id, deadline, position, done_at \ + FROM task WHERE board_id = ?1 AND deleted_at IS NULL", + params![board_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(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)?, + }); + } + Ok(out) + } + + async fn assignees_for_board(&self, board_id: &str) -> Result> { + let mut rows = self + .conn + .query( + "SELECT a.task_id, u.id, u.display_name, u.photo_path \ + FROM task_assignee a \ + JOIN task t ON t.id = a.task_id \ + JOIN user u ON u.id = a.user_id \ + WHERE t.board_id = ?1 AND t.deleted_at IS NULL \ + ORDER BY u.display_name", + params![board_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(( + text(&row, 0)?, + Person { + id: text(&row, 1)?, + display_name: text(&row, 2)?, + photo_path: opt_text(&row, 3)?, + }, + )); + } + Ok(out) + } + + async fn comment_counts_for_board(&self, board_id: &str) -> Result> { + let mut rows = self + .conn + .query( + "SELECT c.task_id, COUNT(*) FROM comment c \ + JOIN task t ON t.id = c.task_id \ + WHERE t.board_id = ?1 AND t.deleted_at IS NULL \ + GROUP BY c.task_id", + params![board_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + let count = row.get::(1).map_err(backend)?.max(0) as u32; + out.push((text(&row, 0)?, count)); + } + Ok(out) + } + + async fn dependencies_for_board(&self, board_id: &str) -> Result> { + let mut rows = self + .conn + .query( + "SELECT d.blocked_task_id, d.blocking_task_id FROM task_dependency d \ + JOIN task t ON t.id = d.blocked_task_id \ + WHERE t.board_id = ?1 AND d.cleared_at IS NULL AND t.deleted_at IS NULL", + params![board_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push((text(&row, 0)?, text(&row, 1)?)); + } + Ok(out) + } } #[cfg(test)] diff --git a/crates/dizey-core/tests/store.rs b/crates/dizey-core/tests/store.rs index 2a2ca7d..29b9050 100644 --- a/crates/dizey-core/tests/store.rs +++ b/crates/dizey-core/tests/store.rs @@ -1200,3 +1200,345 @@ async fn an_address_can_only_be_invited_once() { Err(AccountError::AddressTaken) )); } + +// -- board ------------------------------------------------------------------ + +use dizey_core::board::{BoardReads, BoardView, Person, load}; +use dizey_core::store::NewTask; +use std::sync::atomic::{AtomicUsize, Ordering}; +use time::Date; +use time::macros::date; + +/// Wraps the real store and counts the round trips a board costs. +/// +/// This is the whole point of [`BoardReads`] being its own trait: the guard +/// against N+1 is tested by its effect — the count does not move when the board +/// gets bigger — rather than by reading the queries and taking their word. +struct CountingReads<'a> { + inner: &'a TursoStore, + calls: AtomicUsize, +} + +impl<'a> CountingReads<'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 BoardReads for CountingReads<'_> { + async fn board( + &self, + workspace_id: &str, + ) -> Result, StoreError> { + self.tick(); + self.inner.board(workspace_id).await + } + + async fn columns(&self, board_id: &str) -> Result, StoreError> { + self.tick(); + self.inner.columns(board_id).await + } + + async fn tasks_for_board( + &self, + board_id: &str, + ) -> Result, StoreError> { + self.tick(); + self.inner.tasks_for_board(board_id).await + } + + async fn assignees_for_board( + &self, + board_id: &str, + ) -> Result, StoreError> { + self.tick(); + self.inner.assignees_for_board(board_id).await + } + + async fn comment_counts_for_board( + &self, + board_id: &str, + ) -> Result, StoreError> { + self.tick(); + self.inner.comment_counts_for_board(board_id).await + } + + async fn dependencies_for_board( + &self, + board_id: &str, + ) -> Result, StoreError> { + self.tick(); + self.inner.dependencies_for_board(board_id).await + } +} + +async fn board_of(store: &TursoStore, workspace_id: &str) -> BoardView { + load(store, workspace_id) + .await + .unwrap() + .expect("a claimed workspace has a board") +} + +async fn column_named(store: &TursoStore, workspace_id: &str, name: &str) -> String { + let board = board_of(store, workspace_id).await; + board + .columns + .iter() + .find(|column| column.column.name == name) + .unwrap_or_else(|| panic!("no column named {name}")) + .column + .id + .clone() +} + +async fn add_task( + store: &TursoStore, + workspace_id: &str, + column: &str, + title: &str, + deadline: Option, + author: &str, +) -> String { + let board = store.board(workspace_id).await.unwrap().unwrap(); + let column_id = column_named(store, workspace_id, column).await; + store + .create_task(NewTask { + board_id: &board.id, + column_id: &column_id, + title, + description: "", + deadline, + created_by: author, + }) + .await + .unwrap() + .id +} + +#[tokio::test] +async fn a_claimed_workspace_starts_with_four_named_columns() { + let (scratch, workspace, _admin) = workspace_with_admin().await; + let board = board_of(&scratch.store, &workspace).await; + + let names: Vec<&str> = board + .columns + .iter() + .map(|column| column.column.name.as_str()) + .collect(); + assert_eq!(names, ["Backlog", "In Progress", "Review", "Done"]); + assert!(board.is_empty(), "a fresh board has no cards"); + // Only the last column finishes a task. + let done: Vec = board + .columns + .iter() + .map(|column| column.column.is_done) + .collect(); + assert_eq!(done, [false, false, false, true]); +} + +#[tokio::test] +async fn tasks_get_consecutive_keys_off_the_board_counter() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + for title in ["Pricing page draft", "Choose analytics stack"] { + add_task(store, &workspace, "Backlog", title, None, &admin).await; + } + + let board = board_of(store, &workspace).await; + let keys: Vec<&str> = board.cards().map(|card| card.task_key.as_str()).collect(); + assert_eq!(keys, ["DZ-01", "DZ-02"]); +} + +#[tokio::test] +async fn a_card_carries_its_assignees_comments_and_dependency_keys() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let mel = store + .create_user(NewUser { + workspace_id: workspace.clone(), + email: "mel@dizey.sh".into(), + display_name: "Mel Duarte".into(), + role: Role::Member, + }) + .await + .unwrap(); + + let blocking = add_task( + store, + &workspace, + "In Progress", + "CLI install script (curl | sh)", + Some(date!(2026 - 08 - 21)), + &admin, + ) + .await; + let blocked = add_task( + store, + &workspace, + "Backlog", + "Onboarding email sequence", + Some(date!(2026 - 10 - 06)), + &admin, + ) + .await; + + store.assign_task(&blocking, &admin).await.unwrap(); + store.assign_task(&blocking, &mel.id).await.unwrap(); + // Assigning twice is the same as assigning once. + store.assign_task(&blocking, &mel.id).await.unwrap(); + store + .add_dependency(&blocked, &blocking, OffsetDateTime::now_utc()) + .await + .unwrap(); + for body in ["needs a checksum", "and a version pin", "ready for review"] { + store + .add_comment(&blocking, &admin, body, OffsetDateTime::now_utc()) + .await + .unwrap(); + } + + let board = board_of(store, &workspace).await; + let card = board.cards().find(|card| card.id == blocking).unwrap(); + assert_eq!(card.assignees.len(), 2); + assert_eq!(card.comment_count, 3); + assert_eq!(card.blocks, ["DZ-02"]); + assert!(card.blocked_by.is_empty()); + assert!(!card.is_blocked()); + + let waiting = board.cards().find(|card| card.id == blocked).unwrap(); + assert_eq!(waiting.blocked_by, ["DZ-01"]); + assert!(waiting.is_blocked()); + assert_eq!(waiting.comment_count, 0); + assert!(waiting.assignees.is_empty()); + + let today = date!(2026 - 08 - 26); + assert_eq!(card.deadline_label(today), "Aug 21 · overdue"); + assert_eq!(waiting.deadline_label(today), "Oct 06"); + assert_eq!(board.overdue_count(today), 1); + assert_eq!(board.blocked_count(), 1); +} + +#[tokio::test] +async fn a_cleared_dependency_stops_showing_on_the_card() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let blocking = add_task(store, &workspace, "In Progress", "Invite flow", None, &admin).await; + let blocked = add_task(store, &workspace, "Backlog", "Terms of service", None, &admin).await; + let now = OffsetDateTime::now_utc(); + store.add_dependency(&blocked, &blocking, now).await.unwrap(); + + let board = board_of(store, &workspace).await; + assert!( + board + .cards() + .find(|card| card.id == blocked) + .unwrap() + .is_blocked() + ); + + store + .clear_dependency(&blocked, &blocking, now) + .await + .unwrap(); + let board = board_of(store, &workspace).await; + let card = board.cards().find(|card| card.id == blocked).unwrap(); + assert!(card.blocked_by.is_empty()); + assert!(!card.is_blocked()); +} + +#[tokio::test] +async fn cards_sort_by_deadline_with_the_undated_last() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + for (title, deadline) in [ + ("Choose analytics stack", None), + ("Terms of service review", Some(date!(2026 - 09 - 30))), + ("Pricing page draft", Some(date!(2026 - 09 - 12))), + ] { + add_task(store, &workspace, "Backlog", title, deadline, &admin).await; + } + + let board = board_of(store, &workspace).await; + let titles: Vec<&str> = board.columns[0] + .cards + .iter() + .map(|card| card.title.as_str()) + .collect(); + assert_eq!( + titles, + [ + "Pricing page draft", + "Terms of service review", + "Choose analytics stack" + ] + ); +} + +#[tokio::test] +async fn a_board_costs_six_queries_whatever_its_size() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + + let small = CountingReads::new(store); + load(&small, &workspace).await.unwrap(); + assert_eq!(small.count(), 6, "an empty board"); + + // Forty tasks, each with an assignee, a comment and a dependency — the + // three things a naive card query fans out on. + let mut previous: Option = None; + for n in 0..40 { + let id = add_task( + store, + &workspace, + "Backlog", + &format!("task {n}"), + Some(date!(2026 - 09 - 12)), + &admin, + ) + .await; + store.assign_task(&id, &admin).await.unwrap(); + store + .add_comment(&id, &admin, "a note", OffsetDateTime::now_utc()) + .await + .unwrap(); + if let Some(previous) = previous.replace(id.clone()) { + store + .add_dependency(&id, &previous, OffsetDateTime::now_utc()) + .await + .unwrap(); + } + } + + let big = CountingReads::new(store); + let board = load(&big, &workspace).await.unwrap().unwrap(); + assert_eq!(board.task_count(), 40); + assert_eq!( + big.count(), + 6, + "the round trips a board costs must not follow the number of tasks" + ); +} + +#[test] +fn initials_fall_back_to_two_letters() { + let person = |name: &str| Person { + id: "u".into(), + display_name: name.into(), + photo_path: None, + }; + assert_eq!(person("Mel Duarte").initials(), "MD"); + assert_eq!(person("Ada").initials(), "A"); + assert_eq!(person(" ").initials(), "?"); +}