From 9b4b86ead56a74c370ed5dcc734bc151ee976e5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 26 Aug 2026 09:43:05 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A5=20feat(delete):=20a=20writer=20may?= =?UTF-8?q?=20delete,=20softly,=20after=20being=20told=20what=20goes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The delete policy is removed — column, enum, trait parameter and branch. It was a setting with no screen: configurable-looking, unreachable, and hiding a destructive default in the schema. A writer may delete. What makes that safe is not a role but the two things around it. The delete is soft: the task keeps a deleted_at, and its comments and both directions of its edges stay in the table. Every read already joins the task and filters deleted_at, so a deleted task's links stop applying without being destroyed, and the freed-tasks calculation is unchanged — a soft-deleted task is gone from the board, so what it blocked really is unblocked. And it asks first. `what_delete_costs` is a read that reports the key, the title, the comment count, the number of links that stop applying and the keys of the tasks that would be freed; the modal says those out loud, in the artboard's language, before the red button appears. The artboard drew no confirmation, which was a gap in the mockup rather than a rule: this action reaches other people's tasks and, from slice 7, sends mail. Nothing in the UI restores a deleted task. `deleted_at` is what makes a mistake recoverable by hand today; a restore surface can wait until someone asks. --- crates/dizey-core/migrations/0001_init.sql | 4 +- crates/dizey-core/src/detail.rs | 13 ++ crates/dizey-core/src/store/mod.rs | 34 +---- crates/dizey-core/src/store/turso_store.rs | 96 +++++++++++--- crates/dizey-core/tests/store.rs | 71 +++++++++-- crates/dizey-web/src/detail.rs | 142 ++++++++++++++++----- crates/dizey-web/tests/http.rs | 69 +++++----- style/main.scss | 42 ++++++ 8 files changed, 350 insertions(+), 121 deletions(-) diff --git a/crates/dizey-core/migrations/0001_init.sql b/crates/dizey-core/migrations/0001_init.sql index 19114a3..db31924 100644 --- a/crates/dizey-core/migrations/0001_init.sql +++ b/crates/dizey-core/migrations/0001_init.sql @@ -20,9 +20,7 @@ CREATE TABLE workspace ( attachment_limit_bytes INTEGER NOT NULL DEFAULT 26214400, photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152, -- JSON array of allowed extensions. An empty array means every type. - allowed_file_types TEXT NOT NULL DEFAULT '[]', - -- 'anyone' | 'admin' - who_can_delete_tasks TEXT NOT NULL DEFAULT 'anyone' + allowed_file_types TEXT NOT NULL DEFAULT '[]' ); CREATE TABLE user ( diff --git a/crates/dizey-core/src/detail.rs b/crates/dizey-core/src/detail.rs index e5ecf1a..68e2b7b 100644 --- a/crates/dizey-core/src/detail.rs +++ b/crates/dizey-core/src/detail.rs @@ -60,6 +60,19 @@ impl DependencyEdge { } } +/// What deleting a task would take with it. The confirmation step says this +/// out loud before the button fires. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct DeletionCost { + pub task_key: String, + pub title: String, + pub comment_count: u32, + /// Links in either direction that stop applying. + pub link_count: u32, + /// Keys of the tasks that would have nothing in front of them afterwards. + pub frees: Vec, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Comment { pub id: String, diff --git a/crates/dizey-core/src/store/mod.rs b/crates/dizey-core/src/store/mod.rs index 1e029f7..b93f7bb 100644 --- a/crates/dizey-core/src/store/mod.rs +++ b/crates/dizey-core/src/store/mod.rs @@ -10,7 +10,7 @@ use time::OffsetDateTime; use crate::Role; use crate::board::{BoardReads, TaskRow}; -use crate::detail::{ActivityKind, DetailReads}; +use crate::detail::{ActivityKind, DeletionCost, DetailReads}; pub mod turso_store; @@ -51,33 +51,6 @@ pub struct Workspace { pub attachment_limit_bytes: u64, pub photo_limit_bytes: u64, pub allowed_file_types: Vec, - pub who_can_delete_tasks: DeletePolicy, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum DeletePolicy { - /// Anyone who can write tasks may delete one. - Anyone, - /// Only the admin. - Admin, -} - -impl DeletePolicy { - pub fn as_str(self) -> &'static str { - match self { - DeletePolicy::Anyone => "anyone", - DeletePolicy::Admin => "admin", - } - } - - pub fn parse(raw: &str) -> Result { - match raw { - "anyone" => Ok(DeletePolicy::Anyone), - "admin" => Ok(DeletePolicy::Admin), - other => Err(StoreError::Corrupt(format!("delete policy {other:?}"))), - } - } } /// An account. `password_hash` is `None` for an invited member who has not @@ -202,7 +175,6 @@ pub trait Store: BoardReads + DetailReads + 'static { attachment_limit_bytes: u64, photo_limit_bytes: u64, allowed_file_types: &[String], - who_can_delete_tasks: DeletePolicy, ) -> Result<()>; // -- users ------------------------------------------------------------- @@ -371,6 +343,10 @@ pub trait Store: BoardReads + DetailReads + 'static { /// Appends one line to a task's activity trail. `actor_id` is `None` when /// the system did it rather than a person. + /// What a delete would take with it, for the confirmation step. Reads + /// only; nothing here writes. + async fn deletion_cost(&self, task_id: &str) -> Result>; + async fn record_activity( &self, task_id: &str, diff --git a/crates/dizey-core/src/store/turso_store.rs b/crates/dizey-core/src/store/turso_store.rs index fb9775f..2a98c4c 100644 --- a/crates/dizey-core/src/store/turso_store.rs +++ b/crates/dizey-core/src/store/turso_store.rs @@ -12,12 +12,12 @@ use turso::transaction::TransactionBehavior; use turso::{Builder, Connection, Row, Value, params}; use uuid::Uuid; -use super::{ - DeletePolicy, NewTask, NewUser, Result, Session, SigninLink, Store, StoreError, User, Workspace, -}; +use super::{NewTask, NewUser, Result, Session, SigninLink, Store, StoreError, User, Workspace}; use crate::Role; use crate::board::{BoardMeta, BoardReads, Column, Person, TaskRow}; -use crate::detail::{ActivityEntry, ActivityKind, Comment, DependencyEdge, DetailReads, TaskFacts}; +use crate::detail::{ + ActivityEntry, ActivityKind, Comment, DeletionCost, DependencyEdge, DetailReads, TaskFacts, +}; use time::Date; use time::format_description::BorrowedFormatItem; use time::macros::format_description; @@ -216,13 +216,12 @@ fn workspace_from(row: &Row) -> Result { attachment_limit_bytes: row.get::(8).map_err(backend)?.max(0) as u64, allowed_file_types, photo_limit_bytes: row.get::(10).map_err(backend)?.max(0) as u64, - who_can_delete_tasks: DeletePolicy::parse(&text(row, 11)?)?, }) } const WORKSPACE_COLUMNS: &str = "id, name, created_at, smtp_host, smtp_port, smtp_username, \ smtp_from_name, smtp_from_address, attachment_limit_bytes, allowed_file_types, \ - photo_limit_bytes, who_can_delete_tasks"; + photo_limit_bytes"; fn user_from(row: &Row) -> Result { Ok(User { @@ -439,19 +438,17 @@ impl Store for TursoStore { attachment_limit_bytes: u64, photo_limit_bytes: u64, allowed_file_types: &[String], - who_can_delete_tasks: DeletePolicy, ) -> Result<()> { let types = serde_json::to_string(allowed_file_types) .map_err(|e| StoreError::Corrupt(format!("allowed_file_types: {e}")))?; self.conn .execute( "UPDATE workspace SET attachment_limit_bytes = ?1, photo_limit_bytes = ?2, \ - allowed_file_types = ?3, who_can_delete_tasks = ?4 WHERE id = ?5", + allowed_file_types = ?3 WHERE id = ?4", params![ attachment_limit_bytes as i64, photo_limit_bytes as i64, types, - who_can_delete_tasks.as_str(), workspace_id ], ) @@ -1208,12 +1205,9 @@ impl Store for TursoStore { } drop(rows); - tx.execute( - "DELETE FROM task_dependency \ - WHERE blocked_task_id = ?1 OR blocking_task_id = ?1", - params![task_id], - ) - .await?; + // The edges and the comments stay in the table: the delete is a + // soft one, and every read filters on the task's deleted_at, so a + // deleted task's links stop applying without being destroyed. tx.execute( "UPDATE task SET deleted_at = ?2, updated_at = ?2 WHERE id = ?1", params![task_id, stamp.clone()], @@ -1286,6 +1280,78 @@ impl Store for TursoStore { } } + async fn deletion_cost(&self, task_id: &str) -> Result> { + let mut rows = self + .conn + .query( + "SELECT task_key, title FROM task WHERE id = ?1 AND deleted_at IS NULL", + params![task_id], + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Ok(None); + }; + let task_key = text(&row, 0)?; + let title = text(&row, 1)?; + drop(rows); + + // Both counts in one sweep: the confirmation says what goes, and it + // should not cost three round trips to say it. + let mut rows = self + .conn + .query( + "SELECT (SELECT COUNT(*) FROM comment WHERE task_id = ?1), \ + (SELECT COUNT(*) FROM task_dependency d JOIN task t \ + ON t.id = CASE WHEN d.blocked_task_id = ?1 \ + THEN d.blocking_task_id ELSE d.blocked_task_id END \ + WHERE (d.blocked_task_id = ?1 OR d.blocking_task_id = ?1) \ + AND d.cleared_at IS NULL AND t.deleted_at IS NULL)", + params![task_id], + ) + .await + .map_err(backend)?; + let (comment_count, link_count) = match rows.next().await.map_err(backend)? { + Some(row) => ( + row.get::(0).map_err(backend)?.max(0) as u32, + row.get::(1).map_err(backend)?.max(0) as u32, + ), + None => (0, 0), + }; + drop(rows); + + // Who would be left with nothing in front of them. The same reading the + // delete itself uses: an uncleared edge to a live task is what counts. + let mut rows = self + .conn + .query( + "SELECT t.task_key FROM task_dependency d \ + JOIN task t ON t.id = d.blocked_task_id \ + WHERE d.blocking_task_id = ?1 AND d.cleared_at IS NULL \ + AND t.deleted_at IS NULL \ + AND NOT EXISTS ( \ + SELECT 1 FROM task_dependency o \ + JOIN task b ON b.id = o.blocking_task_id \ + WHERE o.blocked_task_id = t.id AND o.blocking_task_id <> ?1 \ + AND o.cleared_at IS NULL AND b.deleted_at IS NULL)", + params![task_id], + ) + .await + .map_err(backend)?; + let mut frees = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + frees.push(text(&row, 0)?); + } + + Ok(Some(DeletionCost { + task_key, + title, + comment_count, + link_count, + frees, + })) + } + async fn record_activity( &self, task_id: &str, diff --git a/crates/dizey-core/tests/store.rs b/crates/dizey-core/tests/store.rs index 702d72d..995352b 100644 --- a/crates/dizey-core/tests/store.rs +++ b/crates/dizey-core/tests/store.rs @@ -8,7 +8,7 @@ use std::path::PathBuf; use dizey_core::Role; use dizey_core::auth::{Token, hash_password}; -use dizey_core::store::{DeletePolicy, NewUser, Store, StoreError, TursoStore, User}; +use dizey_core::store::{NewUser, Store, StoreError, TursoStore, User}; use time::{Duration, OffsetDateTime}; use uuid::Uuid; @@ -213,7 +213,6 @@ async fn workspace_defaults_match_the_settings_screen() { ws.allowed_file_types.is_empty(), "every type until narrowed" ); - assert_eq!(ws.who_can_delete_tasks, DeletePolicy::Anyone); assert!(ws.smtp_host.is_none()); } @@ -258,20 +257,13 @@ async fn limits_round_trip_including_the_file_type_list() { let types = vec!["png".to_string(), "pdf".to_string()]; scratch .store - .set_limits( - &ws_id, - 10 * 1024 * 1024, - 512 * 1024, - &types, - DeletePolicy::Admin, - ) + .set_limits(&ws_id, 10 * 1024 * 1024, 512 * 1024, &types) .await .unwrap(); let ws = scratch.store.workspace().await.unwrap().unwrap(); assert_eq!(ws.attachment_limit_bytes, 10 * 1024 * 1024); assert_eq!(ws.photo_limit_bytes, 512 * 1024); assert_eq!(ws.allowed_file_types, types); - assert_eq!(ws.who_can_delete_tasks, DeletePolicy::Admin); } #[tokio::test] @@ -2118,3 +2110,62 @@ async fn a_task_detail_costs_seven_queries_whatever_it_carries() { "the round trips a detail costs must not follow what it carries" ); } + +#[tokio::test] +async fn a_delete_says_what_it_would_take_with_it() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + + let doomed = add_task(store, &workspace, "Backlog", "doomed", None, &admin).await; + let other = add_task(store, &workspace, "Backlog", "other", None, &admin).await; + let freed = add_task(store, &workspace, "Backlog", "freed", None, &admin).await; + let still_stuck = add_task(store, &workspace, "Backlog", "stuck", None, &admin).await; + store.add_dependency(&freed, &doomed, now).await.unwrap(); + store + .add_dependency(&still_stuck, &doomed, now) + .await + .unwrap(); + store + .add_dependency(&still_stuck, &other, now) + .await + .unwrap(); + store + .add_comment(&doomed, &admin, "one", now) + .await + .unwrap(); + store + .add_comment(&doomed, &admin, "two", now) + .await + .unwrap(); + + let cost = store.deletion_cost(&doomed).await.unwrap().unwrap(); + assert_eq!(cost.title, "doomed"); + assert_eq!(cost.comment_count, 2); + assert_eq!(cost.link_count, 2, "both tasks waiting on this one"); + + // The same reading the delete itself takes: only the task with nothing + // else in front of it is named. + let freed_key = key_of(store, &workspace, "freed").await; + assert_eq!(cost.frees, vec![freed_key]); + + // And it is a preview: nothing was written. + assert_eq!( + store.delete_task(&doomed, &admin, now).await.unwrap(), + vec![freed.clone()] + ); + assert!(store.deletion_cost(&doomed).await.unwrap().is_none()); +} + +/// The key the board shows for a task with this title. +async fn key_of(store: &TursoStore, workspace: &str, title: &str) -> String { + let board = board_of(store, workspace).await; + board + .columns + .iter() + .flat_map(|column| column.cards.iter()) + .find(|card| card.title == title) + .expect("no such card") + .task_key + .clone() +} diff --git a/crates/dizey-web/src/detail.rs b/crates/dizey-web/src/detail.rs index 4775b3a..2d4d69d 100644 --- a/crates/dizey-web/src/detail.rs +++ b/crates/dizey-web/src/detail.rs @@ -7,7 +7,7 @@ //! authorization question, not a validation one. use dizey_core::board::Person; -use dizey_core::detail::{Comment, DependencyEdge, TaskDetail}; +use dizey_core::detail::{Comment, DeletionCost, DependencyEdge, TaskDetail}; use leptos::prelude::*; use serde::{Deserialize, Serialize}; use time::Date; @@ -34,7 +34,7 @@ pub struct DetailSnapshot { pub linkable: Vec, pub may_write: bool, pub may_comment: bool, - /// The workspace's delete policy, already applied to this person. + /// Whether this person may delete the task. A writer may. pub may_delete: bool, } @@ -83,7 +83,6 @@ mod guard { pub async fn fetch_task(task_id: String) -> Result, ServerFnError> { use crate::server::{accounts, require_user}; use dizey_core::detail::load; - use dizey_core::store::DeletePolicy; use time::OffsetDateTime; let user = match require_user().await { @@ -123,25 +122,16 @@ pub async fn fetch_task(task_id: String) -> Result true, - DeletePolicy::Admin => user.role.can_administer(), - }; Ok(Ok(DetailSnapshot { detail, linkable, may_write, may_comment: user.role.can_comment(), - may_delete, + may_delete: may_write, me: Me { id: user.id, display_name: user.display_name, @@ -398,34 +388,45 @@ pub async fn post_comment(task_id: String, body: String) -> Result Result, ServerFnError> { + use crate::server::accounts; + + if let Err(refusal) = guard::writer_and_task(&task_id).await { + return Ok(Err(refusal)); + } + match accounts() + .store() + .deletion_cost(&task_id) + .await + .map_err(|e| ServerFnError::new(e.to_string()))? + { + Some(cost) => Ok(Ok(cost)), + None => Ok(Err(Refusal::NotFound)), + } +} + +/// Deletes a task. A writer may: the delete is soft — the row keeps a +/// `deleted_at`, its comments and its edges stay in the table — so a mistake is +/// recoverable by hand. Whatever was waiting only on it becomes unblocked, and +/// the store records that. #[server] pub async fn delete_task(task_id: String) -> Result, ServerFnError> { use crate::server::accounts; - use dizey_core::store::DeletePolicy; use time::OffsetDateTime; let (user, _) = match guard::writer_and_task(&task_id).await { Ok(pair) => pair, Err(refusal) => return Ok(Some(refusal)), }; - let store = accounts().store().clone(); - let fail = |e: dizey_core::store::StoreError| ServerFnError::new(e.to_string()); - let policy = store - .workspace() - .await - .map_err(fail)? - .map(|workspace| workspace.who_can_delete_tasks) - .unwrap_or(DeletePolicy::Admin); - if matches!(policy, DeletePolicy::Admin) && !user.role.can_administer() { - return Ok(Some(Refusal::Forbidden)); - } - - store + accounts() + .store() .delete_task(&task_id, &user.id, OffsetDateTime::now_utc()) .await - .map_err(fail)?; + .map_err(|e| ServerFnError::new(e.to_string()))?; Ok(None) } @@ -536,6 +537,10 @@ fn DetailScreen( let comment = ServerAction::::new(); let link = ServerAction::::new(); let remove = ServerAction::::new(); + // Deleting is two steps: ask what it would cost, then say it out loud and + // let the person decide. The artboard's red button had no confirmation and + // this action reaches other people's tasks. + let ask = ServerAction::::new(); // Every action that lands re-reads the task and the board behind it. for value in [save.value(), comment.value(), link.value()] { Effect::new(move |_| { @@ -793,16 +798,85 @@ fn DetailScreen( {problem} + {move || { + ask.value() + .get() + .and_then(|answer| answer.ok().and_then(|inner| inner.ok())) + .map(|cost| { + let DeletionCost { task_key, title, comment_count, link_count, frees } = cost; + let freed = frees.join(", "); + view! { +
+
+ {format!("Delete {task_key} — {title}?")} +
+
    + {(comment_count > 0) + .then(|| { + view! { +
  • + {if comment_count == 1 { + "1 comment goes with it".to_string() + } else { + format!("{comment_count} comments go with it") + }} +
  • + } + })} + {(link_count > 0) + .then(|| { + view! { +
  • + {if link_count == 1 { + "1 dependency stops applying".to_string() + } else { + format!("{link_count} dependencies stop applying") + }} +
  • + } + })} + {(!freed.is_empty()) + .then(|| { + view! {
  • {format!("{freed} stops being blocked")}
  • } + })} +
+
+ "The task keeps its record in the database, but nothing in Dizey brings it back." +
+
+ + + + + +
+
+ } + }) + }} +