From 76964b1144553e7dc1caf7564095174f6ad02613 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 09:15:03 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20core:=20authz,=20clock,=20m?= =?UTF-8?q?ember/session/board/task/comment/activity=20store?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/iz-core/src/authz.rs | 244 ++++ crates/iz-core/src/board.rs | 24 + crates/iz-core/src/clock.rs | 160 +++ crates/iz-core/src/lib.rs | 2 + crates/iz-core/src/store/activity.rs | 174 +++ crates/iz-core/src/store/board.rs | 625 ++++++++++ crates/iz-core/src/store/comments.rs | 333 ++++++ crates/iz-core/src/store/members.rs | 412 +++++++ crates/iz-core/src/store/mod.rs | 82 +- crates/iz-core/src/store/sessions.rs | 245 ++++ crates/iz-core/src/store/tasks.rs | 1585 ++++++++++++++++++++++++++ 11 files changed, 3884 insertions(+), 2 deletions(-) create mode 100644 crates/iz-core/src/authz.rs create mode 100644 crates/iz-core/src/clock.rs create mode 100644 crates/iz-core/src/store/activity.rs create mode 100644 crates/iz-core/src/store/board.rs create mode 100644 crates/iz-core/src/store/comments.rs create mode 100644 crates/iz-core/src/store/members.rs create mode 100644 crates/iz-core/src/store/sessions.rs create mode 100644 crates/iz-core/src/store/tasks.rs diff --git a/crates/iz-core/src/authz.rs b/crates/iz-core/src/authz.rs new file mode 100644 index 0000000..bf1bc58 --- /dev/null +++ b/crates/iz-core/src/authz.rs @@ -0,0 +1,244 @@ +//! Authorization (docs/architecture.md section 6). One pure function decides what an actor may do: +//! every page, form handler, API route and live stream calls [`authorize`] before it reads or writes. +//! A denial is `NotFound` when the viewer must not learn that the thing exists, and `Forbidden` +//! when the viewer may know it but may not act on it. +//! +//! Levels: admin contains member, member contains viewer. `im_admin` acts as admin. A disabled +//! account and role `none` are denied everything with `NotFound`. An anonymous actor is `Forbidden`, +//! so the caller can show the sign-in card. The store repeats the disabled and `none` checks in its +//! own queries (sessions, assignments), so a denied member cannot reach data through another path. + +use crate::error::Error; + +/// A member's stored role (`members.role`). Matches the CHECK constraint in the schema. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Role { + /// Full control of the board, including settings, tags, columns and roles. + Admin, + /// Reads and writes tasks, comments and files, and may be assigned. + Member, + /// Reads the board only. Never assigned, never mailed. + Viewer, + /// In the directory but with no access (stored as `none`). + NoAccess, +} + +impl Role { + /// The stored spelling of the role. + pub fn as_str(self) -> &'static str { + match self { + Role::Admin => "admin", + Role::Member => "member", + Role::Viewer => "viewer", + Role::NoAccess => "none", + } + } + + /// Parses the stored spelling. Unknown text is `None`, so a corrupt row is never read as a role. + pub fn parse(text: &str) -> Option { + match text { + "admin" => Some(Role::Admin), + "member" => Some(Role::Member), + "viewer" => Some(Role::Viewer), + "none" => Some(Role::NoAccess), + _ => None, + } + } +} + +/// Who is asking. Built by the web layer from the session, never from request input. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Actor { + /// No session. + Anonymous, + /// A signed-in member, with the flags read from the members row. + Member { + /// The member's stable id (the OIDC `sub`). + sub: String, + /// The stored role. + role: Role, + /// Whether the directory marks the member as an administrator. + im_admin: bool, + /// Whether the account is disabled. + disabled: bool, + }, +} + +/// What the actor wants to do. Actions that depend on ownership carry the owner's id. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Action { + /// Read the board, its tasks and their activity. + ReadBoard, + /// Read a person's card (same board only; the caller scopes the query). + ViewPerson, + /// Create, edit, move, assign, link or delete tasks. + WriteTask, + /// Post a comment. + Comment, + /// Edit a comment. Only its author may, and only while still a member. + EditComment { + /// Author of the comment. + author: String, + }, + /// Delete a comment: its author while still a member, or any admin. + DeleteComment { + /// Author of the comment. + author: String, + }, + /// Attach a file. + UploadFile, + /// Delete a file: its uploader while still a member, or any admin. + DeleteFile { + /// Uploader of the file. + uploader: String, + }, + /// Manage settings, tags, columns, roles and mail rules. + Administer, +} + +/// Why an action was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Denied { + /// The viewer may not know that the resource exists. Answer as if it were missing. + NotFound, + /// The viewer may know the resource but may not do this. + Forbidden, +} + +impl From for Error { + fn from(denied: Denied) -> Error { + match denied { + Denied::NotFound => Error::NotFound, + Denied::Forbidden => { + Error::Forbidden("this action is not allowed for your account".into()) + } + } + } +} + +/// Ordered levels. A larger level includes every permission of the smaller ones. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum Level { + Viewer, + Member, + Admin, +} + +/// Decides whether `actor` may perform `action`. Pure: no I/O, no clock. +pub fn authorize(actor: &Actor, action: &Action) -> Result<(), Denied> { + let (sub, level) = match actor { + Actor::Anonymous => return Err(Denied::Forbidden), + Actor::Member { disabled: true, .. } => return Err(Denied::NotFound), + Actor::Member { + sub, + im_admin: true, + .. + } => (sub.as_str(), Level::Admin), + Actor::Member { sub, role, .. } => { + let level = match role { + Role::Admin => Level::Admin, + Role::Member => Level::Member, + Role::Viewer => Level::Viewer, + Role::NoAccess => return Err(Denied::NotFound), + }; + (sub.as_str(), level) + } + }; + let allowed = match action { + Action::ReadBoard | Action::ViewPerson => level >= Level::Viewer, + Action::WriteTask | Action::Comment | Action::UploadFile => level >= Level::Member, + Action::EditComment { author } => level >= Level::Member && sub == author, + Action::DeleteComment { author } => { + level == Level::Admin || (level >= Level::Member && sub == author) + } + Action::DeleteFile { uploader } => { + level == Level::Admin || (level >= Level::Member && sub == uploader) + } + Action::Administer => level == Level::Admin, + }; + if allowed { + Ok(()) + } else { + Err(Denied::Forbidden) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn member(sub: &str, role: Role, im_admin: bool, disabled: bool) -> Actor { + Actor::Member { + sub: sub.into(), + role, + im_admin, + disabled, + } + } + + /// The truth table: each row is one actor and the result for each action, in this order: + /// read, write, comment, edit own comment `ada`, delete `ada`'s comment, upload, delete `ada`'s + /// file, administer. + #[test] + fn truth_table() { + use Denied::{Forbidden as F, NotFound as N}; + let ok = Ok(()); + let edit_ada = Action::EditComment { + author: "ada".into(), + }; + let del_ada = Action::DeleteComment { + author: "ada".into(), + }; + let file_ada = Action::DeleteFile { + uploader: "ada".into(), + }; + let rows: Vec<(Actor, [Result<(), Denied>; 8])> = vec![ + (Actor::Anonymous, [Err(F); 8]), + ( + member("ada", Role::Admin, false, false), + [ok, ok, ok, ok, ok, ok, ok, ok], + ), + ( + member("ada", Role::Member, false, false), + [ok, ok, ok, ok, ok, ok, ok, Err(F)], + ), + ( + member("bo", Role::Member, false, false), + [ok, ok, ok, Err(F), Err(F), ok, Err(F), Err(F)], + ), + ( + member("bo", Role::Viewer, false, false), + [ok, Err(F), Err(F), Err(F), Err(F), Err(F), Err(F), Err(F)], + ), + ( + member("bo", Role::Member, true, false), + [ok, ok, ok, Err(F), ok, ok, ok, ok], + ), + (member("ada", Role::NoAccess, false, false), [Err(N); 8]), + (member("ada", Role::Admin, false, true), [Err(N); 8]), + ]; + let actions = [ + Action::ReadBoard, + Action::WriteTask, + Action::Comment, + edit_ada, + del_ada, + Action::UploadFile, + file_ada, + Action::Administer, + ]; + for (actor, expected) in rows { + for (action, want) in actions.iter().zip(expected) { + assert_eq!(authorize(&actor, action), want, "{actor:?} {action:?}"); + } + } + } + + #[test] + fn role_spelling_round_trips() { + for role in [Role::Admin, Role::Member, Role::Viewer, Role::NoAccess] { + assert_eq!(Role::parse(role.as_str()), Some(role)); + } + assert_eq!(Role::parse("owner"), None); + } +} diff --git a/crates/iz-core/src/board.rs b/crates/iz-core/src/board.rs index d29af8f..b5f0cf7 100644 --- a/crates/iz-core/src/board.rs +++ b/crates/iz-core/src/board.rs @@ -76,6 +76,20 @@ pub fn position_between(before: Option, after: Option) -> f64 { } } +/// Folds text for case-insensitive search. Turkish letters are folded the way a Turkish reader +/// expects: `I`, `ı`, `İ` and `i` all match each other, so a search for `istanbul` finds `İSTANBUL` +/// and `ISTANBUL` finds `istanbul`. Every other letter uses Unicode lowercasing. +pub fn fold_for_search(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + match c { + 'I' | 'İ' | 'ı' | 'i' => out.push('i'), + other => out.extend(other.to_lowercase()), + } + } + out +} + /// A task key: `PREFIX-n`, for example `IZ-42`. The counter `n` comes from the board row. pub fn format_key(prefix: &str, n: u64) -> String { format!("{prefix}-{n}") @@ -144,6 +158,16 @@ mod tests { assert!(!would_cycle(&[(1, 2)], (4, 2))); } + #[test] + fn search_folds_turkish_dotted_and_dotless_i() { + let target = fold_for_search("İSTANBUL Şişli"); + assert!(target.contains(&fold_for_search("istanbul"))); + assert!(target.contains(&fold_for_search("ıstanbul"))); + assert!(target.contains(&fold_for_search("ISTANBUL"))); + assert!(target.contains(&fold_for_search("şişli"))); + assert!(!target.contains(&fold_for_search("ankara"))); + } + #[test] fn positions_and_keys() { assert_eq!(position_between(None, None), 1.0); diff --git a/crates/iz-core/src/clock.rs b/crates/iz-core/src/clock.rs new file mode 100644 index 0000000..81f6f31 --- /dev/null +++ b/crates/iz-core/src/clock.rs @@ -0,0 +1,160 @@ +//! Deadline and meeting-time rules (docs/reference/old-inventory.md 2.4), on real IANA zones through +//! `zones.rs`. A task has a deadline day, a meeting instant, or both. The user types a day and an +//! optional `HH:MM` in their own zone; this module turns that into the values the store keeps. +//! +//! Rules: a time needs a day; hour and minute are both given or neither; a meeting sets the deadline +//! day to the meeting's local day. A local time that does not exist (DST gap) or happens twice +//! (DST overlap) is refused, because the user has to choose. + +use jiff::civil::Date; +use jiff::tz::TimeZone; +use jiff::{SignedDuration, Timestamp}; +use time::OffsetDateTime; + +use crate::error::{Error, Result}; +use crate::time::format_stamp; +use crate::zones::{local_to_utc, utc_to_local}; + +/// How long before a meeting its reminder is due, in minutes. A default; the `reminder_minutes` +/// setting replaces it once the setting exists. +pub const REMINDER_LEAD_MINUTES: i64 = 15; + +/// What the user typed for a deadline and meeting time. Every part is optional. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct MeetingInput { + /// The day (a deadline, or the day of the meeting). + pub day: Option, + /// Hour of the meeting in the user's zone, 0 to 23. + pub hour: Option, + /// Minute of the meeting in the user's zone, 0 to 59. + pub minute: Option, +} + +/// Validates the input and resolves it to the stored values: the deadline day and the meeting as a +/// UTC stamp (the fixed-width format of `time::format_stamp`). Errors are `Invalid` and name the rule. +pub fn resolve_meeting( + input: MeetingInput, + zone: &TimeZone, +) -> Result<(Option, Option)> { + match (input.day, input.hour, input.minute) { + (day, None, None) => Ok((day, None)), + (None, _, _) => Err(Error::Invalid("a meeting time needs a day".into())), + (Some(day), Some(hour), Some(minute)) => { + let hour = i8::try_from(hour) + .map_err(|_| Error::Invalid(format!("hour {hour} is out of range")))?; + let minute = i8::try_from(minute) + .map_err(|_| Error::Invalid(format!("minute {minute} is out of range")))?; + let at = local_to_utc(zone, day, hour, minute)?; + let local_day = utc_to_local(zone, at).date(); + Ok((Some(local_day), Some(stamp_of(at)?))) + } + _ => Err(Error::Invalid( + "set both the hour and the minute, or neither".into(), + )), + } +} + +/// The stored stamp of an instant. Fails only for instants outside the range of `time`. +pub fn stamp_of(at: Timestamp) -> Result { + OffsetDateTime::from_unix_timestamp_nanos(at.as_nanosecond()) + .map(format_stamp) + .map_err(|e| Error::Invalid(format!("meeting time out of range: {e}"))) +} + +/// Parses a stored stamp back into an instant for comparisons. +pub fn timestamp_of(stamp: &str) -> Result { + stamp + .parse::() + .map_err(|e| Error::Database(format!("stored meeting time is not a stamp: {e}"))) +} + +/// The moment a reminder for a meeting at `meeting` is due: `REMINDER_LEAD_MINUTES` before it. +pub fn reminder_due(meeting: Timestamp) -> Result { + let due = meeting + .checked_sub(SignedDuration::from_mins(REMINDER_LEAD_MINUTES)) + .map_err(|e| Error::Invalid(format!("reminder time out of range: {e}")))?; + stamp_of(due) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::zones::parse_zone; + use jiff::civil::date; + + #[test] + fn meeting_rules_truth_table() { + let berlin = parse_zone("Europe/Berlin").unwrap(); + let d = Some(date(2026, 1, 15)); + // No time: the day stands alone. + let plain = MeetingInput { + day: d, + hour: None, + minute: None, + }; + assert_eq!(resolve_meeting(plain, &berlin).unwrap(), (d, None)); + // Nothing at all clears both. + assert_eq!( + resolve_meeting(MeetingInput::default(), &berlin).unwrap(), + (None, None) + ); + // Day and full time: 09:30 Berlin winter is 08:30Z, and the deadline day is kept. + let full = MeetingInput { + day: d, + hour: Some(9), + minute: Some(30), + }; + assert_eq!( + resolve_meeting(full, &berlin).unwrap(), + (d, Some("2026-01-15T08:30:00.000000000Z".into())) + ); + // A time without a day, or only half a time, is refused. + let no_day = MeetingInput { + day: None, + hour: Some(9), + minute: Some(30), + }; + assert!(matches!( + resolve_meeting(no_day, &berlin), + Err(Error::Invalid(_)) + )); + let half = MeetingInput { + day: d, + hour: Some(9), + minute: None, + }; + assert!(matches!( + resolve_meeting(half, &berlin), + Err(Error::Invalid(_)) + )); + // A DST gap is refused (02:30 does not exist on 2026-03-29 in Berlin). + let gap = MeetingInput { + day: Some(date(2026, 3, 29)), + hour: Some(2), + minute: Some(30), + }; + assert!(matches!( + resolve_meeting(gap, &berlin), + Err(Error::Invalid(_)) + )); + // Out-of-range clock values are refused. + let late = MeetingInput { + day: d, + hour: Some(24), + minute: Some(0), + }; + assert!(matches!( + resolve_meeting(late, &berlin), + Err(Error::Invalid(_)) + )); + } + + #[test] + fn reminder_is_lead_time_before_meeting() { + let meeting: Timestamp = "2026-01-15T08:30:00Z".parse().unwrap(); + assert_eq!( + reminder_due(meeting).unwrap(), + "2026-01-15T08:15:00.000000000Z" + ); + } +} diff --git a/crates/iz-core/src/lib.rs b/crates/iz-core/src/lib.rs index 7208a46..299c96d 100644 --- a/crates/iz-core/src/lib.rs +++ b/crates/iz-core/src/lib.rs @@ -3,7 +3,9 @@ //! This crate has no HTTP. It keeps the invariants: the schema, the length limits, the board rules //! (overdue, cycles, ordering), time zone math and sealing of secrets. `iz-web` builds on it. +pub mod authz; pub mod board; +pub mod clock; pub mod config; pub mod error; pub mod limits; diff --git a/crates/iz-core/src/store/activity.rs b/crates/iz-core/src/store/activity.rs new file mode 100644 index 0000000..66fc1a2 --- /dev/null +++ b/crates/iz-core/src/store/activity.rs @@ -0,0 +1,174 @@ +//! The activity trail. `record` writes one row and must be called inside the transaction of the change +//! it describes, so an activity row exists if and only if the change committed. Reads are keyset +//! pages ordered newest first; the cursor is `~` (stamps never contain `~`). +//! +//! Account events (`task_id` NULL) are visible to every board query. The web layer decides who may +//! see them; this module only keeps the board scope for task events. + +use turso::transaction::Transaction; + +use super::{col_opt_text, col_text, db_err, fetch_all, new_id}; +use crate::error::{Error, Result}; +use crate::store::Store; +use crate::time::now_stamp; + +/// Smallest and largest page size accepted by [`Store::list_recent`]. +pub const PAGE_MIN: usize = 1; +/// Largest page size accepted by [`Store::list_recent`]. Reason: bounds one response. +pub const PAGE_MAX: usize = 200; + +/// One activity row as read back. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Activity { + /// Row id (ULID). + pub id: String, + /// The task the event is about, or `None` for account events. + pub task_id: Option, + /// Who did it, or `None` for system events. + pub actor: Option, + /// The member the event is about (for example the person assigned), if any. + pub subject: Option, + /// Event kind (one of the CHECK list in the schema). + pub kind: String, + /// JSON text with the details. + pub detail: String, + /// UTC stamp. + pub at: String, +} + +/// An event to record. `kind` is one of the schema's CHECK list; the schema refuses anything else. +pub struct NewActivity<'a> { + /// The task, if the event is about one. + pub task_id: Option<&'a str>, + /// The acting member, or `None` for a system event. + pub actor: Option<&'a str>, + /// The member the event concerns, if any. + pub subject: Option<&'a str>, + /// Event kind. + pub kind: &'static str, + /// Details. Never secrets. + pub detail: serde_json::Value, +} + +/// Filters for the recent-activity page. `None` means no filter. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ActivityFilter { + /// Only this event kind. + pub kind: Option, + /// Only events by this member. + pub actor: Option, +} + +/// One keyset page of activity. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ActivityPage { + /// Newest first. + pub items: Vec, + /// Pass back as `cursor` for the next (older) page; `None` when this page is not full. + pub next_cursor: Option, +} + +/// Writes one activity row inside `tx`. The caller commits or rolls back with the change. +pub async fn record(tx: &Transaction<'_>, entry: NewActivity<'_>) -> Result<()> { + let detail = serde_json::to_string(&entry.detail) + .map_err(|e| Error::Database(format!("activity detail is not JSON: {e}")))?; + tx.execute( + "INSERT INTO activity (id, task_id, actor, subject, kind, detail, at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + ( + new_id(), + entry.task_id.map(str::to_owned), + entry.actor.map(str::to_owned), + entry.subject.map(str::to_owned), + entry.kind, + detail, + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) +} + +const ACTIVITY_COLS: &str = "a.id, a.task_id, a.actor, a.subject, a.kind, a.detail, a.at"; + +fn map_activity(row: &turso::Row) -> Result { + Ok(Activity { + id: col_text(row, 0)?, + task_id: col_opt_text(row, 1)?, + actor: col_opt_text(row, 2)?, + subject: col_opt_text(row, 3)?, + kind: col_text(row, 4)?, + detail: col_text(row, 5)?, + at: col_text(row, 6)?, + }) +} + +impl Store { + /// Every event about one task of `board_id`, oldest first (the order of the task's history). + pub async fn list_for_task(&self, board_id: &str, task_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {ACTIVITY_COLS} FROM activity a JOIN tasks t ON t.id = a.task_id \ + WHERE a.task_id = ?1 AND t.board_id = ?2 ORDER BY a.at, a.id" + ), + (task_id.to_owned(), board_id.to_owned()), + map_activity, + ) + .await + } + + /// One page of recent activity, newest first. `cursor` is the `next_cursor` of the previous page. + /// `limit` must be between [`PAGE_MIN`] and [`PAGE_MAX`]. + pub async fn list_recent( + &self, + board_id: &str, + filter: &ActivityFilter, + cursor: Option<&str>, + limit: usize, + ) -> Result { + if !(PAGE_MIN..=PAGE_MAX).contains(&limit) { + return Err(Error::Invalid(format!( + "page size must be {PAGE_MIN} to {PAGE_MAX}" + ))); + } + let (before_at, before_id) = match cursor { + None => (None, None), + Some(text) => { + let (at, id) = text + .split_once('~') + .ok_or_else(|| Error::Invalid("malformed activity cursor".into()))?; + (Some(at.to_owned()), Some(id.to_owned())) + } + }; + let conn = self.read_conn().await; + let items = fetch_all( + &conn, + &format!( + "SELECT {ACTIVITY_COLS} FROM activity a LEFT JOIN tasks t ON t.id = a.task_id \ + WHERE (t.board_id = ?1 OR a.task_id IS NULL) \ + AND (?2 IS NULL OR a.kind = ?2) \ + AND (?3 IS NULL OR a.actor = ?3) \ + AND (?4 IS NULL OR a.at < ?4 OR (a.at = ?4 AND a.id < ?5)) \ + ORDER BY a.at DESC, a.id DESC LIMIT ?6" + ), + ( + board_id.to_owned(), + filter.kind.clone(), + filter.actor.clone(), + before_at, + before_id, + i64::try_from(limit).unwrap_or(i64::MAX), + ), + map_activity, + ) + .await?; + let next_cursor = match items.last() { + Some(last) if items.len() == limit => Some(format!("{}~{}", last.at, last.id)), + _ => None, + }; + Ok(ActivityPage { items, next_cursor }) + } +} diff --git a/crates/iz-core/src/store/board.rs b/crates/iz-core/src/store/board.rs new file mode 100644 index 0000000..96c0b06 --- /dev/null +++ b/crates/iz-core/src/store/board.rs @@ -0,0 +1,625 @@ +//! The board itself: its row, its columns and its tags (projects). Columns are never deleted; a column +//! that is no longer used is retired (`deleted_at`), so transitions keep naming it. Exactly one live +//! column is the done column, and it is always last. Tags keep positions without gaps, and the default +//! tag cannot be deleted. +//! +//! Each multi-step change runs in one transaction. Positions are renumbered from 1 (columns) and 1.0 +//! (tags) after every move or removal, so the order never has holes. + +use turso::Connection; +use turso::transaction::Transaction; + +use super::{col_bool, col_int, col_real, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; +use crate::error::{Error, Result}; +use crate::limits::{COLUMN_NAME_MAX, TAG_NAME_MAX}; +use crate::store::Store; +use crate::time::now_stamp; + +/// Name of the board created on first start. The board has no other name source yet. +const DEFAULT_BOARD_NAME: &str = "Board"; +/// The four seeded columns, in order. The last one is the done column. +const DEFAULT_COLUMNS: [(&str, bool); 4] = [ + ("Backlog", false), + ("In Progress", false), + ("Review", false), + ("Done", true), +]; +/// Name of the tag every task wears when no other is chosen. +pub const DEFAULT_TAG_NAME: &str = "General"; +/// Longest tag colour name, in characters. Reason: colours come from a short fixed palette. +const COLOR_MAX: usize = 20; + +/// The board row. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Board { + /// Board id (ULID). + pub id: String, + /// Display name. + pub name: String, + /// Two to six uppercase letters; task keys are `PREFIX-n`. + pub key_prefix: String, + /// The next task number to hand out. Only goes up, so keys are never reused. + pub next_task_number: i64, + /// UTC stamp. + pub created_at: String, +} + +/// A column of the board. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Column { + /// Column id (ULID). + pub id: String, + /// Board the column belongs to. + pub board_id: String, + /// Display name, 1 to 60 characters. + pub name: String, + /// Order among the live columns, from 1. + pub position: i64, + /// Whether this is the done column (entering it stamps `done_at`). + pub is_done: bool, + /// Set when the column is retired. Retired columns are hidden but still named by transitions. + pub deleted_at: Option, +} + +/// A tag (project). Every task wears exactly one. +#[derive(Debug, Clone, PartialEq)] +pub struct Tag { + /// Tag id (ULID). + pub id: String, + /// Board the tag belongs to. + pub board_id: String, + /// Name, unique per board regardless of case. + pub name: String, + /// Order among the tags, from 1.0. + pub position: f64, + /// Whether this is the default tag (one per board, not deletable). + pub is_default: bool, + /// Optional colour name from the fixed palette. + pub color: Option, +} + +/// Direction for moving a column or a tag one place. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Direction { + /// Towards the start. + Up, + /// Towards the end. + Down, +} + +const BOARD_COLS: &str = "id, name, key_prefix, next_task_number, created_at"; +const COLUMN_COLS: &str = "id, board_id, name, position, is_done, deleted_at"; +const TAG_COLS: &str = "id, board_id, name, position, is_default, color"; + +fn map_board(row: &turso::Row) -> Result { + Ok(Board { + id: col_text(row, 0)?, + name: col_text(row, 1)?, + key_prefix: col_text(row, 2)?, + next_task_number: col_int(row, 3)?, + created_at: col_text(row, 4)?, + }) +} + +fn map_column(row: &turso::Row) -> Result { + Ok(Column { + id: col_text(row, 0)?, + board_id: col_text(row, 1)?, + name: col_text(row, 2)?, + position: col_int(row, 3)?, + is_done: col_bool(row, 4)?, + deleted_at: super::col_opt_text(row, 5)?, + }) +} + +fn map_tag(row: &turso::Row) -> Result { + Ok(Tag { + id: col_text(row, 0)?, + board_id: col_text(row, 1)?, + name: col_text(row, 2)?, + position: col_real(row, 3)?, + is_default: col_bool(row, 4)?, + color: super::col_opt_text(row, 5)?, + }) +} + +/// A board key prefix: two to six uppercase ASCII letters. +pub fn valid_prefix(prefix: &str) -> bool { + (2..=6).contains(&prefix.len()) && prefix.bytes().all(|b| b.is_ascii_uppercase()) +} + +/// Trims and checks a column name. +pub fn clean_column_name(name: &str) -> Result { + let name = name.trim(); + if name.is_empty() || name.chars().count() > COLUMN_NAME_MAX { + return Err(Error::Invalid(format!( + "column name must be 1 to {COLUMN_NAME_MAX} characters" + ))); + } + Ok(name.to_owned()) +} + +/// Trims and checks a tag name. +pub fn clean_tag_name(name: &str) -> Result { + let name = name.trim(); + if name.is_empty() || name.chars().count() > TAG_NAME_MAX { + return Err(Error::Invalid(format!( + "project name must be 1 to {TAG_NAME_MAX} characters" + ))); + } + Ok(name.to_owned()) +} + +/// Live columns of a board in display order. A query helper shared with the task module. +pub(super) async fn live_columns(conn: &Connection, board_id: &str) -> Result> { + fetch_all( + conn, + &format!( + "SELECT {COLUMN_COLS} FROM columns WHERE board_id = ?1 AND deleted_at IS NULL \ + ORDER BY position, id" + ), + (board_id.to_owned(),), + map_column, + ) + .await +} + +/// One column of a board, retired or not. +pub(super) async fn column_in( + conn: &Connection, + board_id: &str, + column_id: &str, +) -> Result> { + fetch_opt( + conn, + &format!("SELECT {COLUMN_COLS} FROM columns WHERE id = ?1 AND board_id = ?2"), + (column_id.to_owned(), board_id.to_owned()), + map_column, + ) + .await +} + +/// Writes `order` back as positions 1, 2, 3, ... for the live columns of the board. +async fn renumber_columns(tx: &Transaction<'_>, board_id: &str, order: &[String]) -> Result<()> { + for (i, id) in order.iter().enumerate() { + let position = i64::try_from(i + 1).unwrap_or(i64::MAX); + tx.execute( + "UPDATE columns SET position = ?3 WHERE id = ?1 AND board_id = ?2", + (id.clone(), board_id.to_owned(), position), + ) + .await + .map_err(db_err)?; + } + Ok(()) +} + +/// Writes `order` back as positions 1.0, 2.0, ... for the tags of the board. +async fn renumber_tags(tx: &Transaction<'_>, board_id: &str, order: &[String]) -> Result<()> { + for (i, id) in order.iter().enumerate() { + let position = f64::from(u32::try_from(i + 1).unwrap_or(u32::MAX)); + tx.execute( + "UPDATE tags SET position = ?3 WHERE id = ?1 AND board_id = ?2", + (id.clone(), board_id.to_owned(), position), + ) + .await + .map_err(db_err)?; + } + Ok(()) +} + +async fn all_tags(tx: &Transaction<'_>, board_id: &str) -> Result> { + fetch_all( + tx, + &format!("SELECT {TAG_COLS} FROM tags WHERE board_id = ?1 ORDER BY position, id"), + (board_id.to_owned(),), + map_tag, + ) + .await +} + +impl Store { + /// Makes sure the board exists, creating it with its four columns and the default tag on first + /// use. Idempotent: an existing board is returned unchanged. Returns the board. + pub async fn ensure_board(&self, key_prefix: &str) -> Result { + if !valid_prefix(key_prefix) { + return Err(Error::Invalid( + "key prefix must be 2 to 6 uppercase letters".into(), + )); + } + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + if let Some(board) = fetch_opt( + &tx, + &format!("SELECT {BOARD_COLS} FROM boards ORDER BY created_at, id LIMIT 1"), + (), + map_board, + ) + .await? + { + return Ok(board); + } + let board_id = new_id(); + let now = now_stamp(); + tx.execute( + "INSERT INTO boards (id, name, key_prefix, created_at) VALUES (?1, ?2, ?3, ?4)", + ( + board_id.clone(), + DEFAULT_BOARD_NAME, + key_prefix.to_owned(), + now.clone(), + ), + ) + .await + .map_err(db_err)?; + for (i, (name, is_done)) in DEFAULT_COLUMNS.iter().enumerate() { + let position = i64::try_from(i + 1).unwrap_or(i64::MAX); + tx.execute( + "INSERT INTO columns (id, board_id, name, position, is_done, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + ( + new_id(), + board_id.clone(), + *name, + position, + i64::from(*is_done), + now.clone(), + ), + ) + .await + .map_err(db_err)?; + } + tx.execute( + "INSERT INTO tags (id, board_id, name, position, is_default, created_at) \ + VALUES (?1, ?2, ?3, 1.0, 1, ?4)", + (new_id(), board_id.clone(), DEFAULT_TAG_NAME, now), + ) + .await + .map_err(db_err)?; + fetch_opt( + &tx, + &format!("SELECT {BOARD_COLS} FROM boards WHERE id = ?1"), + (board_id,), + map_board, + ) + .await? + .ok_or_else(|| Error::Database("board vanished after insert".into())) + } + .await; + finish(tx, outcome).await + } + + /// The board, or `None` before [`Store::ensure_board`] has run. + pub async fn board(&self) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!("SELECT {BOARD_COLS} FROM boards ORDER BY created_at, id LIMIT 1"), + (), + map_board, + ) + .await + } + + /// The live columns of a board, in order. Retired columns are not included. + pub async fn columns(&self, board_id: &str) -> Result> { + let conn = self.read_conn().await; + live_columns(&conn, board_id).await + } + + /// One column of `board_id`, retired or not. `None` when it belongs to another board or does not exist. + pub async fn column(&self, board_id: &str, column_id: &str) -> Result> { + let conn = self.read_conn().await; + column_in(&conn, board_id, column_id).await + } + + /// Adds a column before the done column (so done stays last). Returns the new column. + pub async fn add_column(&self, board_id: &str, name: &str) -> Result { + let name = clean_column_name(name)?; + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let live = live_columns(&tx, board_id).await?; + let mut order: Vec = live.iter().map(|c| c.id.clone()).collect(); + let at = live.iter().position(|c| c.is_done).unwrap_or(order.len()); + let id = new_id(); + tx.execute( + "INSERT INTO columns (id, board_id, name, position, is_done, created_at) \ + VALUES (?1, ?2, ?3, 0, 0, ?4)", + (id.clone(), board_id.to_owned(), name, now_stamp()), + ) + .await + .map_err(db_err)?; + order.insert(at, id.clone()); + renumber_columns(&tx, board_id, &order).await?; + column_in(&tx, board_id, &id) + .await? + .ok_or_else(|| Error::Database("column vanished after insert".into())) + } + .await; + finish(tx, outcome).await + } + + /// Renames a live column. Retired or foreign columns are `NotFound`. + pub async fn rename_column(&self, board_id: &str, column_id: &str, name: &str) -> Result<()> { + let name = clean_column_name(name)?; + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE columns SET name = ?3 WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", + (column_id.to_owned(), board_id.to_owned(), name), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + Ok(()) + } + + /// Moves a live column one place. The done column cannot move, and no column moves past it. At + /// the ends of the board the call changes nothing. + pub async fn move_column( + &self, + board_id: &str, + column_id: &str, + direction: Direction, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let live = live_columns(&tx, board_id).await?; + let index = live + .iter() + .position(|c| c.id == column_id) + .ok_or(Error::NotFound)?; + if live[index].is_done { + return Err(Error::Invalid("the done column stays last".into())); + } + let target = match direction { + Direction::Up => index.checked_sub(1), + Direction::Down => Some(index + 1).filter(|&i| i < live.len()), + }; + let Some(target) = target else { return Ok(()) }; + if live[target].is_done { + return Err(Error::Invalid("the done column stays last".into())); + } + let mut order: Vec = live.iter().map(|c| c.id.clone()).collect(); + order.swap(index, target); + renumber_columns(&tx, board_id, &order).await + } + .await; + finish(tx, outcome).await + } + + /// Retires a live column. Refused for the done column, and while any live task is in it. + pub async fn retire_column(&self, board_id: &str, column_id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let live = live_columns(&tx, board_id).await?; + let column = live + .iter() + .find(|c| c.id == column_id) + .ok_or(Error::NotFound)?; + if column.is_done { + return Err(Error::Invalid("the done column cannot be retired".into())); + } + let holding = fetch_opt( + &tx, + "SELECT COUNT(*) FROM tasks WHERE board_id = ?1 AND column_id = ?2 AND deleted_at IS NULL", + (board_id.to_owned(), column_id.to_owned()), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + if holding > 0 { + return Err(Error::Conflict(format!( + "the column still holds {holding} tasks; move them first" + ))); + } + tx.execute( + "UPDATE columns SET deleted_at = ?3 WHERE id = ?1 AND board_id = ?2", + (column_id.to_owned(), board_id.to_owned(), now_stamp()), + ) + .await + .map_err(db_err)?; + let order: Vec = live + .iter() + .filter(|c| c.id != column_id) + .map(|c| c.id.clone()) + .collect(); + renumber_columns(&tx, board_id, &order).await + } + .await; + finish(tx, outcome).await + } + + /// Every tag of a board, in order. + pub async fn tags(&self, board_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!("SELECT {TAG_COLS} FROM tags WHERE board_id = ?1 ORDER BY position, id"), + (board_id.to_owned(),), + map_tag, + ) + .await + } + + /// One tag of `board_id`, or `None`. + pub async fn tag(&self, board_id: &str, tag_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!("SELECT {TAG_COLS} FROM tags WHERE id = ?1 AND board_id = ?2"), + (tag_id.to_owned(), board_id.to_owned()), + map_tag, + ) + .await + } + + /// Adds a tag at the end. Names are unique per board, ignoring case. Returns the tag. + pub async fn add_tag(&self, board_id: &str, name: &str, color: Option<&str>) -> Result { + let name = clean_tag_name(name)?; + let color = match color.map(str::trim).filter(|c| !c.is_empty()) { + Some(c) if c.chars().count() <= COLOR_MAX => Some(c.to_owned()), + Some(_) => return Err(Error::Invalid("colour name is too long".into())), + None => None, + }; + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = + async { + let existing = all_tags(&tx, board_id).await?; + if existing + .iter() + .any(|t| t.name.to_lowercase() == name.to_lowercase()) + { + return Err(Error::Conflict( + "a project with that name already exists".into(), + )); + } + let position = existing.iter().map(|t| t.position).fold(0.0_f64, f64::max) + 1.0; + let id = new_id(); + tx.execute( + "INSERT INTO tags (id, board_id, name, position, is_default, color, created_at) \ + VALUES (?1, ?2, ?3, ?4, 0, ?5, ?6)", + (id.clone(), board_id.to_owned(), name, position, color, now_stamp()), + ) + .await + .map_err(db_err)?; + fetch_opt( + &tx, + &format!("SELECT {TAG_COLS} FROM tags WHERE id = ?1"), + (id,), + map_tag, + ) + .await? + .ok_or_else(|| Error::Database("tag vanished after insert".into())) + } + .await; + finish(tx, outcome).await + } + + /// Renames a tag. The new name must be unique per board, ignoring case. + pub async fn rename_tag(&self, board_id: &str, tag_id: &str, name: &str) -> Result<()> { + let name = clean_tag_name(name)?; + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let existing = all_tags(&tx, board_id).await?; + if !existing.iter().any(|t| t.id == tag_id) { + return Err(Error::NotFound); + } + if existing + .iter() + .any(|t| t.id != tag_id && t.name.to_lowercase() == name.to_lowercase()) + { + return Err(Error::Conflict( + "a project with that name already exists".into(), + )); + } + tx.execute( + "UPDATE tags SET name = ?3 WHERE id = ?1 AND board_id = ?2", + (tag_id.to_owned(), board_id.to_owned(), name), + ) + .await + .map_err(db_err)?; + Ok(()) + } + .await; + finish(tx, outcome).await + } + + /// Deletes a tag. Refused for the default tag, and while a live task wears it. Trashed (deleted) + /// tasks that still name it are moved to the default tag in the same transaction. + pub async fn delete_tag(&self, board_id: &str, tag_id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let tags = all_tags(&tx, board_id).await?; + let tag = tags.iter().find(|t| t.id == tag_id).ok_or(Error::NotFound)?; + if tag.is_default { + return Err(Error::Invalid("the default project cannot be deleted".into())); + } + let in_use = fetch_opt( + &tx, + "SELECT COUNT(*) FROM tasks WHERE board_id = ?1 AND tag_id = ?2 AND deleted_at IS NULL", + (board_id.to_owned(), tag_id.to_owned()), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + if in_use > 0 { + return Err(Error::Conflict(format!( + "the project is used by {in_use} tasks; move them first" + ))); + } + let default_id = tags + .iter() + .find(|t| t.is_default) + .map(|t| t.id.clone()) + .ok_or_else(|| Error::Database("board has no default project".into()))?; + tx.execute( + "UPDATE tasks SET tag_id = ?3 WHERE board_id = ?1 AND tag_id = ?2 AND deleted_at IS NOT NULL", + (board_id.to_owned(), tag_id.to_owned(), default_id), + ) + .await + .map_err(db_err)?; + tx.execute( + "DELETE FROM tags WHERE id = ?1 AND board_id = ?2", + (tag_id.to_owned(), board_id.to_owned()), + ) + .await + .map_err(db_err)?; + let order: Vec = tags + .iter() + .filter(|t| t.id != tag_id) + .map(|t| t.id.clone()) + .collect(); + renumber_tags(&tx, board_id, &order).await + } + .await; + finish(tx, outcome).await + } + + /// Moves a tag one place and renumbers all tags, so there are never gaps. At the ends, no change. + pub async fn move_tag(&self, board_id: &str, tag_id: &str, direction: Direction) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let tags = all_tags(&tx, board_id).await?; + let index = tags + .iter() + .position(|t| t.id == tag_id) + .ok_or(Error::NotFound)?; + let target = match direction { + Direction::Up => index.checked_sub(1), + Direction::Down => Some(index + 1).filter(|&i| i < tags.len()), + }; + let Some(target) = target else { return Ok(()) }; + let mut order: Vec = tags.iter().map(|t| t.id.clone()).collect(); + order.swap(index, target); + renumber_tags(&tx, board_id, &order).await + } + .await; + finish(tx, outcome).await + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prefix_and_names_are_checked() { + assert!(valid_prefix("IZ")); + assert!(valid_prefix("ABCDEF")); + assert!(!valid_prefix("I")); + assert!(!valid_prefix("iz")); + assert!(!valid_prefix("IZ1")); + assert!(clean_column_name(" ").is_err()); + assert_eq!(clean_tag_name(" Home ").unwrap(), "Home"); + } +} diff --git a/crates/iz-core/src/store/comments.rs b/crates/iz-core/src/store/comments.rs new file mode 100644 index 0000000..78b3a67 --- /dev/null +++ b/crates/iz-core/src/store/comments.rs @@ -0,0 +1,333 @@ +//! Comments on tasks. Posting is the caller's check (a member, not a viewer). Editing and deleting are +//! checked here through `authz::authorize`, against the comment's own author, so the rule lives in one +//! place: an author edits or deletes their own comment, and an admin may delete any comment. Deletion is +//! soft: the row stays so the activity trail can name it, and lists skip it. + +use turso::Connection; + +use super::activity::{self, NewActivity}; +use super::{col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; +use crate::authz::{Action, Actor, authorize}; +use crate::error::{Error, Result}; +use crate::limits::COMMENT_MAX; +use crate::store::Store; +use crate::time::now_stamp; + +/// One comment as stored. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Comment { + /// Comment id (ULID). + pub id: String, + /// The task it belongs to. + pub task_id: String, + /// The author's member id. + pub author: String, + /// Plain text, 1 to 10 000 characters. + pub body: String, + /// UTC stamp. + pub created_at: String, + /// UTC stamp of the last edit, if edited. + pub edited_at: Option, + /// UTC stamp of deletion, if deleted (such rows are not listed). + pub deleted_at: Option, +} + +const COMMENT_COLS: &str = "id, task_id, author, body, created_at, edited_at, deleted_at"; + +fn map_comment(row: &turso::Row) -> Result { + Ok(Comment { + id: col_text(row, 0)?, + task_id: col_text(row, 1)?, + author: col_text(row, 2)?, + body: col_text(row, 3)?, + created_at: col_text(row, 4)?, + edited_at: col_opt_text(row, 5)?, + deleted_at: col_opt_text(row, 6)?, + }) +} + +fn clean_body(body: &str) -> Result { + let body = body.trim(); + if body.is_empty() || body.chars().count() > COMMENT_MAX { + return Err(Error::Invalid(format!( + "comment must be 1 to {COMMENT_MAX} characters" + ))); + } + Ok(body.to_owned()) +} + +/// The member id behind an actor that has already passed `authorize`. +fn member_sub(actor: &Actor) -> Result<&str> { + match actor { + Actor::Member { sub, .. } => Ok(sub), + Actor::Anonymous => Err(Error::Forbidden("sign in to continue".into())), + } +} + +/// Reads a live comment of `board_id` with its task id and author. Missing or foreign: `NotFound`. +async fn live_comment(conn: &Connection, board_id: &str, comment_id: &str) -> Result { + fetch_opt( + conn, + "SELECT c.id, c.task_id, c.author, c.body, c.created_at, c.edited_at, c.deleted_at FROM comments c \ + JOIN tasks t ON t.id = c.task_id \ + WHERE c.id = ?1 AND t.board_id = ?2 AND c.deleted_at IS NULL", + (comment_id.to_owned(), board_id.to_owned()), + map_comment, + ) + .await? + .ok_or(Error::NotFound) +} + +impl Store { + /// Posts a comment on a live task of `board_id`, with its `comment_added` activity row. + pub async fn add_comment( + &self, + board_id: &str, + task_id: &str, + author: &str, + body: &str, + ) -> Result { + let body = clean_body(body)?; + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let live = fetch_opt( + &tx, + "SELECT id FROM tasks WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", + (task_id.to_owned(), board_id.to_owned()), + |row| col_text(row, 0), + ) + .await?; + if live.is_none() { + return Err(Error::NotFound); + } + let id = new_id(); + tx.execute( + "INSERT INTO comments (id, task_id, author, body, created_at) VALUES (?1, ?2, ?3, ?4, ?5)", + (id.clone(), task_id.to_owned(), author.to_owned(), body, now_stamp()), + ) + .await + .map_err(db_err)?; + activity::record( + &tx, + NewActivity { + task_id: Some(task_id), + actor: Some(author), + subject: None, + kind: "comment_added", + detail: serde_json::json!({ "comment": id }), + }, + ) + .await?; + fetch_opt( + &tx, + &format!("SELECT {COMMENT_COLS} FROM comments WHERE id = ?1"), + (id,), + map_comment, + ) + .await? + .ok_or_else(|| Error::Database("comment vanished after insert".into())) + } + .await; + finish(tx, outcome).await + } + + /// Live comments of a task of `board_id`, oldest first. + pub async fn list_comments(&self, board_id: &str, task_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT c.id, c.task_id, c.author, c.body, c.created_at, c.edited_at, c.deleted_at FROM comments c \ + JOIN tasks t ON t.id = c.task_id \ + WHERE c.task_id = ?1 AND t.board_id = ?2 AND c.deleted_at IS NULL ORDER BY c.created_at, c.id", + (task_id.to_owned(), board_id.to_owned()), + map_comment, + ) + .await + } + + /// Edits a comment. Only its author may, and only while still a member (`authz`). + pub async fn edit_comment( + &self, + board_id: &str, + comment_id: &str, + actor: &Actor, + body: &str, + ) -> Result { + let body = clean_body(body)?; + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let current = live_comment(&tx, board_id, comment_id).await?; + authorize( + actor, + &Action::EditComment { + author: current.author.clone(), + }, + )?; + let sub = member_sub(actor)?; + tx.execute( + "UPDATE comments SET body = ?2, edited_at = ?3 WHERE id = ?1", + (comment_id.to_owned(), body, now_stamp()), + ) + .await + .map_err(db_err)?; + activity::record( + &tx, + NewActivity { + task_id: Some(¤t.task_id), + actor: Some(sub), + subject: None, + kind: "comment_edited", + detail: serde_json::json!({ "comment": comment_id }), + }, + ) + .await?; + fetch_opt( + &tx, + &format!("SELECT {COMMENT_COLS} FROM comments WHERE id = ?1"), + (comment_id.to_owned(),), + map_comment, + ) + .await? + .ok_or(Error::NotFound) + } + .await; + finish(tx, outcome).await + } + + /// Soft-deletes a comment. Its author (while a member) or any admin may do it (`authz`). + pub async fn delete_comment( + &self, + board_id: &str, + comment_id: &str, + actor: &Actor, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let current = live_comment(&tx, board_id, comment_id).await?; + authorize( + actor, + &Action::DeleteComment { + author: current.author.clone(), + }, + )?; + let sub = member_sub(actor)?; + tx.execute( + "UPDATE comments SET deleted_at = ?2 WHERE id = ?1", + (comment_id.to_owned(), now_stamp()), + ) + .await + .map_err(db_err)?; + activity::record( + &tx, + NewActivity { + task_id: Some(¤t.task_id), + actor: Some(sub), + subject: Some(¤t.author), + kind: "comment_deleted", + detail: serde_json::json!({ "comment": comment_id }), + }, + ) + .await + } + .await; + finish(tx, outcome).await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::authz::Role; + use crate::store::activity::ActivityFilter; + use crate::store::tasks::NewTask; + use crate::store::test_support::seeded; + + fn member(sub: &str, role: Role) -> Actor { + Actor::Member { + sub: sub.into(), + role, + im_admin: false, + disabled: false, + } + } + + #[tokio::test] + async fn only_the_author_edits_and_admins_moderate() { + let (_dir, store, board) = seeded().await; + let tag = store.tags(&board).await.unwrap()[0].id.clone(); + let column = store.columns(&board).await.unwrap()[0].id.clone(); + let task = store + .create_task( + &board, + NewTask { + title: "Talk".into(), + description: String::new(), + column_id: column, + tag_id: tag, + deadline: None, + meeting_at: None, + assignees: vec![], + parent_id: None, + link: None, + }, + "ada", + ) + .await + .unwrap(); + let comment = store + .add_comment(&board, &task.id, "bo", " hello ") + .await + .unwrap(); + assert_eq!(comment.body, "hello"); + // The admin cannot edit someone else's words, but can delete them. + let ada = member("ada", Role::Admin); + assert!(matches!( + store + .edit_comment(&board, &comment.id, &ada, "changed") + .await, + Err(Error::Forbidden(_)) + )); + let bo = member("bo", Role::Member); + let edited = store + .edit_comment(&board, &comment.id, &bo, "edited") + .await + .unwrap(); + assert!(edited.edited_at.is_some()); + store + .delete_comment(&board, &comment.id, &ada) + .await + .unwrap(); + assert!( + store + .list_comments(&board, &task.id) + .await + .unwrap() + .is_empty() + ); + // The activity trail pages newest first with a keyset cursor. + let page = store + .list_recent(&board, &ActivityFilter::default(), None, 2) + .await + .unwrap(); + assert_eq!(page.items.len(), 2); + let next = store + .list_recent( + &board, + &ActivityFilter::default(), + page.next_cursor.as_deref(), + 200, + ) + .await + .unwrap(); + assert!(next.items.iter().all(|a| !page.items.contains(a))); + assert!( + store + .list_recent(&board, &ActivityFilter::default(), None, 0) + .await + .is_err() + ); + } +} diff --git a/crates/iz-core/src/store/members.rs b/crates/iz-core/src/store/members.rs new file mode 100644 index 0000000..9fc689e --- /dev/null +++ b/crates/iz-core/src/store/members.rs @@ -0,0 +1,412 @@ +//! Members: the mirror of the family directory (`im`) plus iz's own state (role, preferences). +//! Directory data is written by `apply_directory_member` (the roster and change stream) and by +//! `upsert_from_claims` (a sign-in, which also stamps `last_sign_in_at`). iz never invents a member: +//! people are added in `im`, and iz only assigns roles. +//! +//! Role changes that remove access also remove the member's assignments and pending reminders in the +//! same transaction, so a viewer or a removed member never keeps a card or a reminder. + +use turso::Connection; +use turso::transaction::Transaction; + +use super::{col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish}; +use crate::authz::Role; +use crate::error::{Error, Result}; +use crate::limits::DISPLAY_NAME_MAX; +use crate::store::Store; +use crate::time::now_stamp; +use crate::zones::parse_zone; + +/// Longest email address accepted from the directory, in characters (RFC 5321 path limit). +const EMAIL_MAX: usize = 320; +/// Theme choices, matching the CHECK constraint. +pub const THEMES: [&str; 3] = ["system", "light", "dark"]; +/// Layout choices, matching the CHECK constraint. +pub const UI_STYLES: [&str; 2] = ["instrument", "ledger"]; +/// Languages iz is translated into. +pub const LOCALES: [&str; 2] = ["en", "tr"]; + +/// One member as stored. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Member { + /// Stable id (the OIDC `sub`). + pub sub: String, + /// Address as the directory has it. + pub email: String, + /// Display name. + pub name: String, + /// Directory flag: this person is an administrator in `im`. + pub im_admin: bool, + /// Disabled in `im` or deleted. A disabled member has no access and is not mailed. + pub disabled: bool, + /// Language from the directory, if any. + pub locale: Option, + /// Language chosen by the member in iz, if any. + pub locale_override: Option, + /// IANA zone name, for example `Europe/Istanbul`. + pub zoneinfo: String, + /// Stored role. + pub role: Role, + /// `system`, `light` or `dark`. + pub theme: String, + /// `instrument` or `ledger`. + pub ui: String, + /// Bumped by the directory when the photo changes; used for avatar caching. + pub picture_version: i64, + /// UTC stamp of the first time the member was seen. + pub first_seen_at: String, + /// UTC stamp of the last sign-in, if any. + pub last_sign_in_at: Option, +} + +/// What the directory (or a sign-in) says about one person. Validated before it is stored. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DirectoryMember { + /// Stable id (the OIDC `sub`). + pub sub: String, + /// Address. + pub email: String, + /// Display name. + pub name: String, + /// Administrator flag in `im`. + pub im_admin: bool, + /// Disabled flag in `im`. + pub disabled: bool, + /// `en`, `tr`, or `None` for anything else. + pub locale: Option, + /// IANA zone name. Must parse. + pub zoneinfo: String, + /// Photo version from `im`. + pub picture_version: i64, +} + +const MEMBER_COLS: &str = "sub, email, name, im_admin, disabled, locale, locale_override, zoneinfo, \ + role, theme, ui, picture_version, first_seen_at, last_sign_in_at"; + +fn map_member(row: &turso::Row) -> Result { + let role_text = col_text(row, 8)?; + let role = Role::parse(&role_text) + .ok_or_else(|| Error::Database(format!("unknown stored role: {role_text}")))?; + Ok(Member { + sub: col_text(row, 0)?, + email: col_text(row, 1)?, + name: col_text(row, 2)?, + im_admin: col_bool(row, 3)?, + disabled: col_bool(row, 4)?, + locale: col_opt_text(row, 5)?, + locale_override: col_opt_text(row, 6)?, + zoneinfo: col_text(row, 7)?, + role, + theme: col_text(row, 9)?, + ui: col_text(row, 10)?, + picture_version: col_int(row, 11)?, + first_seen_at: col_text(row, 12)?, + last_sign_in_at: col_opt_text(row, 13)?, + }) +} + +/// Checks a directory record and returns the normalised copy to store. +fn validate(m: &DirectoryMember) -> Result { + let sub = m.sub.trim(); + let email = m.email.trim(); + let name = m.name.trim(); + if sub.is_empty() || sub.len() > 64 { + return Err(Error::Invalid( + "member id must be 1 to 64 characters".into(), + )); + } + if email.is_empty() || email.chars().count() > EMAIL_MAX { + return Err(Error::Invalid( + "member email must be 1 to 320 characters".into(), + )); + } + if name.is_empty() || name.chars().count() > DISPLAY_NAME_MAX { + return Err(Error::Invalid( + "member name must be 1 to 100 characters".into(), + )); + } + if m.picture_version < 0 { + return Err(Error::Invalid( + "picture version must not be negative".into(), + )); + } + let zone = parse_zone(&m.zoneinfo)?; + let zoneinfo = zone + .iana_name() + .map(str::to_owned) + .unwrap_or_else(|| m.zoneinfo.trim().to_owned()); + Ok(DirectoryMember { + sub: sub.to_owned(), + email: email.to_owned(), + name: name.to_owned(), + im_admin: m.im_admin, + disabled: m.disabled, + locale: m.locale.clone().filter(|l| LOCALES.contains(&l.as_str())), + zoneinfo, + picture_version: m.picture_version, + }) +} + +async fn select_member(conn: &Connection, sub: &str) -> Result> { + fetch_opt( + conn, + &format!("SELECT {MEMBER_COLS} FROM members WHERE sub = ?1"), + (sub.to_owned(),), + map_member, + ) + .await +} + +/// Removes a member's assignments and pending (unsent) reminders, inside `tx`. +async fn drop_assignments(tx: &Transaction<'_>, sub: &str) -> Result<()> { + tx.execute( + "DELETE FROM task_assignees WHERE sub = ?1", + (sub.to_owned(),), + ) + .await + .map_err(db_err)?; + tx.execute( + "DELETE FROM reminders WHERE sub = ?1 AND sent_at IS NULL", + (sub.to_owned(),), + ) + .await + .map_err(db_err)?; + Ok(()) +} + +impl Store { + /// Creates or refreshes a member from the directory. A new member gets `default_role`; an + /// existing member keeps their role and preferences. Returns the stored row. + pub async fn apply_directory_member( + &self, + member: &DirectoryMember, + default_role: Role, + ) -> Result { + self.upsert_member(member, default_role, false).await + } + + /// Creates or refreshes a member at sign-in (from the ID token claims) and stamps the sign-in time. + pub async fn upsert_from_claims( + &self, + member: &DirectoryMember, + default_role: Role, + ) -> Result { + self.upsert_member(member, default_role, true).await + } + + async fn upsert_member( + &self, + member: &DirectoryMember, + default_role: Role, + signed_in: bool, + ) -> Result { + let m = validate(member)?; + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + tx.execute( + "INSERT INTO members (sub, email, name, im_admin, disabled, locale, zoneinfo, \ + picture_version, im_updated_at, role, first_seen_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?9) \ + ON CONFLICT(sub) DO UPDATE SET email = excluded.email, name = excluded.name, \ + im_admin = excluded.im_admin, disabled = excluded.disabled, \ + locale = excluded.locale, zoneinfo = excluded.zoneinfo, \ + picture_version = excluded.picture_version, im_updated_at = excluded.im_updated_at", + ( + m.sub.clone(), + m.email.clone(), + m.name.clone(), + i64::from(m.im_admin), + i64::from(m.disabled), + m.locale.clone(), + m.zoneinfo.clone(), + m.picture_version, + now.clone(), + default_role.as_str(), + ), + ) + .await + .map_err(db_err)?; + if signed_in { + tx.execute( + "UPDATE members SET last_sign_in_at = ?2 WHERE sub = ?1", + (m.sub.clone(), now.clone()), + ) + .await + .map_err(db_err)?; + } + select_member(&tx, &m.sub) + .await? + .ok_or_else(|| Error::Database("member vanished after upsert".into())) + } + .await; + finish(tx, outcome).await + } + + /// Marks a member as deleted in the directory: disabled, role `none`. Their assignments and pending + /// reminders are removed in the same transaction. Unknown members are `NotFound`. + pub async fn mark_deleted(&self, sub: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let changed = tx + .execute( + "UPDATE members SET disabled = 1, role = 'none' WHERE sub = ?1", + (sub.to_owned(),), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + drop_assignments(&tx, sub).await + } + .await; + finish(tx, outcome).await + } + + /// One member by id, or `None`. + pub async fn member(&self, sub: &str) -> Result> { + let conn = self.read_conn().await; + select_member(&conn, sub).await + } + + /// Every member, by name. + pub async fn list_members(&self) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!("SELECT {MEMBER_COLS} FROM members ORDER BY name COLLATE NOCASE, sub"), + (), + map_member, + ) + .await + } + + /// Sets a member's role. Refuses to remove the last active administrator: an administrator is a + /// member with role `admin` or the directory admin flag, who is not disabled. The check is part + /// of the same conditional UPDATE, so two demotions cannot both pass. + /// + /// Moving to `viewer` or `none` also removes the member's assignments and pending reminders. + pub async fn set_role(&self, sub: &str, role: Role) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let changed = tx + .execute( + "UPDATE members SET role = ?2 WHERE sub = ?1 AND (?2 = 'admin' OR EXISTS ( \ + SELECT 1 FROM members other WHERE other.sub <> ?1 AND other.disabled = 0 \ + AND (other.im_admin = 1 OR other.role = 'admin')))", + (sub.to_owned(), role.as_str()), + ) + .await + .map_err(db_err)?; + if changed == 0 { + if select_member(&tx, sub).await?.is_none() { + return Err(Error::NotFound); + } + return Err(Error::Conflict( + "the last administrator cannot be demoted".into(), + )); + } + if matches!(role, Role::Viewer | Role::NoAccess) { + drop_assignments(&tx, sub).await?; + } + Ok(()) + } + .await; + finish(tx, outcome).await + } + + /// Stores a member's own preferences. Values are checked here as well as by the schema, so the + /// user gets a message instead of a constraint error. + pub async fn set_preferences( + &self, + sub: &str, + theme: &str, + ui: &str, + locale_override: Option<&str>, + ) -> Result<()> { + if !THEMES.contains(&theme) { + return Err(Error::Invalid(format!("unknown theme: {theme}"))); + } + if !UI_STYLES.contains(&ui) { + return Err(Error::Invalid(format!("unknown layout: {ui}"))); + } + if let Some(locale) = locale_override.filter(|l| !LOCALES.contains(l)) { + return Err(Error::Invalid(format!("unknown language: {locale}"))); + } + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE members SET theme = ?2, ui = ?3, locale_override = ?4 WHERE sub = ?1", + ( + sub.to_owned(), + theme.to_owned(), + ui.to_owned(), + locale_override.map(str::to_owned), + ), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn validation_normalises_zone_and_drops_unknown_locale() { + let raw = DirectoryMember { + sub: " u1 ".into(), + email: "a@example.com".into(), + name: " Ada ".into(), + im_admin: false, + disabled: false, + locale: Some("de".into()), + zoneinfo: "Europe/Istanbul".into(), + picture_version: 0, + }; + let v = validate(&raw).unwrap(); + assert_eq!(v.sub, "u1"); + assert_eq!(v.name, "Ada"); + assert_eq!(v.locale, None); + assert_eq!(v.zoneinfo, "Europe/Istanbul"); + let bad = DirectoryMember { + zoneinfo: "Mars/Base".into(), + ..raw + }; + assert!(validate(&bad).is_err()); + } + + #[tokio::test] + async fn last_administrator_cannot_be_demoted() { + let (_dir, store, _board) = crate::store::test_support::seeded().await; + // `ada` is the only admin, so she cannot step down; `bo` is a member and can be promoted. + assert!(matches!( + store.set_role("ada", Role::Viewer).await, + Err(Error::Conflict(_)) + )); + store.set_role("bo", Role::Admin).await.unwrap(); + store.set_role("ada", Role::Viewer).await.unwrap(); + assert_eq!( + store.member("ada").await.unwrap().unwrap().role, + Role::Viewer + ); + // Now `bo` is the last one. + assert!(matches!( + store.set_role("bo", Role::Member).await, + Err(Error::Conflict(_)) + )); + assert!(matches!( + store.set_role("nobody", Role::Member).await, + Err(Error::NotFound) + )); + } +} diff --git a/crates/iz-core/src/store/mod.rs b/crates/iz-core/src/store/mod.rs index 3c5393e..4b488ed 100644 --- a/crates/iz-core/src/store/mod.rs +++ b/crates/iz-core/src/store/mod.rs @@ -1,21 +1,30 @@ -//! Turso-backed storage. All metadata lives here. Only the settings functions exist so far; the -//! table modules come with the features that use them. +//! Turso-backed storage. All metadata lives here: members and sessions, the board (columns, tags), +//! tasks with their links, comments and activity. Each table group is a child module; this file has +//! the connections, the settings, and the helpers every module uses. //! //! Connections: `conn` is the single writer. Every write, every transaction and every //! read-then-write sequence runs on it behind its tokio mutex, so transactions never interleave. //! `readers` is a small pool of `query_only` connections on the same database (WAL), so pure //! SELECTs run in parallel with each other and with the writer. +pub mod activity; +pub mod board; +pub mod comments; +pub mod members; pub mod migrate; +pub mod sessions; pub mod snapshot; +pub mod tasks; use std::path::Path; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; +use time::OffsetDateTime; use tokio::sync::{Mutex, MutexGuard}; use turso::{Builder, Connection, Database, IntoParams, Row, Value}; +use ulid::Ulid; use crate::error::{Error, Result}; use crate::time::now_stamp; @@ -214,6 +223,45 @@ where } } +/// A fresh ULID as text: 48 bits of millisecond time, then 80 random bits. Sorts by creation time. +pub fn new_id() -> String { + let millis = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000; + let millis = u64::try_from(millis).unwrap_or(0); + let mut buf = [0u8; 16]; + rand::fill(&mut buf); + let random = u128::from_le_bytes(buf) & ((1u128 << 80) - 1); + Ulid::from_parts(millis, random).to_string() +} + +/// A nullable text column: `None` for NULL. +pub fn col_opt_text(row: &Row, i: usize) -> Result> { + match row.get_value(i).map_err(db_err)? { + Value::Null => Ok(None), + Value::Text(s) => Ok(Some(s)), + _ => Err(Error::Database(format!("column {i} is not text"))), + } +} + +/// A 0/1 integer column as a bool. Any other value is a database error. +pub fn col_bool(row: &Row, i: usize) -> Result { + match col_int(row, i)? { + 0 => Ok(false), + 1 => Ok(true), + other => Err(Error::Database(format!( + "column {i} is {other}, not 0 or 1" + ))), + } +} + +/// A REAL (floating point) column. Integers are accepted and widened, as SQLite allows either. +pub fn col_real(row: &Row, i: usize) -> Result { + match row.get_value(i).map_err(db_err)? { + Value::Real(f) => Ok(f), + Value::Integer(n) => Ok(n as f64), + _ => Err(Error::Database(format!("column {i} is not a number"))), + } +} + /// A text column. NULL and other types are a database error here; use a nullable reader for NULLs. pub fn col_text(row: &Row, i: usize) -> Result { match row.get_value(i).map_err(db_err)? { @@ -241,6 +289,36 @@ pub fn col_to_string(row: &Row, i: usize) -> Result { } } +/// Test fixtures shared by the store modules: a fresh database in a temp dir, one board, and two members. +#[cfg(test)] +pub(crate) mod test_support { + use super::Store; + use super::members::DirectoryMember; + use crate::authz::Role; + + /// A store with a board and two members: `ada` (admin) and `bo` (member). Keep the returned temp dir + /// alive for as long as the store is used. + pub(crate) async fn seeded() -> (tempfile::TempDir, Store, String) { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("iz.db")).await.unwrap(); + let board = store.ensure_board("IZ").await.unwrap(); + for (sub, role) in [("ada", Role::Admin), ("bo", Role::Member)] { + let member = DirectoryMember { + sub: sub.into(), + email: format!("{sub}@example.com"), + name: sub.into(), + im_admin: false, + disabled: false, + locale: None, + zoneinfo: "UTC".into(), + picture_version: 0, + }; + store.apply_directory_member(&member, role).await.unwrap(); + } + (dir, store, board.id) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/iz-core/src/store/sessions.rs b/crates/iz-core/src/store/sessions.rs new file mode 100644 index 0000000..4b04988 --- /dev/null +++ b/crates/iz-core/src/store/sessions.rs @@ -0,0 +1,245 @@ +//! Local sessions (docs/contracts.md 2.4) and the replay guard for back-channel logout tokens. +//! +//! The cookie token is random; only its SHA-256 is stored, so a leaked table cannot be replayed. +//! A session is valid only while it is unexpired and its member is enabled and has a role other than +//! `none`. Lookups repeat those checks in SQL, so disabling a member takes effect on the next request +//! even if the back-channel message was lost. + +use std::time::Duration; + +use super::{col_opt_text, col_text, db_err, fetch_opt, new_id}; +use crate::error::{Error, Result}; +use crate::store::Store; +use crate::time::{now_stamp, stamp_after}; +use crate::token::{generate_token, hash_token}; + +/// A session as the web layer needs it after a lookup. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SessionRecord { + /// Session id (ULID). + pub id: String, + /// The member the session belongs to. + pub sub: String, + /// The per-session CSRF token that every state-changing form must carry. + pub csrf_token: String, + /// The im browser session id, used by back-channel logout. + pub sid: Option, + /// UTC stamp after which the session is refused. + pub expires_at: String, + /// UTC stamp of the last request that used the session. + pub last_seen: String, +} + +/// A freshly created session. `token` goes into the cookie and is never stored. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IssuedSession { + /// Session id. + pub id: String, + /// Cookie value (43 characters). Shown once. + pub token: String, + /// CSRF token for forms in this session. + pub csrf_token: String, +} + +const SESSION_COLS: &str = "s.id, s.sub, s.csrf_token, s.sid, s.expires_at, s.last_seen"; + +fn map_session(row: &turso::Row) -> Result { + Ok(SessionRecord { + id: col_text(row, 0)?, + sub: col_text(row, 1)?, + csrf_token: col_text(row, 2)?, + sid: col_opt_text(row, 3)?, + expires_at: col_text(row, 4)?, + last_seen: col_text(row, 5)?, + }) +} + +impl Store { + /// Creates a session for `sub` that lasts `lifetime`. The member must be enabled and have a role + /// other than `none`; otherwise nothing is written and the result is `Forbidden`. + pub async fn create_session( + &self, + sub: &str, + sid: Option<&str>, + lifetime: Duration, + user_agent: Option<&str>, + ip: Option<&str>, + ) -> Result { + let token = generate_token(); + let csrf_token = generate_token(); + let id = new_id(); + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "INSERT INTO sessions (id, sub, token_hash, csrf_token, sid, created_at, expires_at, \ + last_seen, user_agent, ip) \ + SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?6, ?8, ?9 FROM members \ + WHERE sub = ?2 AND disabled = 0 AND role <> 'none'", + ( + id.clone(), + sub.to_owned(), + hash_token(&token), + csrf_token.clone(), + sid.map(str::to_owned), + now, + stamp_after(lifetime), + user_agent.map(str::to_owned), + ip.map(str::to_owned), + ), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::Forbidden("this account cannot sign in".into())); + } + Ok(IssuedSession { + id, + token, + csrf_token, + }) + } + + /// The live session for a cookie token: unexpired, member enabled, role not `none`. `None` otherwise, + /// with no hint about which check failed. + pub async fn session_by_token(&self, token: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!( + "SELECT {SESSION_COLS} FROM sessions s JOIN members m ON m.sub = s.sub \ + WHERE s.token_hash = ?1 AND s.expires_at > ?2 AND m.disabled = 0 AND m.role <> 'none'" + ), + (hash_token(token), now_stamp()), + map_session, + ) + .await + } + + /// Records that a session was used now. + pub async fn touch_session(&self, id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE sessions SET last_seen = ?2 WHERE id = ?1", + (id.to_owned(), now_stamp()), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Deletes one session. Returns whether a row was removed. + pub async fn delete_session(&self, id: &str) -> Result { + let conn = self.inner.conn.lock().await; + let removed = conn + .execute("DELETE FROM sessions WHERE id = ?1", (id.to_owned(),)) + .await + .map_err(db_err)?; + Ok(removed > 0) + } + + /// Deletes every session that belongs to the im browser session `sid` (back-channel logout). + /// Returns how many were removed. + pub async fn delete_sessions_by_sid(&self, sid: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute("DELETE FROM sessions WHERE sid = ?1", (sid.to_owned(),)) + .await + .map_err(db_err) + } + + /// Deletes every session of one member (disabled, deleted, or password changed). Returns the count. + pub async fn delete_sessions_by_sub(&self, sub: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute("DELETE FROM sessions WHERE sub = ?1", (sub.to_owned(),)) + .await + .map_err(db_err) + } + + /// Deletes sessions whose expiry has passed. Returns the count. + pub async fn sweep_sessions(&self) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM sessions WHERE expires_at <= ?1", + (now_stamp(),), + ) + .await + .map_err(db_err) + } + + /// Records a logout-token id. Returns `true` when the id was already recorded (a replay, which the + /// caller must refuse) and `false` when this is its first use. The record lives for `lifetime`. + pub async fn seen_jti(&self, jti: &str, lifetime: Duration) -> Result { + let conn = self.inner.conn.lock().await; + let inserted = conn + .execute( + "INSERT INTO seen_logout_jti (jti, expires_at) VALUES (?1, ?2) ON CONFLICT(jti) DO NOTHING", + (jti.to_owned(), stamp_after(lifetime)), + ) + .await + .map_err(db_err)?; + Ok(inserted == 0) + } + + /// Deletes replay records whose lifetime has passed. Returns the count. + pub async fn sweep_jti(&self) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM seen_logout_jti WHERE expires_at <= ?1", + (now_stamp(),), + ) + .await + .map_err(db_err) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::store::test_support::seeded; + + #[tokio::test] + async fn sessions_follow_member_state_and_jti_is_single_use() { + let (_dir, store, _board) = seeded().await; + let issued = store + .create_session("bo", Some("sid-1"), Duration::from_secs(3600), None, None) + .await + .unwrap(); + let found = store + .session_by_token(&issued.token) + .await + .unwrap() + .unwrap(); + assert_eq!(found.sub, "bo"); + assert_eq!(found.csrf_token, issued.csrf_token); + // Back-channel logout by sid removes the session. + assert_eq!(store.delete_sessions_by_sid("sid-1").await.unwrap(), 1); + assert!( + store + .session_by_token(&issued.token) + .await + .unwrap() + .is_none() + ); + // A member with role none cannot start a session at all. + store.mark_deleted("bo").await.unwrap(); + assert!(matches!( + store + .create_session("bo", None, Duration::from_secs(60), None, None) + .await, + Err(Error::Forbidden(_)) + )); + // A logout token id is accepted once; the replay is reported. + assert!( + !store + .seen_jti("jti-1", Duration::from_secs(600)) + .await + .unwrap() + ); + assert!( + store + .seen_jti("jti-1", Duration::from_secs(600)) + .await + .unwrap() + ); + } +} diff --git a/crates/iz-core/src/store/tasks.rs b/crates/iz-core/src/store/tasks.rs new file mode 100644 index 0000000..ba049d9 --- /dev/null +++ b/crates/iz-core/src/store/tasks.rs @@ -0,0 +1,1585 @@ +//! Tasks: creation, edits, moves through columns, deletion, assignees, one level of subtasks, +//! dependencies, and the board and task reads. +//! +//! Every write that touches more than one row runs in one transaction with its activity rows and, +//! for a move, its transition row. Board scope is part of every `WHERE` (`board_id = ?`), so a task id +//! from another board is simply not found. Reminders (inventory 2.4) are rebuilt inside the same +//! transaction whenever the meeting time, the assignees, the done state or the deletion changes. + +use std::collections::{HashMap, HashSet}; + +use jiff::Timestamp; +use jiff::civil::Date; +use jiff::tz::TimeZone; +use turso::Connection; +use turso::transaction::Transaction; + +use super::activity::{self, NewActivity}; +use super::board::{Column, Tag, column_in, live_columns}; +use super::{ + col_int, col_opt_text, col_real, col_text, db_err, fetch_all, fetch_opt, finish, new_id, +}; +use crate::board::{fold_for_search, format_key, is_overdue, position_between, would_cycle}; +use crate::clock::{reminder_due, timestamp_of}; +use crate::error::{Error, Result}; +use crate::limits::{DESCRIPTION_MAX, TITLE_MAX}; +use crate::store::Store; +use crate::time::now_stamp; + +/// A task row as read back. Deadline and meeting are typed; the rest is text or numbers. +#[derive(Debug, Clone, PartialEq)] +pub struct Task { + /// Task id (ULID). + pub id: String, + /// Board the task belongs to. + pub board_id: String, + /// Readable key `PREFIX-n`, unique per board, never reused. + pub key: String, + /// The parent task, for a subtask. + pub parent_id: Option, + /// Title, 1 to 200 characters. + pub title: String, + /// Free text, at most 20 000 characters. + pub description: String, + /// The column the task is in. + pub column_id: String, + /// The project (tag) the task wears. + pub tag_id: String, + /// The deadline day, if any. + pub deadline: Option, + /// The meeting instant as a UTC stamp, if any. + pub meeting_at: Option, + /// Order within the column. + pub position: f64, + /// Who created the task. + pub created_by: String, + /// UTC stamp. + pub created_at: String, + /// UTC stamp of the last change. + pub updated_at: String, + /// UTC stamp of entering the done column; cleared on leaving it. + pub done_at: Option, + /// UTC stamp of deletion (soft delete). Deleted tasks are hidden everywhere. + pub deleted_at: Option, +} + +/// A person assigned to a task. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Assignee { + /// The member's id. + pub sub: String, + /// The member's display name. + pub name: String, +} + +/// Which way a dependency link points, seen from the new task. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LinkDirection { + /// The new task waits for the other task. + BlockedBy, + /// The other task waits for the new task. + Blocks, +} + +/// Everything needed to create a task. Deadline and meeting are already resolved (see `clock.rs`). +#[derive(Debug, Clone, PartialEq)] +pub struct NewTask { + /// Title (trimmed, 1 to 200 characters). + pub title: String, + /// Description (at most 20 000 characters). + pub description: String, + /// Column to place the task in. Must be live on this board. + pub column_id: String, + /// Project. Must belong to this board. + pub tag_id: String, + /// Deadline day. + pub deadline: Option, + /// Meeting instant (UTC stamp). + pub meeting_at: Option, + /// Assignees. Each must be an enabled admin or member. + pub assignees: Vec, + /// Parent task, for a subtask. Must be a live top-level task on this board. + pub parent_id: Option, + /// Optional dependency link to another task of this board. + pub link: Option<(String, LinkDirection)>, +} + +/// The editable fields of a task. The form sends all of them, so each is replaced as a whole. +#[derive(Debug, Clone, PartialEq)] +pub struct TaskEdit { + /// New title. + pub title: String, + /// New description. + pub description: String, + /// New project. + pub tag_id: String, + /// New deadline day. + pub deadline: Option, + /// New meeting instant (UTC stamp). + pub meeting_at: Option, +} + +/// The result of a move. Only `Moved` changes anything. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MoveOutcome { + /// The task is now in the target column. + Moved, + /// The task was already in the target column. + Unchanged, + /// The task is no longer in the column the client last saw; someone else moved it. + Stale, + /// The target is the done column and the task has subtasks that are not done. + SubtasksOpen, +} + +/// Sorting of the board's cards. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum SortBy { + /// Earliest deadline first; tasks without a deadline last. + #[default] + Deadline, + /// Newest first. + Created, + /// Alphabetical by title, ignoring case and Turkish dotted/dotless i. + Title, +} + +/// Who a board filter means when it names an assignee. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AssigneeFilter { + /// Tasks with nobody assigned. + Nobody, + /// Tasks assigned to this member. + Member(String), +} + +/// Filters and sorting for the board. Every field is optional; the default shows everything. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct BoardFilter { + /// Only this project. + pub tag_id: Option, + /// Only this assignee (or nobody). + pub assignee: Option, + /// Text to search for in key, title and description (case and Turkish-i insensitive). + pub query: Option, + /// Card order. + pub sort: SortBy, +} + +/// One card on the board. +#[derive(Debug, Clone, PartialEq)] +pub struct Card { + /// The task. + pub task: Task, + /// The project's name. + pub tag_name: String, + /// Not done, and waiting for a blocker that is not done. + pub blocked: bool, + /// Overdue for the viewer (see `board::is_overdue`). + pub overdue: bool, + /// Subtasks that are done. + pub subtasks_done: i64, + /// Subtasks in total (live ones). + pub subtasks_total: i64, + /// Live comments. + pub comments: i64, + /// Assignees, by name. + pub assignees: Vec, +} + +/// One column with its cards in order. +#[derive(Debug, Clone, PartialEq)] +pub struct ColumnCards { + /// The live column. + pub column: Column, + /// Its cards, sorted by the filter's order. + pub cards: Vec, +} + +/// The whole board for one viewer. +#[derive(Debug, Clone, PartialEq)] +pub struct BoardView { + /// Live columns in order. + pub columns: Vec, + /// Overdue cards among those shown. + pub overdue: usize, + /// Blocked cards among those shown. + pub blocked: usize, +} + +/// One task with its context, for the task modal. +#[derive(Debug, Clone, PartialEq)] +pub struct TaskDetail { + /// The task. + pub task: Task, + /// Its project. + pub tag: Tag, + /// Its assignees, by name. + pub assignees: Vec, + /// Its live subtasks, in position order. + pub subtasks: Vec, + /// Live tasks it waits for (uncleared links). + pub blocked_by: Vec, + /// Live tasks waiting for it (uncleared links). + pub blocks: Vec, +} + +const TASK_COLS: &str = "id, board_id, key, parent_id, title, description, column_id, tag_id, \ + deadline, meeting_at, position, created_by, created_at, updated_at, done_at, deleted_at"; + +/// The same columns qualified with the alias `t`, for joins. +const TASK_COLS_T: &str = "t.id, t.board_id, t.key, t.parent_id, t.title, t.description, t.column_id, \ + t.tag_id, t.deadline, t.meeting_at, t.position, t.created_by, t.created_at, t.updated_at, \ + t.done_at, t.deleted_at"; + +fn parse_date(text: &str) -> Result { + text.parse::() + .map_err(|e| Error::Database(format!("stored deadline is not a date: {e}"))) +} + +fn map_task(row: &turso::Row) -> Result { + let deadline = col_opt_text(row, 8)? + .as_deref() + .map(parse_date) + .transpose()?; + Ok(Task { + id: col_text(row, 0)?, + board_id: col_text(row, 1)?, + key: col_text(row, 2)?, + parent_id: col_opt_text(row, 3)?, + title: col_text(row, 4)?, + description: col_text(row, 5)?, + column_id: col_text(row, 6)?, + tag_id: col_text(row, 7)?, + deadline, + meeting_at: col_opt_text(row, 9)?, + position: col_real(row, 10)?, + created_by: col_text(row, 11)?, + created_at: col_text(row, 12)?, + updated_at: col_text(row, 13)?, + done_at: col_opt_text(row, 14)?, + deleted_at: col_opt_text(row, 15)?, + }) +} + +fn map_assignee(row: &turso::Row) -> Result<(String, Assignee)> { + Ok(( + col_text(row, 0)?, + Assignee { + sub: col_text(row, 1)?, + name: col_text(row, 2)?, + }, + )) +} + +fn clean_title(title: &str) -> Result { + let title = title.trim(); + if title.is_empty() || title.chars().count() > TITLE_MAX { + return Err(Error::Invalid(format!( + "title must be 1 to {TITLE_MAX} characters" + ))); + } + Ok(title.to_owned()) +} + +fn clean_description(description: &str) -> Result { + if description.chars().count() > DESCRIPTION_MAX { + return Err(Error::Invalid(format!( + "description must be at most {DESCRIPTION_MAX} characters" + ))); + } + Ok(description.to_owned()) +} + +/// Removes repeats while keeping the first occurrence of each id. +fn unique(ids: &[String]) -> Vec { + let mut seen = HashSet::new(); + ids.iter() + .filter(|id| seen.insert(id.as_str())) + .cloned() + .collect() +} + +/// A live task of `board_id`, or `NotFound`. Deleted and foreign tasks are both `NotFound`. +async fn live_task(conn: &Connection, board_id: &str, task_id: &str) -> Result { + fetch_opt( + conn, + &format!( + "SELECT {TASK_COLS} FROM tasks WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL" + ), + (task_id.to_owned(), board_id.to_owned()), + map_task, + ) + .await? + .ok_or(Error::NotFound) +} + +/// Any task of `board_id`, deleted or not. +async fn task_row(conn: &Connection, board_id: &str, task_id: &str) -> Result> { + fetch_opt( + conn, + &format!("SELECT {TASK_COLS} FROM tasks WHERE id = ?1 AND board_id = ?2"), + (task_id.to_owned(), board_id.to_owned()), + map_task, + ) + .await +} + +/// Whether a member may be assigned: enabled, and role `admin` or `member`. +async fn assignable(conn: &Connection, sub: &str) -> Result { + let found = fetch_opt( + conn, + "SELECT 1 FROM members WHERE sub = ?1 AND disabled = 0 AND role IN ('admin', 'member')", + (sub.to_owned(),), + |row| col_int(row, 0), + ) + .await?; + Ok(found.is_some()) +} + +async fn tag_in_board(conn: &Connection, board_id: &str, tag_id: &str) -> Result { + let found = fetch_opt( + conn, + "SELECT 1 FROM tags WHERE id = ?1 AND board_id = ?2", + (tag_id.to_owned(), board_id.to_owned()), + |row| col_int(row, 0), + ) + .await?; + Ok(found.is_some()) +} + +/// Uncleared links between live tasks of the board, as `(blocked, blocking)`. +async fn live_edges(conn: &Connection, board_id: &str) -> Result> { + fetch_all( + conn, + "SELECT d.blocked_id, d.blocking_id FROM dependencies d \ + JOIN tasks blocked ON blocked.id = d.blocked_id \ + JOIN tasks blocking ON blocking.id = d.blocking_id \ + WHERE blocked.board_id = ?1 AND d.cleared_at IS NULL \ + AND blocked.deleted_at IS NULL AND blocking.deleted_at IS NULL", + (board_id.to_owned(),), + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), + ) + .await +} + +/// Position for a task appended to the end of a column: after the largest live position there. +async fn next_position(conn: &Connection, column_id: &str) -> Result { + let positions = fetch_all( + conn, + "SELECT position FROM tasks WHERE column_id = ?1 AND deleted_at IS NULL", + (column_id.to_owned(),), + |row| col_real(row, 0), + ) + .await?; + let last = positions.into_iter().reduce(f64::max); + Ok(position_between(last, None)) +} + +/// Appends a row to the transitions table. `from` is `None` for the first placement. +async fn record_transition( + tx: &Transaction<'_>, + task_id: &str, + from: Option<&str>, + to: &str, + actor: &str, +) -> Result<()> { + tx.execute( + "INSERT INTO transitions (id, task_id, from_column, to_column, actor, at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + ( + new_id(), + task_id.to_owned(), + from.map(str::to_owned), + to.to_owned(), + actor.to_owned(), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) +} + +/// Writes one task-scoped activity row. +async fn log( + tx: &Transaction<'_>, + task_id: &str, + actor: &str, + kind: &'static str, + subject: Option<&str>, + detail: serde_json::Value, +) -> Result<()> { + activity::record( + tx, + NewActivity { + task_id: Some(task_id), + actor: Some(actor), + subject, + kind, + detail, + }, + ) + .await +} + +/// Rebuilds the pending reminders of one task (inventory 2.4): one per assignee, due a fixed lead time +/// before the meeting. Sent reminders are kept. None are made when the task is done, deleted, has no +/// meeting, or its meeting is in the past. +async fn sync_reminders(tx: &Transaction<'_>, task_id: &str) -> Result<()> { + tx.execute( + "DELETE FROM reminders WHERE task_id = ?1 AND sent_at IS NULL", + (task_id.to_owned(),), + ) + .await + .map_err(db_err)?; + let state = fetch_opt( + tx, + "SELECT meeting_at, done_at, deleted_at FROM tasks WHERE id = ?1", + (task_id.to_owned(),), + |row| { + Ok(( + col_opt_text(row, 0)?, + col_opt_text(row, 1)?, + col_opt_text(row, 2)?, + )) + }, + ) + .await?; + let Some((Some(meeting), None, None)) = state else { + return Ok(()); + }; + let at = timestamp_of(&meeting)?; + if at <= Timestamp::now() { + return Ok(()); + } + let due = reminder_due(at)?; + tx.execute( + "INSERT INTO reminders (task_id, sub, due_at, sent_at) \ + SELECT a.task_id, a.sub, ?2, NULL FROM task_assignees a \ + WHERE a.task_id = ?1 AND EXISTS ( \ + SELECT 1 FROM members m WHERE m.sub = a.sub AND m.disabled = 0 AND m.role IN ('admin', 'member')) \ + ON CONFLICT(task_id, sub) DO NOTHING", + (task_id.to_owned(), due), + ) + .await + .map_err(db_err)?; + Ok(()) +} + +impl Store { + /// Creates a task with everything it starts with, in one transaction: the key (from the board's + /// counter, never reused), the placement, the assignees, the optional subtask parent and the optional + /// dependency link, with their activity rows and the first transition. Any refusal rolls all of it back, + /// so no half-made card is left behind. A link that would close a cycle is refused. + pub async fn create_task(&self, board_id: &str, new: NewTask, actor: &str) -> Result { + let title = clean_title(&new.title)?; + let description = clean_description(&new.description)?; + let assignees = unique(&new.assignees); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let column = column_in(&tx, board_id, &new.column_id) + .await? + .filter(|c| c.deleted_at.is_none()) + .ok_or_else(|| Error::Invalid("that column does not exist".into()))?; + if !tag_in_board(&tx, board_id, &new.tag_id).await? { + return Err(Error::Invalid("that project does not exist".into())); + } + if let Some(parent) = &new.parent_id { + let row = task_row(&tx, board_id, parent) + .await? + .filter(|p| p.deleted_at.is_none()) + .ok_or_else(|| Error::Invalid("the parent task does not exist".into()))?; + if row.parent_id.is_some() { + return Err(Error::Invalid("subtasks may only be one level deep".into())); + } + } + for sub in &assignees { + if !assignable(&tx, sub).await? { + return Err(Error::Invalid("that person cannot be assigned".into())); + } + } + let (prefix, number) = fetch_opt( + &tx, + "SELECT key_prefix, next_task_number FROM boards WHERE id = ?1", + (board_id.to_owned(),), + |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), + ) + .await? + .ok_or(Error::NotFound)?; + tx.execute( + "UPDATE boards SET next_task_number = ?2 WHERE id = ?1", + (board_id.to_owned(), number + 1), + ) + .await + .map_err(db_err)?; + let key = format_key(&prefix, u64::try_from(number).unwrap_or(0)); + let id = new_id(); + let now = now_stamp(); + let done_at = column.is_done.then(|| now.clone()); + let position = next_position(&tx, &column.id).await?; + tx.execute( + "INSERT INTO tasks (id, board_id, key, parent_id, title, description, column_id, tag_id, \ + deadline, meeting_at, position, created_by, created_at, updated_at, done_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?13, ?14)", + ( + id.clone(), + board_id.to_owned(), + key.clone(), + new.parent_id.clone(), + title.clone(), + description, + column.id.clone(), + new.tag_id.clone(), + new.deadline.map(|d| d.to_string()), + new.meeting_at.clone(), + position, + actor.to_owned(), + now, + done_at, + ), + ) + .await + .map_err(db_err)?; + if let Some((other, direction)) = &new.link { + if live_task(&tx, board_id, other).await.is_err() { + return Err(Error::Invalid("the linked task does not exist".into())); + } + let (blocked, blocking) = match direction { + LinkDirection::BlockedBy => (id.as_str(), other.as_str()), + LinkDirection::Blocks => (other.as_str(), id.as_str()), + }; + let edges = live_edges(&tx, board_id).await?; + let refs: Vec<(&str, &str)> = + edges.iter().map(|(a, b)| (a.as_str(), b.as_str())).collect(); + if would_cycle(&refs, (blocked, blocking)) { + return Err(Error::Conflict("this link would make a dependency cycle".into())); + } + tx.execute( + "INSERT INTO dependencies (blocked_id, blocking_id, created_at) VALUES (?1, ?2, ?3)", + (blocked.to_owned(), blocking.to_owned(), now_stamp()), + ) + .await + .map_err(db_err)?; + let direction_text = match direction { + LinkDirection::BlockedBy => "blocked_by", + LinkDirection::Blocks => "blocks", + }; + log( + &tx, + &id, + actor, + "link_added", + None, + serde_json::json!({ "other": other, "direction": direction_text }), + ) + .await?; + } + for sub in &assignees { + tx.execute( + "INSERT INTO task_assignees (task_id, sub, assigned_at) VALUES (?1, ?2, ?3)", + (id.clone(), sub.clone(), now_stamp()), + ) + .await + .map_err(db_err)?; + log(&tx, &id, actor, "assigned", Some(sub), serde_json::json!({})).await?; + } + log( + &tx, + &id, + actor, + "task_created", + None, + serde_json::json!({ "key": key, "title": title }), + ) + .await?; + record_transition(&tx, &id, None, &column.id, actor).await?; + sync_reminders(&tx, &id).await?; + live_task(&tx, board_id, &id).await + } + .await; + finish(tx, outcome).await + } + + /// Edits a task's title, description, project, deadline and meeting time. Writes one activity row per + /// kind of change (`task_edited`, `tag_changed`, `deadline_set`, `deadline_cleared`, `clock_set`, + /// `clock_cleared`). Reminders are rebuilt when the meeting time changes. + pub async fn edit_task( + &self, + board_id: &str, + task_id: &str, + edit: TaskEdit, + actor: &str, + ) -> Result { + let title = clean_title(&edit.title)?; + let description = clean_description(&edit.description)?; + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let before = live_task(&tx, board_id, task_id).await?; + if !tag_in_board(&tx, board_id, &edit.tag_id).await? { + return Err(Error::Invalid("that project does not exist".into())); + } + let deadline = edit.deadline.map(|d| d.to_string()); + tx.execute( + "UPDATE tasks SET title = ?3, description = ?4, tag_id = ?5, deadline = ?6, meeting_at = ?7, \ + updated_at = ?8 WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", + ( + task_id.to_owned(), + board_id.to_owned(), + title.clone(), + description.clone(), + edit.tag_id.clone(), + deadline.clone(), + edit.meeting_at.clone(), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + if before.title != title { + log(&tx, task_id, actor, "task_edited", None, serde_json::json!({ "field": "title" })).await?; + } + if before.description != description { + log(&tx, task_id, actor, "task_edited", None, serde_json::json!({ "field": "description" })).await?; + } + if before.tag_id != edit.tag_id { + log( + &tx, + task_id, + actor, + "tag_changed", + None, + serde_json::json!({ "from": before.tag_id, "to": edit.tag_id }), + ) + .await?; + } + if before.deadline != edit.deadline { + match (before.deadline, edit.deadline) { + (_, None) => log(&tx, task_id, actor, "deadline_cleared", None, serde_json::json!({})).await?, + (_, Some(day)) => { + log(&tx, task_id, actor, "deadline_set", None, serde_json::json!({ "day": day.to_string() })).await? + } + } + } + if before.meeting_at != edit.meeting_at { + match edit.meeting_at.as_deref() { + None => log(&tx, task_id, actor, "clock_cleared", None, serde_json::json!({})).await?, + Some(at) => log(&tx, task_id, actor, "clock_set", None, serde_json::json!({ "at": at })).await?, + } + sync_reminders(&tx, task_id).await?; + } + live_task(&tx, board_id, task_id).await + } + .await; + finish(tx, outcome).await + } + + /// Moves a task to `to_column` if it is still in `expected_from`. Entering the done column stamps + /// `done_at` and is refused while subtasks are open; leaving it clears `done_at`. Each real move writes + /// one transition and one `task_moved` activity row. + pub async fn move_task( + &self, + board_id: &str, + task_id: &str, + expected_from: &str, + to_column: &str, + actor: &str, + ) -> Result { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let task = live_task(&tx, board_id, task_id).await?; + let target = column_in(&tx, board_id, to_column) + .await? + .filter(|c| c.deleted_at.is_none()) + .ok_or_else(|| Error::Invalid("that column does not exist".into()))?; + if task.column_id != expected_from { + return Ok(MoveOutcome::Stale); + } + if task.column_id == target.id { + return Ok(MoveOutcome::Unchanged); + } + if target.is_done { + let open = fetch_opt( + &tx, + "SELECT COUNT(*) FROM tasks WHERE parent_id = ?1 AND deleted_at IS NULL AND done_at IS NULL", + (task_id.to_owned(),), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + if open > 0 { + return Ok(MoveOutcome::SubtasksOpen); + } + } + let position = next_position(&tx, &target.id).await?; + let now = now_stamp(); + let done_at = target.is_done.then(|| now.clone()); + tx.execute( + "UPDATE tasks SET column_id = ?3, position = ?4, done_at = ?5, updated_at = ?6 \ + WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", + ( + task_id.to_owned(), + board_id.to_owned(), + target.id.clone(), + position, + done_at, + now, + ), + ) + .await + .map_err(db_err)?; + record_transition(&tx, task_id, Some(&task.column_id), &target.id, actor).await?; + log( + &tx, + task_id, + actor, + "task_moved", + None, + serde_json::json!({ "from": task.column_id, "to": target.id }), + ) + .await?; + if task.done_at.is_some() != target.is_done { + sync_reminders(&tx, task_id).await?; + } + Ok(MoveOutcome::Moved) + } + .await; + finish(tx, outcome).await + } + + /// Soft-deletes a task and its direct subtasks. Every live link that points at a deleted task is + /// cleared; the tasks that were waiting for a deleted blocker are returned (they are freed), and each + /// gets an `unblocked` activity row. Pending reminders of the deleted tasks are removed. + pub async fn delete_task( + &self, + board_id: &str, + task_id: &str, + actor: &str, + ) -> Result> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result> = async { + live_task(&tx, board_id, task_id).await?; + let children = fetch_all( + &tx, + "SELECT id FROM tasks WHERE parent_id = ?1 AND board_id = ?2 AND deleted_at IS NULL ORDER BY position, id", + (task_id.to_owned(), board_id.to_owned()), + |row| col_text(row, 0), + ) + .await?; + let mut doomed = vec![task_id.to_owned()]; + doomed.extend(children); + let now = now_stamp(); + for id in &doomed { + tx.execute( + "UPDATE tasks SET deleted_at = ?3, updated_at = ?3 \ + WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", + (id.clone(), board_id.to_owned(), now.clone()), + ) + .await + .map_err(db_err)?; + log(&tx, id, actor, "task_deleted", None, serde_json::json!({})).await?; + } + let doomed_set: HashSet<&str> = doomed.iter().map(String::as_str).collect(); + let mut edges: Vec<(String, String)> = Vec::new(); + for id in &doomed { + edges.extend(fetch_all( + &tx, + "SELECT blocked_id, blocking_id FROM dependencies \ + WHERE (blocked_id = ?1 OR blocking_id = ?1) AND cleared_at IS NULL", + (id.clone(),), + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), + ) + .await?); + } + let mut freed = Vec::new(); + for (blocked, blocking) in unique_pairs(edges) { + tx.execute( + "UPDATE dependencies SET cleared_at = ?3 WHERE blocked_id = ?1 AND blocking_id = ?2", + (blocked.clone(), blocking.clone(), now.clone()), + ) + .await + .map_err(db_err)?; + if doomed_set.contains(blocking.as_str()) && !doomed_set.contains(blocked.as_str()) { + let still_live = fetch_opt( + &tx, + "SELECT id FROM tasks WHERE id = ?1 AND deleted_at IS NULL", + (blocked.clone(),), + |row| col_text(row, 0), + ) + .await?; + if still_live.is_some() { + log( + &tx, + &blocked, + actor, + "unblocked", + None, + serde_json::json!({ "blocker": blocking }), + ) + .await?; + freed.push(blocked); + } + } + } + for id in &doomed { + sync_reminders(&tx, id).await?; + } + Ok(unique(&freed)) + } + .await; + finish(tx, outcome).await + } + + /// Assigns members to a task, all or nothing: if any of them cannot be assigned, nothing changes. + pub async fn assign( + &self, + board_id: &str, + task_id: &str, + subs: &[String], + actor: &str, + ) -> Result<()> { + let subs = unique(subs); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + live_task(&tx, board_id, task_id).await?; + for sub in &subs { + if !assignable(&tx, sub).await? { + return Err(Error::Invalid("that person cannot be assigned".into())); + } + } + for sub in &subs { + let added = tx + .execute( + "INSERT INTO task_assignees (task_id, sub, assigned_at) VALUES (?1, ?2, ?3) \ + ON CONFLICT(task_id, sub) DO NOTHING", + (task_id.to_owned(), sub.clone(), now_stamp()), + ) + .await + .map_err(db_err)?; + if added > 0 { + log(&tx, task_id, actor, "assigned", Some(sub), serde_json::json!({})).await?; + } + } + sync_reminders(&tx, task_id).await + } + .await; + finish(tx, outcome).await + } + + /// Removes assignees from a task. People who were not assigned are skipped without an error. + pub async fn unassign( + &self, + board_id: &str, + task_id: &str, + subs: &[String], + actor: &str, + ) -> Result<()> { + let subs = unique(subs); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + live_task(&tx, board_id, task_id).await?; + for sub in &subs { + let removed = tx + .execute( + "DELETE FROM task_assignees WHERE task_id = ?1 AND sub = ?2", + (task_id.to_owned(), sub.clone()), + ) + .await + .map_err(db_err)?; + if removed > 0 { + log( + &tx, + task_id, + actor, + "unassigned", + Some(sub), + serde_json::json!({}), + ) + .await?; + } + } + sync_reminders(&tx, task_id).await + } + .await; + finish(tx, outcome).await + } + + /// Makes `task_id` a subtask of `parent_id`, or a top-level task when `parent_id` is `None`. One level + /// only: the parent must be top-level, and a task with subtasks of its own cannot become one. + pub async fn set_parent( + &self, + board_id: &str, + task_id: &str, + parent_id: Option<&str>, + actor: &str, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let task = live_task(&tx, board_id, task_id).await?; + let new_parent = match parent_id { + None => None, + Some(p) => { + if p == task_id { + return Err(Error::Invalid("a task cannot be its own subtask".into())); + } + let parent = live_task(&tx, board_id, p) + .await + .map_err(|_| Error::Invalid("the parent task does not exist".into()))?; + if parent.parent_id.is_some() { + return Err(Error::Invalid("subtasks may only be one level deep".into())); + } + let children = fetch_opt( + &tx, + "SELECT COUNT(*) FROM tasks WHERE parent_id = ?1", + (task_id.to_owned(),), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + if children > 0 { + return Err(Error::Conflict( + "a task with subtasks cannot become a subtask".into(), + )); + } + Some(parent) + } + }; + tx.execute( + "UPDATE tasks SET parent_id = ?3, updated_at = ?4 WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", + ( + task_id.to_owned(), + board_id.to_owned(), + new_parent.as_ref().map(|p| p.id.clone()), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + if task.parent_id.as_deref() != new_parent.as_ref().map(|p| p.id.as_str()) { + log( + &tx, + task_id, + actor, + "parent_changed", + None, + serde_json::json!({ "parent": new_parent.as_ref().map(|p| p.key.clone()) }), + ) + .await?; + } + Ok(()) + } + .await; + finish(tx, outcome).await + } + + /// Adds "`blocked` waits for `blocking`". Refused for self-links and for links that close a cycle over + /// live edges. Re-adding a cleared link reactivates it; adding a live one changes nothing. + pub async fn add_dependency( + &self, + board_id: &str, + blocked_id: &str, + blocking_id: &str, + actor: &str, + ) -> Result<()> { + if blocked_id == blocking_id { + return Err(Error::Invalid("a task cannot wait for itself".into())); + } + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let blocked = live_task(&tx, board_id, blocked_id).await?; + let blocking = live_task(&tx, board_id, blocking_id).await?; + let existing = fetch_opt( + &tx, + "SELECT cleared_at FROM dependencies WHERE blocked_id = ?1 AND blocking_id = ?2", + (blocked_id.to_owned(), blocking_id.to_owned()), + |row| col_opt_text(row, 0), + ) + .await?; + if existing.as_ref().is_some_and(Option::is_none) { + return Ok(()); + } + let edges = live_edges(&tx, board_id).await?; + let refs: Vec<(&str, &str)> = edges.iter().map(|(a, b)| (a.as_str(), b.as_str())).collect(); + if would_cycle(&refs, (blocked_id, blocking_id)) { + return Err(Error::Conflict("this link would make a dependency cycle".into())); + } + let now = now_stamp(); + if existing.is_some() { + tx.execute( + "UPDATE dependencies SET cleared_at = NULL, created_at = ?3 \ + WHERE blocked_id = ?1 AND blocking_id = ?2", + (blocked_id.to_owned(), blocking_id.to_owned(), now), + ) + .await + .map_err(db_err)?; + } else { + tx.execute( + "INSERT INTO dependencies (blocked_id, blocking_id, created_at) VALUES (?1, ?2, ?3)", + (blocked_id.to_owned(), blocking_id.to_owned(), now), + ) + .await + .map_err(db_err)?; + } + log( + &tx, + blocked_id, + actor, + "link_added", + None, + serde_json::json!({ "blocking": blocking.key, "blocked": blocked.key }), + ) + .await + } + .await; + finish(tx, outcome).await + } + + /// Clears a dependency (soft: the row stays with `cleared_at`, and it stops counting). + pub async fn clear_dependency( + &self, + board_id: &str, + blocked_id: &str, + blocking_id: &str, + actor: &str, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let blocked = live_task(&tx, board_id, blocked_id).await?; + let changed = tx + .execute( + "UPDATE dependencies SET cleared_at = ?3 WHERE blocked_id = ?1 AND blocking_id = ?2 \ + AND cleared_at IS NULL", + (blocked_id.to_owned(), blocking_id.to_owned(), now_stamp()), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + log( + &tx, + blocked_id, + actor, + "link_removed", + None, + serde_json::json!({ "blocked": blocked.key }), + ) + .await + } + .await; + finish(tx, outcome).await + } + + /// The board for one viewer: live columns with their top-level cards, after the filter and sort. + /// Overdue uses `viewer_zone` for day-only deadlines. Blocked means not done with an uncleared blocker + /// that is itself not done and not deleted. The search folds Turkish i (see `board::fold_for_search`). + pub async fn board_view( + &self, + board_id: &str, + filter: &BoardFilter, + viewer_zone: &TimeZone, + ) -> Result { + let now = Timestamp::now(); + let conn = self.read_conn().await; + let columns = live_columns(&conn, board_id).await?; + let tasks = fetch_all( + &conn, + &format!( + "SELECT {TASK_COLS} FROM tasks WHERE board_id = ?1 AND deleted_at IS NULL AND parent_id IS NULL" + ), + (board_id.to_owned(),), + map_task, + ) + .await?; + let tags: HashMap = fetch_all( + &conn, + "SELECT id, name FROM tags WHERE board_id = ?1", + (board_id.to_owned(),), + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), + ) + .await? + .into_iter() + .collect(); + let mut assignees: HashMap> = HashMap::new(); + for (task_id, assignee) in fetch_all( + &conn, + "SELECT a.task_id, m.sub, m.name FROM task_assignees a \ + JOIN tasks t ON t.id = a.task_id JOIN members m ON m.sub = a.sub \ + WHERE t.board_id = ?1 AND t.deleted_at IS NULL ORDER BY m.name, m.sub", + (board_id.to_owned(),), + map_assignee, + ) + .await? + { + assignees.entry(task_id).or_default().push(assignee); + } + let mut subtask_counts: HashMap = HashMap::new(); + for (parent, total, done) in fetch_all( + &conn, + "SELECT parent_id, COUNT(*), COALESCE(SUM(CASE WHEN done_at IS NULL THEN 0 ELSE 1 END), 0) \ + FROM tasks WHERE board_id = ?1 AND deleted_at IS NULL AND parent_id IS NOT NULL GROUP BY parent_id", + (board_id.to_owned(),), + |row| Ok((col_text(row, 0)?, col_int(row, 1)?, col_int(row, 2)?)), + ) + .await? + { + subtask_counts.insert(parent, (done, total)); + } + let comment_counts: HashMap = fetch_all( + &conn, + "SELECT c.task_id, COUNT(*) FROM comments c JOIN tasks t ON t.id = c.task_id \ + WHERE t.board_id = ?1 AND c.deleted_at IS NULL GROUP BY c.task_id", + (board_id.to_owned(),), + |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), + ) + .await? + .into_iter() + .collect(); + let blocked: HashSet = fetch_all( + &conn, + "SELECT d.blocked_id FROM dependencies d \ + JOIN tasks t ON t.id = d.blocked_id JOIN tasks b ON b.id = d.blocking_id \ + WHERE t.board_id = ?1 AND d.cleared_at IS NULL AND t.deleted_at IS NULL \ + AND b.deleted_at IS NULL AND b.done_at IS NULL", + (board_id.to_owned(),), + |row| col_text(row, 0), + ) + .await? + .into_iter() + .collect(); + drop(conn); + + let query = filter + .query + .as_deref() + .map(str::trim) + .filter(|q| !q.is_empty()) + .map(fold_for_search); + let mut cards = Vec::new(); + for task in tasks { + if filter.tag_id.as_deref().is_some_and(|t| t != task.tag_id) { + continue; + } + let task_assignees = assignees.get(&task.id).cloned().unwrap_or_default(); + match &filter.assignee { + Some(AssigneeFilter::Nobody) if !task_assignees.is_empty() => continue, + Some(AssigneeFilter::Member(sub)) + if !task_assignees.iter().any(|a| &a.sub == sub) => + { + continue; + } + _ => {} + } + if let Some(q) = &query { + let hit = fold_for_search(&task.key).contains(q.as_str()) + || fold_for_search(&task.title).contains(q.as_str()) + || fold_for_search(&task.description).contains(q.as_str()); + if !hit { + continue; + } + } + let done = task.done_at.is_some(); + let meeting = task.meeting_at.as_deref().map(timestamp_of).transpose()?; + let overdue = is_overdue(done, task.deadline, meeting, now, viewer_zone); + let (subtasks_done, subtasks_total) = + subtask_counts.get(&task.id).copied().unwrap_or((0, 0)); + cards.push(Card { + tag_name: tags.get(&task.tag_id).cloned().unwrap_or_default(), + blocked: !done && blocked.contains(&task.id), + overdue, + subtasks_done, + subtasks_total, + comments: comment_counts.get(&task.id).copied().unwrap_or(0), + assignees: task_assignees, + task, + }); + } + match filter.sort { + SortBy::Deadline => cards.sort_by(|a, b| { + a.task + .deadline + .is_none() + .cmp(&b.task.deadline.is_none()) + .then(a.task.deadline.cmp(&b.task.deadline)) + .then(a.task.id.cmp(&b.task.id)) + }), + SortBy::Created => cards.sort_by(|a, b| { + b.task + .created_at + .cmp(&a.task.created_at) + .then(b.task.id.cmp(&a.task.id)) + }), + SortBy::Title => cards.sort_by(|a, b| { + fold_for_search(&a.task.title) + .cmp(&fold_for_search(&b.task.title)) + .then(a.task.id.cmp(&b.task.id)) + }), + } + let overdue = cards.iter().filter(|c| c.overdue).count(); + let blocked_count = cards.iter().filter(|c| c.blocked).count(); + let columns = columns + .into_iter() + .map(|column| { + let mine = cards + .iter() + .filter(|c| c.task.column_id == column.id) + .cloned() + .collect(); + ColumnCards { + column, + cards: mine, + } + }) + .collect(); + Ok(BoardView { + columns, + overdue, + blocked: blocked_count, + }) + } + + /// One task with its project, assignees, live subtasks and live links. `key_or_id` is the readable key + /// (`IZ-42`) or the id. Deleted or foreign tasks are `NotFound`. + pub async fn task_detail(&self, board_id: &str, key_or_id: &str) -> Result { + let conn = self.read_conn().await; + let task = fetch_opt( + &conn, + &format!( + "SELECT {TASK_COLS} FROM tasks WHERE board_id = ?1 AND (id = ?2 OR key = ?2) AND deleted_at IS NULL" + ), + (board_id.to_owned(), key_or_id.to_owned()), + map_task, + ) + .await? + .ok_or(Error::NotFound)?; + let tag = fetch_opt( + &conn, + "SELECT id, board_id, name, position, is_default, color FROM tags WHERE id = ?1", + (task.tag_id.clone(),), + |row| { + Ok(Tag { + id: col_text(row, 0)?, + board_id: col_text(row, 1)?, + name: col_text(row, 2)?, + position: col_real(row, 3)?, + is_default: super::col_bool(row, 4)?, + color: col_opt_text(row, 5)?, + }) + }, + ) + .await? + .ok_or_else(|| Error::Database("task has no project".into()))?; + let assignees = fetch_all( + &conn, + "SELECT a.task_id, m.sub, m.name FROM task_assignees a JOIN members m ON m.sub = a.sub \ + WHERE a.task_id = ?1 ORDER BY m.name, m.sub", + (task.id.clone(),), + map_assignee, + ) + .await? + .into_iter() + .map(|(_, a)| a) + .collect(); + let subtasks = fetch_all( + &conn, + &format!( + "SELECT {TASK_COLS} FROM tasks WHERE parent_id = ?1 AND board_id = ?2 AND deleted_at IS NULL \ + ORDER BY position, id" + ), + (task.id.clone(), board_id.to_owned()), + map_task, + ) + .await?; + let blocked_by = fetch_all( + &conn, + &format!( + "SELECT {TASK_COLS_T} FROM dependencies d JOIN tasks t ON t.id = d.blocking_id \ + WHERE d.blocked_id = ?1 AND d.cleared_at IS NULL AND t.deleted_at IS NULL ORDER BY t.key" + ), + (task.id.clone(),), + map_task, + ) + .await?; + let blocks = fetch_all( + &conn, + &format!( + "SELECT {TASK_COLS_T} FROM dependencies d JOIN tasks t ON t.id = d.blocked_id \ + WHERE d.blocking_id = ?1 AND d.cleared_at IS NULL AND t.deleted_at IS NULL ORDER BY t.key" + ), + (task.id.clone(),), + map_task, + ) + .await?; + Ok(TaskDetail { + task, + tag, + assignees, + subtasks, + blocked_by, + blocks, + }) + } +} + +/// Removes repeated `(blocked, blocking)` pairs, keeping the first. +fn unique_pairs(pairs: Vec<(String, String)>) -> Vec<(String, String)> { + let mut seen = HashSet::new(); + pairs + .into_iter() + .filter(|p| seen.insert(p.clone())) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::store::test_support::seeded; + + fn new_task(title: &str, column: &str, tag: &str) -> NewTask { + NewTask { + title: title.into(), + description: String::new(), + column_id: column.into(), + tag_id: tag.into(), + deadline: None, + meeting_at: None, + assignees: vec![], + parent_id: None, + link: None, + } + } + + async fn default_tag(store: &Store, board: &str) -> String { + store + .tags(board) + .await + .unwrap() + .into_iter() + .find(|t| t.is_default) + .unwrap() + .id + } + + async fn column_named(store: &Store, board: &str, is_done: bool) -> Column { + store + .columns(board) + .await + .unwrap() + .into_iter() + .find(|c| c.is_done == is_done) + .unwrap() + } + + async fn live_count(store: &Store, board: &str) -> usize { + let view = store + .board_view(board, &BoardFilter::default(), &TimeZone::UTC) + .await + .unwrap(); + view.columns.iter().map(|c| c.cards.len()).sum() + } + + #[tokio::test] + async fn refused_link_leaves_no_task_row() { + let (_dir, store, board) = seeded().await; + let tag = default_tag(&store, &board).await; + let backlog = store.columns(&board).await.unwrap()[0].id.clone(); + store + .create_task(&board, new_task("First", &backlog, &tag), "ada") + .await + .unwrap(); + // The link names a task that is not on this board: the whole create is refused. + let mut bad = new_task("Second", &backlog, &tag); + bad.link = Some(("no-such-task".into(), LinkDirection::BlockedBy)); + assert!(matches!( + store.create_task(&board, bad, "ada").await, + Err(Error::Invalid(_)) + )); + assert_eq!(live_count(&store, &board).await, 1); + } + + #[tokio::test] + async fn dependency_cycle_is_refused() { + let (_dir, store, board) = seeded().await; + let tag = default_tag(&store, &board).await; + let backlog = store.columns(&board).await.unwrap()[0].id.clone(); + let a = store + .create_task(&board, new_task("A", &backlog, &tag), "ada") + .await + .unwrap(); + let b = store + .create_task(&board, new_task("B", &backlog, &tag), "ada") + .await + .unwrap(); + store + .add_dependency(&board, &a.id, &b.id, "ada") + .await + .unwrap(); + assert!(matches!( + store.add_dependency(&board, &b.id, &a.id, "ada").await, + Err(Error::Conflict(_)) + )); + } + + #[tokio::test] + async fn move_into_done_with_open_subtask_is_refused() { + let (_dir, store, board) = seeded().await; + let tag = default_tag(&store, &board).await; + let backlog = store.columns(&board).await.unwrap()[0].id.clone(); + let done = column_named(&store, &board, true).await; + let parent = store + .create_task(&board, new_task("Parent", &backlog, &tag), "ada") + .await + .unwrap(); + let child = store + .create_task(&board, new_task("Child", &backlog, &tag), "ada") + .await + .unwrap(); + store + .set_parent(&board, &child.id, Some(&parent.id), "ada") + .await + .unwrap(); + let outcome = store + .move_task(&board, &parent.id, &backlog, &done.id, "ada") + .await + .unwrap(); + assert_eq!(outcome, MoveOutcome::SubtasksOpen); + // Finishing the subtask first lets the parent through. + store + .move_task(&board, &child.id, &backlog, &done.id, "ada") + .await + .unwrap(); + let outcome = store + .move_task(&board, &parent.id, &backlog, &done.id, "ada") + .await + .unwrap(); + assert_eq!(outcome, MoveOutcome::Moved); + let moved = store.task_detail(&board, &parent.key).await.unwrap().task; + assert!(moved.done_at.is_some()); + } + + #[tokio::test] + async fn stale_move_is_refused() { + let (_dir, store, board) = seeded().await; + let tag = default_tag(&store, &board).await; + let columns = store.columns(&board).await.unwrap(); + let (backlog, progress) = (columns[0].id.clone(), columns[1].id.clone()); + let task = store + .create_task(&board, new_task("Move me", &backlog, &tag), "ada") + .await + .unwrap(); + // Someone else already moved it, so the client's view of "from" is out of date. + store + .move_task(&board, &task.id, &backlog, &progress, "bo") + .await + .unwrap(); + let stale = store + .move_task(&board, &task.id, &backlog, &columns[2].id, "ada") + .await + .unwrap(); + assert_eq!(stale, MoveOutcome::Stale); + let same = store + .move_task(&board, &task.id, &progress, &progress, "ada") + .await + .unwrap(); + assert_eq!(same, MoveOutcome::Unchanged); + } + + #[tokio::test] + async fn deleting_a_blocker_frees_the_dependent() { + let (_dir, store, board) = seeded().await; + let tag = default_tag(&store, &board).await; + let backlog = store.columns(&board).await.unwrap()[0].id.clone(); + let blocker = store + .create_task(&board, new_task("Blocker", &backlog, &tag), "ada") + .await + .unwrap(); + let mut dependent = new_task("Dependent", &backlog, &tag); + dependent.link = Some((blocker.id.clone(), LinkDirection::BlockedBy)); + let dependent = store.create_task(&board, dependent, "ada").await.unwrap(); + let before = store + .board_view(&board, &BoardFilter::default(), &TimeZone::UTC) + .await + .unwrap(); + assert_eq!(before.blocked, 1); + let freed = store.delete_task(&board, &blocker.id, "ada").await.unwrap(); + assert_eq!(freed, vec![dependent.id.clone()]); + let after = store + .board_view(&board, &BoardFilter::default(), &TimeZone::UTC) + .await + .unwrap(); + assert_eq!(after.blocked, 0); + } + + #[tokio::test] + async fn search_folds_turkish_dotted_and_dotless_i() { + let (_dir, store, board) = seeded().await; + let tag = default_tag(&store, &board).await; + let backlog = store.columns(&board).await.unwrap()[0].id.clone(); + store + .create_task(&board, new_task("İSTANBUL görüşme", &backlog, &tag), "ada") + .await + .unwrap(); + store + .create_task(&board, new_task("Ankara", &backlog, &tag), "ada") + .await + .unwrap(); + for query in ["istanbul", "ıstanbul", "ISTANBUL", "İstanbul"] { + let filter = BoardFilter { + query: Some(query.into()), + ..BoardFilter::default() + }; + let view = store + .board_view(&board, &filter, &TimeZone::UTC) + .await + .unwrap(); + let titles: Vec<&str> = view + .columns + .iter() + .flat_map(|c| c.cards.iter().map(|card| card.task.title.as_str())) + .collect(); + assert_eq!(titles, vec!["İSTANBUL görüşme"], "query {query}"); + } + } + + #[tokio::test] + async fn tag_delete_refused_while_in_use() { + let (_dir, store, board) = seeded().await; + let general = default_tag(&store, &board).await; + let work = store.add_tag(&board, "Work", None).await.unwrap(); + let backlog = store.columns(&board).await.unwrap()[0].id.clone(); + let task = store + .create_task(&board, new_task("Report", &backlog, &work.id), "ada") + .await + .unwrap(); + assert!(matches!( + store.delete_tag(&board, &work.id).await, + Err(Error::Conflict(_)) + )); + assert!(matches!( + store.delete_tag(&board, &general).await, + Err(Error::Invalid(_)) + )); + // Once the only task is deleted, the tag goes and the trashed task is re-pointed to General. + store.delete_task(&board, &task.id, "ada").await.unwrap(); + store.delete_tag(&board, &work.id).await.unwrap(); + assert!(store.tag(&board, &work.id).await.unwrap().is_none()); + let trashed = fetch_opt( + &*store.read_conn().await, + "SELECT tag_id FROM tasks WHERE id = ?1", + (task.id.clone(),), + |row| col_text(row, 0), + ) + .await + .unwrap(); + assert_eq!(trashed, Some(general)); + } +}