From 1788d7f4a9aff5ff08093febae5bd86eb2e337a3 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 15:57:29 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20board:=20Manual=20sort=20by=20defau?= =?UTF-8?q?lt=20with=20in-column=20reorder;=20admins=20restore=20recently?= =?UTF-8?q?=20deleted=20tasks;=20im=20admins'=20role=20is=20fixed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 +- .../0007_activity_restore_kinds.sql | 26 ++ crates/iz-core/src/authz.rs | 28 +- crates/iz-core/src/store/members.rs | 22 +- crates/iz-core/src/store/migrate.rs | 4 + crates/iz-core/src/store/mod.rs | 2 +- crates/iz-core/src/store/outbox.rs | 7 +- crates/iz-core/src/store/reminders.rs | 4 +- crates/iz-core/src/store/rules_engine.rs | 2 +- crates/iz-core/src/store/sessions.rs | 7 +- crates/iz-core/src/store/tasks.rs | 349 +++++++++++++++++- crates/iz-core/src/time.rs | 7 + crates/iz-web/assets/board.js | 44 ++- crates/iz-web/src/i18n/admin.rs | 54 +++ crates/iz-web/src/i18n/board.rs | 14 +- crates/iz-web/src/i18n/task.rs | 10 + crates/iz-web/src/pages/admin.rs | 1 + crates/iz-web/src/pages/board.rs | 21 +- crates/iz-web/src/pages/files.rs | 2 +- crates/iz-web/src/pages/people.rs | 8 +- crates/iz-web/src/pages/photo.rs | 2 +- crates/iz-web/src/pages/settings.rs | 73 +++- crates/iz-web/src/pages/sign_in.rs | 2 +- crates/iz-web/src/pages/tasks.rs | 9 +- crates/iz-web/src/views/admin.rs | 56 +++ crates/iz-web/src/views/board.rs | 5 + crates/iz-web/src/views/structure.rs | 4 + docs/architecture.md | 36 +- 28 files changed, 726 insertions(+), 77 deletions(-) create mode 100644 crates/iz-core/migrations/0007_activity_restore_kinds.sql diff --git a/README.md b/README.md index b06c629..19f1a69 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,9 @@ iz is the family task board. It has columns, cards (with one level of subtasks, dependencies and assignees), projects (tags), deadlines with meeting times and reminders, comments, attachments with in-page viewers (images, media, PDF, spreadsheets, slides), an activity trail, and admin-defined mail -rules with a durable outbox. Sign-in goes through the family's `im` identity provider. +rules with a durable outbox. Sign-in goes through the family's `im` identity provider. Cards keep a manual +order (the default sort), an administrator can restore tasks deleted in the last 30 days, and an `im` +administrator is an administrator in iz whatever role is stored here. Design notes are in `docs/architecture.md`. The HTTP contracts with `im` and `in` are in `docs/contracts.md`, and the code conventions are in `docs/conventions.md`. diff --git a/crates/iz-core/migrations/0007_activity_restore_kinds.sql b/crates/iz-core/migrations/0007_activity_restore_kinds.sql new file mode 100644 index 0000000..087ba60 --- /dev/null +++ b/crates/iz-core/migrations/0007_activity_restore_kinds.sql @@ -0,0 +1,26 @@ +-- 0007: the activity trail gains two kinds. 'task_reordered' is a card placed at a new spot in its column +-- under the Manual sort; 'task_restored' is a deleted task brought back by an administrator. SQLite cannot +-- alter a CHECK, so the table is rebuilt. Rows of 0001 carry over unchanged; the indexes are recreated. +CREATE TABLE activity_by_kind ( + id TEXT PRIMARY KEY, + task_id TEXT REFERENCES tasks(id) ON DELETE CASCADE, + actor TEXT REFERENCES members(sub) ON DELETE SET NULL, + subject TEXT REFERENCES members(sub) ON DELETE SET NULL, + kind TEXT NOT NULL CHECK (kind IN ( + 'task_created', 'task_edited', 'task_moved', 'task_deleted', + 'assigned', 'unassigned', 'tag_changed', 'parent_changed', + 'link_added', 'link_removed', 'unblocked', + 'deadline_set', 'deadline_cleared', 'clock_set', 'clock_cleared', + 'watch_changed', 'comment_added', 'comment_edited', 'comment_deleted', + 'file_added', 'file_deleted', 'reminded', 'account_changed', + 'task_reordered', 'task_restored' + )), + detail TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(detail)), + at TEXT NOT NULL +); +INSERT INTO activity_by_kind (id, task_id, actor, subject, kind, detail, at) + SELECT id, task_id, actor, subject, kind, detail, at FROM activity; +DROP TABLE activity; +ALTER TABLE activity_by_kind RENAME TO activity; +CREATE INDEX activity_by_task ON activity(task_id, at); +CREATE INDEX activity_recent ON activity(at); diff --git a/crates/iz-core/src/authz.rs b/crates/iz-core/src/authz.rs index 800330c..fcd0e93 100644 --- a/crates/iz-core/src/authz.rs +++ b/crates/iz-core/src/authz.rs @@ -3,10 +3,11 @@ //! 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. +//! Levels: admin contains member, member contains viewer. `im_admin` acts as admin, whatever the stored +//! role says. A disabled account is denied everything with `NotFound`; so is a member with role `none` +//! who is not an `im` administrator. 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, mail), +//! with the same `im_admin` exception, so a denied member cannot reach data through another path. use crate::error::Error; @@ -128,19 +129,18 @@ enum Level { pub fn authorize(actor: &Actor, action: &Action) -> Result<(), Denied> { let (sub, level) = match actor { Actor::Anonymous => return Err(Denied::Forbidden), - // A disabled member and a member with no role have no access, even when `im` makes them an admin. - Actor::Member { disabled: true, .. } - | Actor::Member { - role: Role::NoAccess, - .. - } => { - return Err(Denied::NotFound); - } + // A disabled account has no access, even when `im` makes it an admin. + Actor::Member { disabled: true, .. } => return Err(Denied::NotFound), + // An `im` administrator is an admin whatever the stored role says, role `none` included. Actor::Member { sub, im_admin: true, .. } => (sub.as_str(), Level::Admin), + Actor::Member { + role: Role::NoAccess, + .. + } => return Err(Denied::NotFound), Actor::Member { sub, role, .. } => { let level = match role { Role::Admin => Level::Admin, @@ -222,6 +222,10 @@ mod tests { [ok, ok, ok, Err(F), ok, ok, ok, ok], ), (member("ada", Role::NoAccess, false, false), [Err(N); 8]), + ( + member("ada", Role::NoAccess, true, false), + [ok, ok, ok, ok, ok, ok, ok, ok], + ), (member("ada", Role::Admin, false, true), [Err(N); 8]), ]; let actions = [ diff --git a/crates/iz-core/src/store/members.rs b/crates/iz-core/src/store/members.rs index 6e7e56a..cb19c81 100644 --- a/crates/iz-core/src/store/members.rs +++ b/crates/iz-core/src/store/members.rs @@ -59,6 +59,17 @@ pub struct Member { pub last_sign_in_at: Option, } +impl Member { + /// The role iz acts on: an `im` administrator is always `admin`, whatever the stored role says. + pub fn effective_role(&self) -> Role { + if self.im_admin { + Role::Admin + } else { + self.role + } + } +} + /// What the directory (or a sign-in) says about one person. Validated before it is stored. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DirectoryMember { @@ -324,10 +335,18 @@ impl Store { /// 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. + /// A member who is an `im` administrator keeps the admin role whatever is stored, so their role + /// cannot be changed here (refused as a conflict; the page does not offer the change). 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 member = select_member(&tx, sub).await?.ok_or(Error::NotFound)?; + if member.im_admin { + return Err(Error::Conflict( + "the role of an im administrator is set in im".into(), + )); + } let changed = tx .execute( "UPDATE members SET role = ?2 WHERE sub = ?1 AND (?2 = 'admin' OR EXISTS ( \ @@ -338,9 +357,6 @@ impl Store { .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(), )); diff --git a/crates/iz-core/src/store/migrate.rs b/crates/iz-core/src/store/migrate.rs index 6151041..d96e72b 100644 --- a/crates/iz-core/src/store/migrate.rs +++ b/crates/iz-core/src/store/migrate.rs @@ -24,6 +24,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ 6, include_str!("../../migrations/0006_decision_skipped.sql"), ), + ( + 7, + include_str!("../../migrations/0007_activity_restore_kinds.sql"), + ), ]; fn migration_err(e: turso::Error) -> Error { diff --git a/crates/iz-core/src/store/mod.rs b/crates/iz-core/src/store/mod.rs index ece8406..4501c41 100644 --- a/crates/iz-core/src/store/mod.rs +++ b/crates/iz-core/src/store/mod.rs @@ -404,7 +404,7 @@ mod tests { }) .await .unwrap(); - assert_eq!(versions, vec![1, 2, 3, 4, 5, 6]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7]); } #[tokio::test] diff --git a/crates/iz-core/src/store/outbox.rs b/crates/iz-core/src/store/outbox.rs index acd0857..f6a3a3e 100644 --- a/crates/iz-core/src/store/outbox.rs +++ b/crates/iz-core/src/store/outbox.rs @@ -178,7 +178,8 @@ pub fn clamp_page(limit: usize) -> usize { limit.clamp(1, PAGE_MAX) } -/// Decides whether a claimed recipient may still receive mail: enabled, role admin or member. +/// Decides whether a claimed recipient may still receive mail: enabled, role admin or member. The role +/// read is the effective one (an `im` administrator is `admin`). fn eligible_role(role: &str) -> bool { matches!(role, "admin" | "member") } @@ -196,7 +197,7 @@ impl Store { let candidates = fetch_all( &tx, &format!( - "SELECT {OUTBOX_COLS}, m.role FROM mail_outbox o JOIN members m ON m.sub = o.recipient \ + "SELECT {OUTBOX_COLS}, CASE WHEN m.im_admin = 1 THEN 'admin' ELSE m.role END FROM mail_outbox o JOIN members m ON m.sub = o.recipient \ WHERE o.state IN ('pending', 'failed') AND o.next_attempt_at <= ?1 \ AND (o.claimed_at IS NULL OR o.claimed_at <= ?2) \ ORDER BY o.next_attempt_at, o.id LIMIT ?3" @@ -387,7 +388,7 @@ impl Store { } let recipients = fetch_all( &tx, - "SELECT sub FROM members WHERE disabled = 0 AND role IN ('admin', 'member') AND sub <> ?1 ORDER BY sub", + "SELECT sub FROM members WHERE disabled = 0 AND (im_admin = 1 OR role IN ('admin', 'member')) AND sub <> ?1 ORDER BY sub", (actor.to_owned(),), |row| col_text(row, 0), ) diff --git a/crates/iz-core/src/store/reminders.rs b/crates/iz-core/src/store/reminders.rs index f24f4f5..cf434ce 100644 --- a/crates/iz-core/src/store/reminders.rs +++ b/crates/iz-core/src/store/reminders.rs @@ -83,7 +83,7 @@ pub(super) async fn sync_reminders(tx: &Transaction<'_>, task_id: &str) -> Resul "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')) \ + SELECT 1 FROM members m WHERE m.sub = a.sub AND m.disabled = 0 AND (m.im_admin = 1 OR m.role IN ('admin', 'member'))) \ ON CONFLICT(task_id, sub) DO NOTHING", (task_id.to_owned(), due), ) @@ -112,7 +112,7 @@ impl Store { "SELECT r.task_id, r.sub, t.key, t.title, t.meeting_at, m.zoneinfo, m.locale, m.locale_override \ FROM reminders r JOIN tasks t ON t.id = r.task_id JOIN members m ON m.sub = r.sub \ WHERE r.sent_at IS NULL AND r.due_at <= ?1 AND t.deleted_at IS NULL \ - AND m.disabled = 0 AND m.role IN ('admin', 'member') \ + AND m.disabled = 0 AND (m.im_admin = 1 OR m.role IN ('admin', 'member')) \ ORDER BY r.due_at, r.task_id, r.sub LIMIT ?2", (stamp.clone(), i64::try_from(batch).unwrap_or(i64::MAX)), |row| { diff --git a/crates/iz-core/src/store/rules_engine.rs b/crates/iz-core/src/store/rules_engine.rs index 53ea2ee..cbcfccf 100644 --- a/crates/iz-core/src/store/rules_engine.rs +++ b/crates/iz-core/src/store/rules_engine.rs @@ -76,7 +76,7 @@ async fn eligible_members(tx: &Transaction<'_>) -> Result> { fetch_all( tx, "SELECT sub, locale, locale_override, zoneinfo FROM members \ - WHERE disabled = 0 AND role IN ('admin', 'member') ORDER BY sub", + WHERE disabled = 0 AND (im_admin = 1 OR role IN ('admin', 'member')) ORDER BY sub", (), |row| { let locale = col_opt_text(row, 1)?; diff --git a/crates/iz-core/src/store/sessions.rs b/crates/iz-core/src/store/sessions.rs index c620bea..6cc7d25 100644 --- a/crates/iz-core/src/store/sessions.rs +++ b/crates/iz-core/src/store/sessions.rs @@ -81,7 +81,7 @@ impl Store { "INSERT INTO sessions (id, sub, token_hash, csrf_token, sid, created_at, expires_at, \ last_seen, user_agent, ip, id_token_sealed) \ SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?6, ?8, ?9, ?10 FROM members \ - WHERE sub = ?2 AND disabled = 0 AND role <> 'none'", + WHERE sub = ?2 AND disabled = 0 AND (im_admin = 1 OR role <> 'none')", ( id.clone(), sub.to_owned(), @@ -107,7 +107,8 @@ impl Store { }) } - /// The live session for a cookie token: unexpired, member enabled, role not `none`. `None` otherwise, + /// The live session for a cookie token: unexpired, member enabled, role not `none` (an `im` administrator + /// always passes). `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; @@ -115,7 +116,7 @@ impl Store { &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'" + WHERE s.token_hash = ?1 AND s.expires_at > ?2 AND m.disabled = 0 AND (m.im_admin = 1 OR m.role <> 'none')" ), (hash_token(token), now_stamp()), map_session, diff --git a/crates/iz-core/src/store/tasks.rs b/crates/iz-core/src/store/tasks.rs index e137749..78ccae8 100644 --- a/crates/iz-core/src/store/tasks.rs +++ b/crates/iz-core/src/store/tasks.rs @@ -7,6 +7,7 @@ //! transaction whenever the meeting time, the assignees, the done state or the deletion changes. use std::collections::{HashMap, HashSet}; +use std::time::Duration; use jiff::Timestamp; use jiff::civil::Date; @@ -26,7 +27,7 @@ use crate::clock::timestamp_of; use crate::error::{Error, Result}; use crate::limits::{DESCRIPTION_MAX, TITLE_MAX}; use crate::store::Store; -use crate::time::now_stamp; +use crate::time::{now_stamp, stamp_before}; /// A task row as read back. Deadline and meeting are typed; the rest is text or numbers. #[derive(Debug, Clone, PartialEq)] @@ -126,7 +127,9 @@ pub struct TaskEdit { pub enum MoveOutcome { /// The task is now in the target column. Moved, - /// The task was already in the target column. + /// The task stayed in its column and took a new place in it (Manual sort only). + Reordered, + /// The task was already in the target column and no place was asked for. Unchanged, /// The task is no longer in the column the client last saw; someone else moved it. Stale, @@ -134,11 +137,45 @@ pub enum MoveOutcome { SubtasksOpen, } +/// Days a deleted task can be restored. Reason: there is no purge, so the recently deleted list covers the +/// last 30 days and older deletions are final. +pub const RESTORE_DAYS: u64 = 30; + +/// A deleted task as the recently deleted list shows it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DeletedTask { + /// Task id (ULID). + pub id: String, + /// Readable key `PREFIX-n`. + pub key: String, + /// Title. + pub title: String, + /// The parent task, for a subtask. + pub parent_id: Option, + /// When it was deleted (UTC stamp). + pub deleted_at: String, + /// The name of who deleted it, when the activity trail recorded it. + pub deleted_by: Option, +} + +/// The result of a restore that was not refused as missing. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RestoreOutcome { + /// The task and the subtasks deleted with it are live again. + Restored, + /// The parent task is still deleted. Restore the parent first. + ParentDeleted, + /// Deleted more than [`RESTORE_DAYS`] ago. + Expired, +} + /// Sorting of the board's cards. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum SortBy { - /// Earliest deadline first; tasks without a deadline last. + /// The order the cards were placed in (`position`). The default. Only here can a card be reordered. #[default] + Manual, + /// Earliest deadline first; tasks without a deadline last. Deadline, /// Newest first. Created, @@ -331,7 +368,7 @@ async fn task_row(conn: &Connection, board_id: &str, task_id: &str) -> Result Result { let found = fetch_opt( conn, - "SELECT 1 FROM members WHERE sub = ?1 AND disabled = 0 AND role IN ('admin', 'member')", + "SELECT 1 FROM members WHERE sub = ?1 AND disabled = 0 AND (im_admin = 1 OR role IN ('admin', 'member'))", (sub.to_owned(),), |row| col_int(row, 0), ) @@ -378,15 +415,19 @@ async fn next_position(conn: &Connection, column_id: &str) -> Result { Ok(position_between(last, None)) } +/// The smallest gap between two neighbours that a midpoint can still split. Below it the next card placed +/// between them would get the same float, so the column is renumbered first. +const MIN_GAP: f64 = 1e-9; + /// Position for a task placed at `index` among the top-level cards of a column, between its neighbours /// there. The moving task itself is left out, so a card never sits between itself and a neighbour. An -/// index past the end places the task last. +/// index past the end places the task last. `None` when the neighbours are too close to split. async fn position_at( conn: &Connection, column_id: &str, moving_id: &str, index: usize, -) -> Result { +) -> Result> { let positions = fetch_all( conn, "SELECT position FROM tasks WHERE column_id = ?1 AND id <> ?2 AND parent_id IS NULL \ @@ -398,7 +439,51 @@ async fn position_at( let index = index.min(positions.len()); let before = index.checked_sub(1).map(|i| positions[i]); let after = positions.get(index).copied(); - Ok(position_between(before, after)) + let too_close = matches!((before, after), (Some(b), Some(a)) if a - b < MIN_GAP); + Ok((!too_close).then(|| position_between(before, after))) +} + +/// Renumbers the top-level live cards of a column to 1, 2, 3, ... in their current order, with the moving +/// task put at `index`. Returns the moving task's new position. Subtask positions are not touched. +async fn renumber_column( + conn: &Connection, + column_id: &str, + moving_id: &str, + index: usize, +) -> Result { + let mut order = fetch_all( + conn, + "SELECT id FROM tasks WHERE column_id = ?1 AND id <> ?2 AND parent_id IS NULL \ + AND deleted_at IS NULL ORDER BY position, id", + (column_id.to_owned(), moving_id.to_owned()), + |row| col_text(row, 0), + ) + .await?; + let index = index.min(order.len()); + order.insert(index, moving_id.to_owned()); + for (number, id) in order.iter().enumerate() { + conn.execute( + "UPDATE tasks SET position = ?2 WHERE id = ?1", + (id.clone(), (number + 1) as f64), + ) + .await + .map_err(db_err)?; + } + Ok((index + 1) as f64) +} + +/// The position of a task placed at `index` in a column: between its neighbours, or after a renumber when +/// they are too close to split. +async fn place_at( + conn: &Connection, + column_id: &str, + moving_id: &str, + index: usize, +) -> Result { + match position_at(conn, column_id, moving_id, index).await? { + Some(position) => Ok(position), + None => renumber_column(conn, column_id, moving_id, index).await, + } } /// Appends a row to the transitions table. `from` is `None` for the first placement. @@ -703,7 +788,8 @@ impl Store { /// one transition and one `task_moved` activity row. /// /// `index` is the place among the column's top-level cards (0 is the top); `None` appends. A move - /// inside the same column is `Unchanged`: reordering within a column is not a move. + /// inside the same column is not a move: with a place it is a `Reordered` (one activity row, no + /// transition); without one it is `Unchanged`. The caller asks for a place only under the Manual sort. pub async fn move_task( &self, board_id: &str, @@ -725,7 +811,32 @@ impl Store { return Ok(MoveOutcome::Stale); } if task.column_id == target.id { - return Ok(MoveOutcome::Unchanged); + let Some(index) = index else { + return Ok(MoveOutcome::Unchanged); + }; + let position = place_at(&tx, &target.id, task_id, index).await?; + tx.execute( + "UPDATE tasks SET position = ?3, updated_at = ?4 \ + WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", + ( + task_id.to_owned(), + board_id.to_owned(), + position, + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + log( + &tx, + task_id, + actor, + "task_reordered", + None, + serde_json::json!({ "column": target.id, "index": index }), + ) + .await?; + return Ok(MoveOutcome::Reordered); } if target.is_done { let open = fetch_opt( @@ -741,7 +852,7 @@ impl Store { } } let position = match index { - Some(index) => position_at(&tx, &target.id, task_id, index).await?, + Some(index) => place_at(&tx, &target.id, task_id, index).await?, None => next_position(&tx, &target.id).await?, }; let now = now_stamp(); @@ -869,6 +980,152 @@ impl Store { finish(tx, outcome).await } + /// The tasks deleted within [`RESTORE_DAYS`], newest deletion first. `deleted_by` is the name of the + /// member on the task's last `task_deleted` activity row, when there is one. + pub async fn deleted_tasks(&self, board_id: &str) -> Result> { + let cutoff = stamp_before(Duration::from_secs(RESTORE_DAYS * 24 * 60 * 60)); + let conn = self.read_conn().await; + let rows = fetch_all( + &conn, + "SELECT id, key, title, parent_id, deleted_at FROM tasks \ + WHERE board_id = ?1 AND deleted_at IS NOT NULL AND deleted_at >= ?2 \ + ORDER BY deleted_at DESC, key", + (board_id.to_owned(), cutoff), + |row| { + Ok(( + col_text(row, 0)?, + col_text(row, 1)?, + col_text(row, 2)?, + col_opt_text(row, 3)?, + col_text(row, 4)?, + )) + }, + ) + .await?; + let mut deleted = Vec::with_capacity(rows.len()); + for (id, key, title, parent_id, deleted_at) in rows { + let deleted_by = fetch_opt( + &conn, + "SELECT m.name FROM activity a JOIN members m ON m.sub = a.actor \ + WHERE a.task_id = ?1 AND a.kind = 'task_deleted' ORDER BY a.at DESC LIMIT 1", + (id.clone(),), + |row| col_text(row, 0), + ) + .await?; + deleted.push(DeletedTask { + id, + key, + title, + parent_id, + deleted_at, + deleted_by, + }); + } + Ok(deleted) + } + + /// Brings a deleted task back in one transaction. The subtasks deleted with it (the same deletion + /// stamp) come back too. A task whose column was retired goes to the board's first column that is not + /// done, and loses `done_at` there. A task whose parent is still deleted is refused (`ParentDeleted`), + /// and so is one deleted more than [`RESTORE_DAYS`] ago (`Expired`). Reminders are rebuilt. Links cleared + /// by the deletion are not restored, and the files of a deleted task were removed with it. + pub async fn restore_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 { + let task = fetch_opt( + &tx, + &format!( + "SELECT {TASK_COLS} FROM tasks WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NOT NULL" + ), + (task_id.to_owned(), board_id.to_owned()), + map_task, + ) + .await? + .ok_or(Error::NotFound)?; + let Some(deleted_at) = task.deleted_at.clone() else { + return Err(Error::NotFound); + }; + if deleted_at < stamp_before(Duration::from_secs(RESTORE_DAYS * 24 * 60 * 60)) { + return Ok(RestoreOutcome::Expired); + } + if let Some(parent) = &task.parent_id { + let parent_deleted = fetch_opt( + &tx, + "SELECT 1 FROM tasks WHERE id = ?1 AND deleted_at IS NOT NULL", + (parent.clone(),), + |row| col_int(row, 0), + ) + .await?; + if parent_deleted.is_some() { + return Ok(RestoreOutcome::ParentDeleted); + } + } + let mut rows = vec![task]; + rows.extend( + fetch_all( + &tx, + &format!( + "SELECT {TASK_COLS} FROM tasks WHERE parent_id = ?1 AND board_id = ?2 \ + AND deleted_at = ?3 ORDER BY position, id" + ), + (task_id.to_owned(), board_id.to_owned(), deleted_at), + map_task, + ) + .await?, + ); + let now = now_stamp(); + let live = live_columns(&tx, board_id).await?; + for row in rows { + let column = column_in(&tx, board_id, &row.column_id) + .await? + .filter(|c| c.deleted_at.is_none()); + let (column_id, is_done) = match column { + Some(column) => (column.id, column.is_done), + None => { + let first = live + .iter() + .find(|c| !c.is_done) + .ok_or_else(|| Error::Invalid("the board has no open column".into()))?; + (first.id.clone(), false) + } + }; + let done_at = is_done.then(|| row.done_at.clone().unwrap_or_else(|| now.clone())); + tx.execute( + "UPDATE tasks SET deleted_at = NULL, column_id = ?3, done_at = ?4, updated_at = ?5 \ + WHERE id = ?1 AND board_id = ?2", + ( + row.id.clone(), + board_id.to_owned(), + column_id.clone(), + done_at, + now.clone(), + ), + ) + .await + .map_err(db_err)?; + log( + &tx, + &row.id, + actor, + "task_restored", + None, + serde_json::json!({ "column": column_id }), + ) + .await?; + sync_reminders(&tx, &row.id).await?; + } + Ok(RestoreOutcome::Restored) + } + .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, @@ -1358,6 +1615,12 @@ impl Store { }); } match filter.sort { + SortBy::Manual => cards.sort_by(|a, b| { + a.task + .position + .total_cmp(&b.task.position) + .then(a.task.id.cmp(&b.task.id)) + }), SortBy::Deadline => cards.sort_by(|a, b| { a.task .deadline @@ -1673,6 +1936,72 @@ mod tests { assert_eq!(after.blocked, 0); } + /// A card moved to place 0 of its column is first under the Manual order (the default), and a move with no + /// place inside the column changes nothing. + #[tokio::test] + async fn manual_reorder_persists_the_place() { + 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(); + let second = store + .create_task(&board, new_task("Second", &backlog, &tag), "ada") + .await + .unwrap(); + let outcome = store + .move_task(&board, &second.id, &backlog, &backlog, Some(0), "ada") + .await + .unwrap(); + assert_eq!(outcome, MoveOutcome::Reordered); + let view = store + .board_view(&board, &BoardFilter::default(), &TimeZone::UTC) + .await + .unwrap(); + let titles: Vec<&str> = view.columns[0] + .cards + .iter() + .map(|c| c.task.title.as_str()) + .collect(); + assert_eq!(titles, ["Second", "First"]); + let unchanged = store + .move_task(&board, &second.id, &backlog, &backlog, None, "ada") + .await + .unwrap(); + assert_eq!(unchanged, MoveOutcome::Unchanged); + } + + /// Restoring a parent brings back the subtask deleted with it. The subtask alone is refused while the + /// parent is still deleted. + #[tokio::test] + async fn restore_brings_back_the_subtasks_deleted_with_the_parent() { + let (_dir, store, board) = seeded().await; + let tag = default_tag(&store, &board).await; + let backlog = store.columns(&board).await.unwrap()[0].id.clone(); + let parent = store + .create_task(&board, new_task("Parent", &backlog, &tag), "ada") + .await + .unwrap(); + let mut child = new_task("Child", &backlog, &tag); + child.parent_id = Some(parent.id.clone()); + let child = store.create_task(&board, child, "ada").await.unwrap(); + store.delete_task(&board, &parent.id, "ada").await.unwrap(); + assert_eq!(live_count(&store, &board).await, 0); + assert_eq!( + store.restore_task(&board, &child.id, "ada").await.unwrap(), + RestoreOutcome::ParentDeleted + ); + assert_eq!( + store.restore_task(&board, &parent.id, "ada").await.unwrap(), + RestoreOutcome::Restored + ); + // `live_count` sees top-level cards only; an empty deleted list shows the subtask is back too. + assert_eq!(live_count(&store, &board).await, 1); + assert!(store.deleted_tasks(&board).await.unwrap().is_empty()); + } + #[tokio::test] async fn search_folds_turkish_dotted_and_dotless_i() { let (_dir, store, board) = seeded().await; diff --git a/crates/iz-core/src/time.rs b/crates/iz-core/src/time.rs index 267c243..ae0517a 100644 --- a/crates/iz-core/src/time.rs +++ b/crates/iz-core/src/time.rs @@ -44,6 +44,13 @@ pub fn stamp_after(after: Duration) -> String { format_stamp(OffsetDateTime::now_utc().saturating_add(delta)) } +/// The stamp of the time `before` ago. Text order is time order, so `deleted_at >= stamp_before(d)` is +/// "deleted within the last `d`". +pub fn stamp_before(before: Duration) -> String { + let delta = SignedDuration::try_from(before).unwrap_or(SignedDuration::MAX); + format_stamp(OffsetDateTime::now_utc().saturating_sub(delta)) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/iz-web/assets/board.js b/crates/iz-web/assets/board.js index 7c82ce0..6917438 100644 --- a/crates/iz-web/assets/board.js +++ b/crates/iz-web/assets/board.js @@ -8,11 +8,15 @@ * column the page last showed (`from`), the target column (`to`) and the place (`position`), and * asks for JSON. The server's answer decides: {ok: true} keeps the card where it was dropped; * anything else puts it back and shows a toast with the server's translated message. + * - Under the Manual sort (data-sort on the section) a card can also be dropped at a new place in its own + * column. That sends the same POST with `from` equal to `to` and the new place. Under any other sort a + * drop in the same column changes nothing, and a card dropped in another column goes to its end (no + * place is sent). * - A drag that ends outside any column puts the card back where it was. * * It also closes the task modal on Escape (see below). What it never does: decide anything about the move itself. The server checks the column, the - * subtasks, the role and the token; this script only shows the result. Dropping onto the card's own - * column is nothing to send, so it puts the card back. + * subtasks, the role and the token, and it ignores a place unless the sort is manual; this script only + * shows the result. Dropping onto the card's own spot is nothing to send, so it puts the card back. * * The CSRF token comes from data-csrf on the section, which the server renders for this session. The * file is one IIFE with no globals, and it is loaded with `defer`. @@ -47,6 +51,9 @@ /** The text shown when the request never got an answer. Rendered in the page's language. */ const failedText = board.dataset.msgFailed || "The card could not be moved. Try again."; + /** Whether the board shows the Manual order, the only order in which a place in a column is kept. */ + const manual = board.dataset.sort === "manual"; + /** The card being dragged, its place before the drag, and the column it started in. */ let dragged = null; let origin = null; @@ -99,10 +106,17 @@ setTimeout(() => el.remove(), TOAST_MS); } - /** Sends the move and applies the answer. A card the server refused goes back to its place. */ + /** Sends the move and applies the answer. A card the server refused goes back to its place. `index` is + * null when no place is sent (any sort but Manual, or a drop that is not a reorder). */ async function send(card, start, from, to, index) { const id = card.dataset.taskId; - const body = new URLSearchParams({ csrf, from, to, position: String(index) }); + const body = new URLSearchParams({ + csrf, + from, + to, + sort: board.dataset.sort || "", + position: index === null ? "" : String(index), + }); let answer = null; let data = null; try { @@ -130,27 +144,35 @@ const card = event.target.closest(".card[data-task-id]"); if (!card) return; dragged = card; - origin = { parent: card.parentNode, next: card.nextSibling }; + origin = { parent: card.parentNode, next: card.nextSibling, index: indexIn(card.parentNode, card) }; card.classList.add("is-dragging"); event.dataTransfer.effectAllowed = "move"; event.dataTransfer.setData("text/plain", card.dataset.taskId || ""); } - /** Moves the card in the page while the pointer is over another column. */ + /** Moves the card in the page while the pointer is over a column. Within its own column only the Manual + * order places it by the pointer; any other order keeps it where it was. In another column it goes to the + * place the pointer shows under Manual, and to the end otherwise (the server does the same). */ function onDragOver(event) { if (!dragged) return; const list = event.currentTarget; - if (columnOf(list) === columnOf(origin.parent)) { + const same = columnOf(list) === columnOf(origin.parent); + if (same && !manual) { restore(dragged, origin); return; } event.preventDefault(); event.dataTransfer.dropEffect = "move"; - placeAt(list, dragged, event.clientY); + if (manual) { + placeAt(list, dragged, event.clientY); + } else { + list.appendChild(dragged); + } dragged.dataset.columnId = columnOf(list); } - /** A drop in another column sends the move. A drop in the same column changes nothing. */ + /** A drop in another column sends the move. A drop in the same column sends a reorder under Manual, when + * the place changed; otherwise it changes nothing. */ function onDrop(event) { if (!dragged) return; const list = event.currentTarget; @@ -163,11 +185,11 @@ dragged = null; origin = null; card.classList.remove("is-dragging"); - if (from === to) { + if (from === to && (!manual || index === start.index)) { restore(card, start); return; } - send(card, start, from, to, index); + send(card, start, from, to, manual ? index : null); } /** A drag that ends without a drop (Escape, a drop outside) puts the card back. */ diff --git a/crates/iz-web/src/i18n/admin.rs b/crates/iz-web/src/i18n/admin.rs index c57859c..7067954 100644 --- a/crates/iz-web/src/i18n/admin.rs +++ b/crates/iz-web/src/i18n/admin.rs @@ -141,8 +141,24 @@ pub enum K { ReasonColumn, ReasonProject, FilterKind, + // Recently deleted (settings card) + DeletedHeading, + DeletedHelp, + DeletedEmpty, + DeletedTaskHeader, + DeletedAtHeader, + DeletedByHeader, + DeletedUnknown, + RestoreButton, + NoticeTaskRestored, + // Members whose role im sets + ImRoleLocked, // Errors ErrBackupOff, + ErrParentDeleted, + ErrRestoreExpired, + ErrRestoreFailed, + ErrRestoreMissing, } /// The text of `key` in `lang`. Placeholders are `{}` and are filled by [`fill`]. @@ -291,6 +307,44 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::ErrBackupOff, Tr) => { "Yedekleme kapalı, başlatılacak bir şey yok. Önce [backup] dir ayarlayın." } + (K::DeletedHeading, En) => "Recently deleted", + (K::DeletedHeading, Tr) => "Son silinenler", + (K::DeletedHelp, En) => { + "Tasks deleted in the last 30 days. Restoring one brings back the subtasks deleted with it. Links and files removed by the deletion are not brought back." + } + (K::DeletedHelp, Tr) => { + "Son 30 günde silinen görevler. Birini geri yüklemek, onunla birlikte silinen alt görevleri de getirir. Silme sırasında kaldırılan bağlantılar ve dosyalar geri gelmez." + } + (K::DeletedEmpty, En) => "Nothing was deleted in the last 30 days.", + (K::DeletedEmpty, Tr) => "Son 30 günde silinen görev yok.", + (K::DeletedTaskHeader, En) => "Task", + (K::DeletedTaskHeader, Tr) => "Görev", + (K::DeletedAtHeader, En) => "Deleted", + (K::DeletedAtHeader, Tr) => "Silinme", + (K::DeletedByHeader, En) => "By", + (K::DeletedByHeader, Tr) => "Silen", + (K::DeletedUnknown, En) => "not recorded", + (K::DeletedUnknown, Tr) => "kaydedilmemiş", + (K::RestoreButton, En) => "Restore", + (K::RestoreButton, Tr) => "Geri yükle", + (K::NoticeTaskRestored, En) => "The task was restored.", + (K::NoticeTaskRestored, Tr) => "Görev geri yüklendi.", + (K::ImRoleLocked, En) => { + "This person is an administrator in im, so the role stays admin here and cannot be changed." + } + (K::ImRoleLocked, Tr) => { + "Bu kişi im'de yönetici. Buradaki rolü admin olarak kalır ve değiştirilemez." + } + (K::ErrParentDeleted, En) => "The parent task is still deleted. Restore the parent first.", + (K::ErrParentDeleted, Tr) => "Üst görev hâlâ silinmiş. Önce üst görevi geri yükleyin.", + (K::ErrRestoreExpired, En) => { + "This task was deleted more than 30 days ago, so it cannot be restored." + } + (K::ErrRestoreExpired, Tr) => "Bu görev 30 günden önce silindi, geri yüklenemez.", + (K::ErrRestoreFailed, En) => "The task could not be restored.", + (K::ErrRestoreFailed, Tr) => "Görev geri yüklenemedi.", + (K::ErrRestoreMissing, En) => "That task is not in the recently deleted list.", + (K::ErrRestoreMissing, Tr) => "Bu görev son silinenler listesinde yok.", (K::RulesTitle, En) => "Mail rules", (K::RulesTitle, Tr) => "Mail kuralları", (K::RulesHelp, En) => "A rule mails people when something happens on the board.", diff --git a/crates/iz-web/src/i18n/board.rs b/crates/iz-web/src/i18n/board.rs index db3e9ea..490ba51 100644 --- a/crates/iz-web/src/i18n/board.rs +++ b/crates/iz-web/src/i18n/board.rs @@ -41,12 +41,16 @@ pub enum K { FilterNobody, /// The label of the sort order. FilterSort, - /// The sort order by deadline (the default). + /// The sort order the cards were placed in (the default). The only order where a card can be reordered. + SortManual, + /// The sort order by deadline. SortDeadline, /// The sort order newest first. SortCreated, /// The sort order by title. SortTitle, + /// The hint under the board when the sort is not Manual: a drag can only move a card to another column. + SortManualHint, /// The label of the search box. FilterSearch, /// The placeholder of the search box. @@ -148,6 +152,14 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::FilterNobody, Lang::Tr) => "Kimse", (K::FilterSort, Lang::En) => "Sort", (K::FilterSort, Lang::Tr) => "Sırala", + (K::SortManual, Lang::En) => "Manual", + (K::SortManual, Lang::Tr) => "Elle", + (K::SortManualHint, Lang::En) => { + "Reordering a card needs the Manual sort. Here a card can only move to another column, at its end." + } + (K::SortManualHint, Lang::Tr) => { + "Kartların sırasını değiştirmek için Elle sıralama gerekir. Burada bir kart yalnızca başka bir sütuna, sonuna taşınabilir." + } (K::SortDeadline, Lang::En) => "Deadline", (K::SortDeadline, Lang::Tr) => "Son tarih", (K::SortCreated, Lang::En) => "Newest first", diff --git a/crates/iz-web/src/i18n/task.rs b/crates/iz-web/src/i18n/task.rs index edf92ce..9ea39c4 100644 --- a/crates/iz-web/src/i18n/task.rs +++ b/crates/iz-web/src/i18n/task.rs @@ -117,6 +117,10 @@ pub enum K { ActMoved, /// Activity: the task was deleted. ActDeleted, + /// Activity: the task was placed at a new spot in its column (Manual sort). + ActReordered, + /// Activity: an administrator restored the deleted task. + ActRestored, /// Activity: someone was assigned. ActAssigned, /// Activity: someone was unassigned. @@ -354,6 +358,10 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::ActMoved, Lang::Tr) => "görevi taşıdı", (K::ActDeleted, Lang::En) => "deleted the task", (K::ActDeleted, Lang::Tr) => "görevi sildi", + (K::ActReordered, Lang::En) => "moved the card within its column", + (K::ActReordered, Lang::Tr) => "kartı sütunu içinde taşıdı", + (K::ActRestored, Lang::En) => "restored the deleted task", + (K::ActRestored, Lang::Tr) => "silinen görevi geri yükledi", (K::ActAssigned, Lang::En) => "assigned someone", (K::ActAssigned, Lang::Tr) => "birini atadı", (K::ActUnassigned, Lang::En) => "removed an assignee", @@ -492,6 +500,8 @@ pub fn activity_kind(lang: Lang, kind: &str) -> &'static str { "task_edited" => K::ActEdited, "task_moved" => K::ActMoved, "task_deleted" => K::ActDeleted, + "task_reordered" => K::ActReordered, + "task_restored" => K::ActRestored, "assigned" => K::ActAssigned, "unassigned" => K::ActUnassigned, "tag_changed" => K::ActTagChanged, diff --git a/crates/iz-web/src/pages/admin.rs b/crates/iz-web/src/pages/admin.rs index 1bb103d..b8e3a50 100644 --- a/crates/iz-web/src/pages/admin.rs +++ b/crates/iz-web/src/pages/admin.rs @@ -55,6 +55,7 @@ pub fn notice_text(lang: Lang, code: &str, queued: Option<&str>) -> Option t(lang, K::NoticeRetried).to_owned(), "backup" => t(lang, K::NoticeBackupStarted).to_owned(), "role_set" => structure_t(lang, StructureK::NoticeRoleSet).to_owned(), + "task_restored" => t(lang, K::NoticeTaskRestored).to_owned(), "limits" => structure_t(lang, StructureK::NoticeLimitsSaved).to_owned(), "storage" => structure_t(lang, StructureK::NoticeStorageSaved).to_owned(), "tag_added" | "tag_renamed" | "tag_coloured" | "tag_deleted" | "tag_moved" => { diff --git a/crates/iz-web/src/pages/board.rs b/crates/iz-web/src/pages/board.rs index 8652da9..86bb75e 100644 --- a/crates/iz-web/src/pages/board.rs +++ b/crates/iz-web/src/pages/board.rs @@ -64,7 +64,7 @@ pub struct Filters { pub tag: String, /// `none` for nobody, a member id, or empty for anyone. pub assignee: String, - /// `deadline` (the default), `created` or `title`. + /// `manual` (the default: the order the cards were placed in), `deadline`, `created` or `title`. pub sort: &'static str, /// The search text, trimmed and at most [`SEARCH_MAX`] characters. pub query: String, @@ -75,7 +75,7 @@ impl Filters { pub fn active(&self) -> bool { !self.tag.is_empty() || !self.assignee.is_empty() - || self.sort != "deadline" + || self.sort != "manual" || !self.query.is_empty() } } @@ -135,8 +135,8 @@ pub fn query_of(path: &str) -> Option<&str> { } /// Reads the filters from a query string. A bogus project or member id is dropped, as the page would -/// otherwise show an empty board for a filter the viewer cannot see. An unknown sort falls back to the -/// deadline order. +/// otherwise show an empty board for a filter the viewer cannot see. An unknown or missing sort is the +/// Manual order. pub fn parse_filters(query: Option<&str>, tags: &[Tag], members: &[Member]) -> Filters { let pairs = pairs(query.unwrap_or("")); let get = |name: &str| { @@ -161,9 +161,10 @@ pub fn parse_filters(query: Option<&str>, tags: &[Tag], members: &[Member]) -> F String::new() }; let (sort, sort_by) = match get("sort").as_str() { + "deadline" => ("deadline", SortBy::Deadline), "created" => ("created", SortBy::Created), "title" => ("title", SortBy::Title), - _ => ("deadline", SortBy::Deadline), + _ => ("manual", SortBy::Manual), }; let query: String = get("q").chars().take(SEARCH_MAX).collect(); let filter = BoardFilter { @@ -194,7 +195,7 @@ pub fn board_url(filters: &Filters, extra: &[(&str, &str)]) -> String { if !filters.assignee.is_empty() { parts.push(format!("assignee={}", percent_encode(&filters.assignee))); } - if filters.sort != "deadline" { + if filters.sort != "manual" { parts.push(format!("sort={}", filters.sort)); } if !filters.query.is_empty() { @@ -212,7 +213,7 @@ pub fn board_url(filters: &Filters, extra: &[(&str, &str)]) -> String { /// Whether a member may be assigned: enabled, and an admin or a member (not a viewer or no-access). fn assignable(member: &Member) -> bool { - !member.disabled && matches!(member.role, Role::Admin | Role::Member) + !member.disabled && matches!(member.effective_role(), Role::Admin | Role::Member) } /// Loads the board for `me` with the filters of `query`. The caller sets the form, alert and notice. @@ -236,7 +237,7 @@ pub async fn load( let can_write = authorize(&me.actor(), &Action::WriteTask).is_ok(); let viewer = ViewerInfo { name: me.member.name.clone(), - is_admin: me.member.im_admin || me.member.role == Role::Admin, + is_admin: me.member.effective_role() == Role::Admin, csrf: me.session.csrf_token.clone(), }; Ok(BoardPage { @@ -407,7 +408,7 @@ mod tests { #[test] fn board_url_keeps_only_set_filters() { let mut filters = Filters { - sort: "deadline", + sort: "manual", ..Filters::default() }; assert_eq!(board_url(&filters, &[]), "/"); @@ -419,7 +420,7 @@ mod tests { #[test] fn unknown_sort_and_empty_filters_fall_back() { let filters = parse_filters(Some("sort=bogus&tag=nope&assignee=nobody-here"), &[], &[]); - assert_eq!(filters.sort, "deadline"); + assert_eq!(filters.sort, "manual"); assert!(filters.tag.is_empty()); assert!(filters.assignee.is_empty()); assert!(!filters.active()); diff --git a/crates/iz-web/src/pages/files.rs b/crates/iz-web/src/pages/files.rs index cca7df1..b09ea09 100644 --- a/crates/iz-web/src/pages/files.rs +++ b/crates/iz-web/src/pages/files.rs @@ -694,7 +694,7 @@ async fn viewer_page(cx: &Cx) -> Result { let view = load_view(state, &attachment, &base, sheet).await?; let viewer = ViewerInfo { name: me.member.name.clone(), - is_admin: me.member.im_admin || me.member.role == iz_core::authz::Role::Admin, + is_admin: me.member.effective_role() == iz_core::authz::Role::Admin, csrf: me.session.csrf_token.clone(), }; let back_to = format!("/?task={}", percent_encode(&key)); diff --git a/crates/iz-web/src/pages/people.rs b/crates/iz-web/src/pages/people.rs index 661a075..9d6600c 100644 --- a/crates/iz-web/src/pages/people.rs +++ b/crates/iz-web/src/pages/people.rs @@ -48,7 +48,11 @@ async fn person_page(cx: &Cx) -> Result { // The target must be a member of this board. Anything else is a plain 404. let target: Member = match state.store.member(&sub).await.map_err(core_err)? { - Some(member) if member.role != iz_core::authz::Role::NoAccess && !member.disabled => member, + Some(member) + if member.effective_role() != iz_core::authz::Role::NoAccess && !member.disabled => + { + member + } _ => return Err(not_found().into()), }; if authorize(&me.actor(), &Action::ViewPerson).is_err() { @@ -94,7 +98,7 @@ async fn person_page(cx: &Cx) -> Result { .map(|stamp| local_text(stamp, &zone)) .filter(|text| !text.is_empty()) .unwrap_or_else(|| t(language, K::PersonNeverSignedIn).to_owned()); - let role = role_word(language, target.role.as_str()).to_owned(); + let role = role_word(language, target.effective_role().as_str()).to_owned(); let viewer = ViewerInfo { name: me.member.name.clone(), is_admin: authorize(&me.actor(), &Action::Administer).is_ok(), diff --git a/crates/iz-web/src/pages/photo.rs b/crates/iz-web/src/pages/photo.rs index 1ff527c..b60959a 100644 --- a/crates/iz-web/src/pages/photo.rs +++ b/crates/iz-web/src/pages/photo.rs @@ -41,7 +41,7 @@ async fn photo(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec)> { return Err(not_found().into()); }; // A disabled member, or one with no role, has no access to the board, so no photo either. - if member.disabled || member.role == Role::NoAccess { + if member.disabled || member.effective_role() == Role::NoAccess { return Err(not_found().into()); } diff --git a/crates/iz-web/src/pages/settings.rs b/crates/iz-web/src/pages/settings.rs index 8f18e1d..62b3bc7 100644 --- a/crates/iz-web/src/pages/settings.rs +++ b/crates/iz-web/src/pages/settings.rs @@ -11,6 +11,7 @@ use iz_core::sender::{ DEFAULT_FROM_NAME, DEFAULT_PORT, SenderInput, TlsMode, validate_password, validate_sender, }; use iz_core::store::sender::{ReminderSettings, SenderState}; +use iz_core::store::tasks::RestoreOutcome; use jiff::Timestamp; use serde::Deserialize; use topcoat::Result; @@ -30,7 +31,7 @@ use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, record, user_tex use crate::pages::board::the_board; use crate::pages::task::local_text; use crate::state::AppState; -use crate::views::admin::{BackupCard, SenderForm, SettingsView, settings_content}; +use crate::views::admin::{BackupCard, DeletedRow, SenderForm, SettingsView, settings_content}; use crate::views::structure::{MemberRow, ServerInfo, StorageInfo}; use crate::views::{ViewerInfo, respond, shell}; use iz_core::authz::Role; @@ -119,16 +120,31 @@ async fn settings_view( .await? .into_iter() .map(|m| MemberRow { + role: m.effective_role().as_str().to_owned(), sub: m.sub, name: m.name, email: m.email, - role: m.role.as_str().to_owned(), im_admin: m.im_admin, disabled: m.disabled, }) .collect(); let limit_mib = (policy.limit_bytes / (1024 * 1024)).to_string(); let extensions = policy.extensions.join(" "); + let zone = parse_zone(&me.member.zoneinfo).unwrap_or(TimeZone::UTC); + let board = the_board(&state.store).await?; + let deleted = state + .store + .deleted_tasks(&board.id) + .await? + .into_iter() + .map(|task| DeletedRow { + id: task.id, + key: task.key, + title: task.title, + at: local_text(&task.deleted_at, &zone), + by: task.deleted_by, + }) + .collect(); Ok(SettingsView { lang, configured: stored.sender.is_some(), @@ -143,6 +159,7 @@ async fn settings_view( server: server_info(state).await?, storage, backup: backup_card(state, me).await?, + deleted, }) } @@ -531,6 +548,17 @@ async fn save_role(cx: &Cx, form: Option>) -> Result let target = path_param_segment(cx, "sub").to_owned(); let me = require_csrf(cx, Need::Admin, &form.csrf).await?; let language = lang(cx, me.member.locale_override.as_deref()); + // An im administrator's role is not changed here: the page shows it read-only, and a forged post is refused too. + if state + .store + .member(&target) + .await? + .is_some_and(|member| member.im_admin) + { + let message = t(language, K::ImRoleLocked).to_owned(); + let page = settings_view(state, &me, language, None, None, Some(message)).await?; + return render(cx, &me, page, REFUSED).await; + } let outcome: iz_core::Result<()> = async { let role = Role::parse(&form.role) .ok_or_else(|| iz_core::Error::Invalid("unknown role".into()))?; @@ -566,6 +594,47 @@ async fn save_role(cx: &Cx, form: Option>) -> Result } } +/// `POST /settings/deleted/{id}/restore`: brings a task deleted in the last 30 days back. Administrators +/// only (`require_csrf` with `Need::Admin` is the `Administer` check of `authz`), CSRF first. A refusal the +/// admin can read (a deleted parent, an expired deletion) re-renders the page with its reason. +#[route(POST "/settings/deleted/{id}/restore")] +async fn restore_deleted(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let task_id = path_param_segment(cx, "id").to_owned(); + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; + let language = lang(cx, me.member.locale_override.as_deref()); + let board = the_board(&state.store).await?; + let outcome = state + .store + .restore_task(&board.id, &task_id, &me.member.sub) + .await; + let refusal = match outcome { + Ok(RestoreOutcome::Restored) => { + record( + state, + &me, + "task.restore", + "task", + Some(&task_id), + serde_json::json!({}), + ) + .await; + state.live.bump(&Topic::Board(board.id.clone())); + state.live.bump(&Topic::Admin(AdminSection::Settings)); + return back("/settings?notice=task_restored#deleted"); + } + Ok(RestoreOutcome::ParentDeleted) => K::ErrParentDeleted, + Ok(RestoreOutcome::Expired) => K::ErrRestoreExpired, + Err(iz_core::Error::NotFound) => K::ErrRestoreMissing, + Err(iz_core::Error::Invalid(_)) => K::ErrRestoreFailed, + Err(error) => return Err(error.into()), + }; + let message = t(language, refusal).to_owned(); + let page = settings_view(state, &me, language, None, None, Some(message)).await?; + render(cx, &me, page, REFUSED).await +} + /// `POST /settings/attachments`: where attachments are kept. Saving only records the choice; the mover brings the /// files over in the background. `in` needs the Files service to be set up on this server. #[route(POST "/settings/attachments")] diff --git a/crates/iz-web/src/pages/sign_in.rs b/crates/iz-web/src/pages/sign_in.rs index a03cbcf..6b2ccc0 100644 --- a/crates/iz-web/src/pages/sign_in.rs +++ b/crates/iz-web/src/pages/sign_in.rs @@ -263,7 +263,7 @@ async fn callback(cx: &Cx) -> Result { } Err(error) => return Err(error.into()), }; - if stored.disabled || stored.role == Role::NoAccess { + if stored.disabled || stored.effective_role() == Role::NoAccess { tracing::info!(sub = %stored.sub, "sign-in: no access for this member"); return message( cx, diff --git a/crates/iz-web/src/pages/tasks.rs b/crates/iz-web/src/pages/tasks.rs index 3e81699..cc10818 100644 --- a/crates/iz-web/src/pages/tasks.rs +++ b/crates/iz-web/src/pages/tasks.rs @@ -79,6 +79,10 @@ struct MoveForm { /// The place among the column's cards, from the top. Empty appends. #[serde(default)] position: String, + /// The sort the board was showing. A place counts only under `manual`; otherwise a card that moves + /// to another column goes to its end, and a drop inside a column changes nothing. + #[serde(default)] + sort: String, /// The board URL the form was on, so a form answer returns there. #[serde(default)] next: String, @@ -366,6 +370,7 @@ async fn move_task(cx: &Cx, form: Option>) -> Result { let refusal = refused(422, "invalid", K::InvalidForm); return refuse_write(&at, refusal, None).await; }; + let index = if form.sort == "manual" { index } else { None }; let outcome = state .store .move_task( @@ -390,8 +395,8 @@ async fn move_task(cx: &Cx, form: Option>) -> Result { Err(error) => return Err(error.into()), }; let refusal = match outcome { - MoveOutcome::Moved | MoveOutcome::Unchanged => { - if outcome == MoveOutcome::Moved { + MoveOutcome::Moved | MoveOutcome::Reordered | MoveOutcome::Unchanged => { + if matches!(outcome, MoveOutcome::Moved | MoveOutcome::Reordered) { state.live.bump(&Topic::Board(board.id.clone())); } if json { diff --git a/crates/iz-web/src/views/admin.rs b/crates/iz-web/src/views/admin.rs index f7a0f6b..b57544f 100644 --- a/crates/iz-web/src/views/admin.rs +++ b/crates/iz-web/src/views/admin.rs @@ -140,6 +140,23 @@ pub struct SettingsView { pub storage: crate::views::structure::StorageInfo, /// The Backups card: whether backups are on, and the outcome of the last runs. pub backup: BackupCard, + /// The Recently deleted card: tasks deleted within the restore window, newest first. + pub deleted: Vec, +} + +/// One row of the Recently deleted card. `at` is already in the viewer's zone. +#[derive(Debug, Clone, Default)] +pub struct DeletedRow { + /// Task id, for the restore form. + pub id: String, + /// Readable key `PREFIX-n`. + pub key: String, + /// Title. + pub title: String, + /// When it was deleted, as `YYYY-MM-DD HH:MM`. + pub at: String, + /// The name of who deleted it, when the activity trail recorded it. + pub by: Option, } /// The Backups card. Times are already in the viewer's zone; an empty text means nothing was recorded. @@ -366,6 +383,45 @@ pub async fn settings_content(page: &SettingsView, csrf: &str) -> Result(t(lang, K::BackupOff))

} +
+

(t(lang, K::DeletedHeading))

+

(t(lang, K::DeletedHelp))

+ if page.deleted.is_empty() { +

(t(lang, K::DeletedEmpty))

+ } else { + + + + + + + + + + + for row in page.deleted.iter() { + + + + + + + } + +
(t(lang, K::DeletedTaskHeader))(t(lang, K::DeletedAtHeader))(t(lang, K::DeletedByHeader))
(row.key.as_str()) " " (row.title.as_str())(row.at.as_str()) + if let Some(name) = &row.by { + (name.as_str()) + } else { + (t(lang, K::DeletedUnknown)) + } + +
+ + +
+
+ } +
members_section(lang: lang, members: &page.members, csrf: csrf) storage_section(lang: lang, info: &page.storage, csrf: csrf) limits_section(lang: lang, limit_mib: page.limit_mib.as_str(), extensions: page.extensions.as_str(), csrf: csrf) diff --git a/crates/iz-web/src/views/board.rs b/crates/iz-web/src/views/board.rs index 3c38a0b..3ce9baf 100644 --- a/crates/iz-web/src/views/board.rs +++ b/crates/iz-web/src/views/board.rs @@ -63,6 +63,7 @@ pub async fn board_content(page: &BoardPage) -> Result {
@@ -85,6 +86,9 @@ pub async fn board_content(page: &BoardPage) -> Result { } if page.can_write {

(t(lang, K::DragHint))

+ if page.filters.sort != "manual" { +

(t(lang, K::SortManualHint))

+ } } else {

(t(lang, K::ReadOnly))

} @@ -138,6 +142,7 @@ pub async fn filter_bar(page: &BoardPage) -> Result {
+ } } diff --git a/docs/architecture.md b/docs/architecture.md index c41dd70..6910666 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -90,7 +90,7 @@ board (partial unique index). Admin can add, rename, reorder, delete (only when **tasks**: `id`, `board_id`, `key` (UNIQUE per board, `PREFIX-` from a per-board counter: readable and never reused), `parent_id` NULL (one level, enforced by trigger and by store), `title` (1–200), `description` (≤20 000), -`column_id`, `tag_id` NOT NULL, `deadline` NULL (date), `meeting_at` NULL (UTC instant), `position` REAL, +`column_id`, `tag_id` NOT NULL, `deadline` NULL (date), `meeting_at` NULL (UTC instant), `position` REAL (the Manual order, section 5), `created_by`, `created_at`, `updated_at`, `done_at` NULL, `deleted_at` NULL. **task_assignees** (task, sub) PK. **task_watchers** (task, sub) PK — watchers receive "board" audience mail @@ -108,8 +108,9 @@ Authors may edit and delete their own comments (new: old iz had neither). **transitions**: `id`, `task_id`, `from_column` NULL, `to_column`, `actor`, `at`. -**activity**: `id`, `task_id` NULL, `actor` NULL (NULL = system), `subject` NULL, `kind` (enum with CHECK), -`detail` JSON, `at`. Rendered into sentences in the viewer's language at read time. +**activity**: `id`, `task_id` NULL, `actor` NULL (NULL = system), `subject` NULL, `kind` (enum with CHECK; migration +0007 added `task_reordered` and `task_restored`), `detail` JSON, `at`. Rendered into sentences in the viewer's +language at read time. **mail_rules**: `id`, `board_id`, `name`, `trigger` (enum CHECK, 12 triggers from inventory 2.9), `column_id` NULL (only for `status`, CHECK), `tag_id` NULL (new: limit a rule to one project), `audience` CHECK IN @@ -137,7 +138,7 @@ Pages (session; Viewer may read, writes need Member, admin pages need Admin; all | Path | What | |---|---| -| `GET /` | board (inventory 2.2): columns, cards, filters (`tag`, `assignee`, `sort`, `q`), overdue/blocked chips, card menus, drag and drop; `?task=` opens the task modal, `?new=1` the new-task modal | +| `GET /` | board (inventory 2.2): columns, cards, filters (`tag`, `assignee`, `sort` = `manual` (default), `deadline`, `created` or `title`, `q`), overdue/blocked chips, card menus, drag and drop; `?task=` opens the task modal, `?new=1` the new-task modal | | `POST /tasks`, `/tasks/{id}/edit`, `/tasks/{id}/move`, `/tasks/{id}/delete`, `/tasks/{id}/assign`, `/tasks/{id}/unassign`, `/tasks/{id}/tag`, `/tasks/{id}/parent`, `/tasks/{id}/links`, `/tasks/{id}/links/remove`, `/tasks/{id}/watch` | task writes | | `POST /tasks/{id}/comments`, `/comments/{id}/edit`, `/comments/{id}/delete` | comments | | `POST /tasks/{id}/files` (multipart, streamed), `/files/{id}/delete`; `GET /files/{id}` | attachments | @@ -147,12 +148,16 @@ Pages (session; Viewer may read, writes need Member, admin pages need Admin; all | `GET /columns` + POSTs | columns (admin) | | `GET /rules` + POSTs | mail rules (admin), sentence rendering, enable switch, edit | | `GET /logs` | admin: outbox (retry), decisions, activity (filters, keyset paging) | -| `GET /settings` + POSTs | profile/preferences (all); members & roles, sender (check, test), limits, attachment storage (+ migration status), message to members, server (admin); `POST /settings/backup` "Back up now" (admin, CSRF, audited, 303 back with a notice, 422 with an alert when `[backup]` is off); the Backups card shows the recorded outcome of the runs (section 8) | +| `GET /settings` + POSTs | profile/preferences (all); members & roles (an `im` administrator's role is shown, not offered for change), sender (check, test), limits, attachment storage (+ migration status), message to members, server (admin); `POST /settings/backup` "Back up now" (admin, CSRF, audited, 303 back with a notice, 422 with an alert when `[backup]` is off); the Backups card shows the recorded outcome of the runs (section 8); the Recently deleted card lists tasks deleted in the last 30 days (title, key, when, who) with `POST /settings/deleted/{id}/restore` (admin, CSRF, audited as `task.restore`, activity `task_restored`; section 5) | | `GET /avatar/{sub}` | photo proxy with disk cache, only for members of this board | | OIDC client routes, `/-/alive`, live streams, `/healthz`, `/assets/*` | | -`POST /tasks/{id}/move` carries the column the client last saw; a stale move is refused (`moved_already`), a -move into the done column with open subtasks is refused (`subtasks_open`), as in old iz. +`POST /tasks/{id}/move` carries the column the client last saw, the sort the board showed and, for a drop, the +place (`position`). A stale move is refused (`moved_already`), a move into the done column with open subtasks is +refused (`subtasks_open`), as in old iz. The place is used only under `sort=manual`: then a drop in the same column +is a reorder (`Reordered`, activity `task_reordered`), and a drop in another column lands at the place. Under any +other sort the place is ignored: a card moved to another column goes to the end of it, and a drop within its own +column changes nothing. --- @@ -162,6 +167,14 @@ move into the done column with open subtasks is refused (`subtasks_open`), as in overdue when the day is before today in the viewer's zone. - Done: entering the done column stamps `done_at`; leaving it clears it; a card with open subtasks cannot enter. - Subtasks: one level; a parent with children cannot become a subtask; deleting a parent deletes its children. +- Order: the default sort is Manual (`position`, then id). Each column's cards take their `position` from the + neighbours they are placed between; a column is renumbered (1, 2, 3, ...) only when two neighbours are less than + 1e-9 apart. Under deadline, created or title the only drag is to another column, which lands at its end. +- Restore: a deleted task can be restored for 30 days after its deletion (`RESTORE_DAYS`); there is no purge, so + older deletions are final. One transaction clears `deleted_at` on the task and on the subtasks that share its + deletion stamp. A task whose column was retired goes to the first column that is not done (and loses `done_at` + there). A subtask whose parent is still deleted is refused. Reminders are rebuilt. Links cleared by the deletion + and the files of the task (removed with it) do not come back. Only administrators (`Administer`). - Dependencies: no cycles over live edges; soft clear; a finished blocker stops blocking; deleting a blocker frees its dependents and fires `unblocked`. - Viewers: read-only, never assigned, never mailed. Members with role `none` or disabled: no access, not mailed. @@ -178,9 +191,12 @@ move into the done column with open subtasks is refused (`subtasks_open`), as in `authz::authorize(actor, action)` with `actor` = `Anonymous | Member { sub, role, im_admin, disabled }` and `action` from: `ReadBoard`, `WriteTask`, `Comment`, `EditComment { author }`, `UploadFile`, -`DeleteFile { uploader }`, `Administer`, `ViewPerson { sub }`. Roles: Admin ⊇ Member ⊇ Viewer; `none` and -disabled are denied everything (404 for pages, the sign-in card for `/`). Deleting a file: uploader while still a -Member, or Admin. Truth-table tested. +`DeleteFile { uploader }`, `Administer`, `ViewPerson { sub }`. Roles: Admin ⊇ Member ⊇ Viewer. An `im` +administrator (`im_admin`) acts as Admin whatever the stored role is, `none` included; the store applies the same +rule in its own queries (sessions, assignees, reminders, mail recipients) and the members page does not offer +their role for change (a forged change is refused too). A disabled account is denied everything (404 for pages, +the sign-in card for `/`), and so is a member with role `none` who is not an `im` administrator. Deleting a file: +uploader while still a Member, or Admin. Truth-table tested. ---