forge
Explore
Log in

Don't you dare go Hollow

✨ board: Manual sort by default with in-column reorder; admins restore recently deleted tasks; im admins' role is fixed

Browse files at this commit

1788d7f4a9aff5ff08093febae5bd86eb2e337a3Ahmet Kaan GümüşParent: eaa81cf
README.mdmodified+3 -1
@@ -3,7 +3,9 @@
3 iz is the family task board. It has columns, cards (with one level of subtasks, dependencies and3 iz is the family task board. It has columns, cards (with one level of subtasks, dependencies and
4 assignees), projects (tags), deadlines with meeting times and reminders, comments, attachments with4 assignees), projects (tags), deadlines with meeting times and reminders, comments, attachments with
5 in-page viewers (images, media, PDF, spreadsheets, slides), an activity trail, and admin-defined mail5 in-page viewers (images, media, PDF, spreadsheets, slides), an activity trail, and admin-defined mail
6-rules with a durable outbox. Sign-in goes through the family's `im` identity provider.6+rules with a durable outbox. Sign-in goes through the family's `im` identity provider. Cards keep a manual
7+order (the default sort), an administrator can restore tasks deleted in the last 30 days, and an `im`
8+administrator is an administrator in iz whatever role is stored here.
7 9
8 Design notes are in `docs/architecture.md`. The HTTP contracts with `im` and `in` are in10 Design notes are in `docs/architecture.md`. The HTTP contracts with `im` and `in` are in
9 `docs/contracts.md`, and the code conventions are in `docs/conventions.md`.11 `docs/contracts.md`, and the code conventions are in `docs/conventions.md`.
crates/iz-core/migrations/0007_activity_restore_kinds.sqladded+26 -0
@@ -0,0 +1,26 @@
1+-- 0007: the activity trail gains two kinds. 'task_reordered' is a card placed at a new spot in its column
2+-- under the Manual sort; 'task_restored' is a deleted task brought back by an administrator. SQLite cannot
3+-- alter a CHECK, so the table is rebuilt. Rows of 0001 carry over unchanged; the indexes are recreated.
4+CREATE TABLE activity_by_kind (
5+ id TEXT PRIMARY KEY,
6+ task_id TEXT REFERENCES tasks(id) ON DELETE CASCADE,
7+ actor TEXT REFERENCES members(sub) ON DELETE SET NULL,
8+ subject TEXT REFERENCES members(sub) ON DELETE SET NULL,
9+ kind TEXT NOT NULL CHECK (kind IN (
10+ 'task_created', 'task_edited', 'task_moved', 'task_deleted',
11+ 'assigned', 'unassigned', 'tag_changed', 'parent_changed',
12+ 'link_added', 'link_removed', 'unblocked',
13+ 'deadline_set', 'deadline_cleared', 'clock_set', 'clock_cleared',
14+ 'watch_changed', 'comment_added', 'comment_edited', 'comment_deleted',
15+ 'file_added', 'file_deleted', 'reminded', 'account_changed',
16+ 'task_reordered', 'task_restored'
17+ )),
18+ detail TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(detail)),
19+ at TEXT NOT NULL
20+);
21+INSERT INTO activity_by_kind (id, task_id, actor, subject, kind, detail, at)
22+ SELECT id, task_id, actor, subject, kind, detail, at FROM activity;
23+DROP TABLE activity;
24+ALTER TABLE activity_by_kind RENAME TO activity;
25+CREATE INDEX activity_by_task ON activity(task_id, at);
26+CREATE INDEX activity_recent ON activity(at);
crates/iz-core/src/authz.rsmodified+16 -12
@@ -3,10 +3,11 @@
3 //! A denial is `NotFound` when the viewer must not learn that the thing exists, and `Forbidden`3 //! A denial is `NotFound` when the viewer must not learn that the thing exists, and `Forbidden`
4 //! when the viewer may know it but may not act on it.4 //! when the viewer may know it but may not act on it.
5 //!5 //!
6-//! Levels: admin contains member, member contains viewer. `im_admin` acts as admin. A disabled6+//! Levels: admin contains member, member contains viewer. `im_admin` acts as admin, whatever the stored
7-//! account and role `none` are denied everything with `NotFound`. An anonymous actor is `Forbidden`,7+//! role says. A disabled account is denied everything with `NotFound`; so is a member with role `none`
8-//! so the caller can show the sign-in card. The store repeats the disabled and `none` checks in its8+//! who is not an `im` administrator. An anonymous actor is `Forbidden`, so the caller can show the sign-in
9-//! own queries (sessions, assignments), so a denied member cannot reach data through another path.9+//! card. The store repeats the disabled and `none` checks in its own queries (sessions, assignments, mail),
10+//! with the same `im_admin` exception, so a denied member cannot reach data through another path.
10 11
11 use crate::error::Error;12 use crate::error::Error;
12 13
@@ -128,19 +129,18 @@ enum Level {
128 pub fn authorize(actor: &Actor, action: &Action) -> Result<(), Denied> {129 pub fn authorize(actor: &Actor, action: &Action) -> Result<(), Denied> {
129 let (sub, level) = match actor {130 let (sub, level) = match actor {
130 Actor::Anonymous => return Err(Denied::Forbidden),131 Actor::Anonymous => return Err(Denied::Forbidden),
131- // A disabled member and a member with no role have no access, even when `im` makes them an admin.132+ // A disabled account has no access, even when `im` makes it an admin.
132- Actor::Member { disabled: true, .. }133+ Actor::Member { disabled: true, .. } => return Err(Denied::NotFound),
133- | Actor::Member {134+ // An `im` administrator is an admin whatever the stored role says, role `none` included.
134- role: Role::NoAccess,
135- ..
136- } => {
137- return Err(Denied::NotFound);
138- }
139 Actor::Member {135 Actor::Member {
140 sub,136 sub,
141 im_admin: true,137 im_admin: true,
142 ..138 ..
143 } => (sub.as_str(), Level::Admin),139 } => (sub.as_str(), Level::Admin),
140+ Actor::Member {
141+ role: Role::NoAccess,
142+ ..
143+ } => return Err(Denied::NotFound),
144 Actor::Member { sub, role, .. } => {144 Actor::Member { sub, role, .. } => {
145 let level = match role {145 let level = match role {
146 Role::Admin => Level::Admin,146 Role::Admin => Level::Admin,
@@ -222,6 +222,10 @@ mod tests {
222 [ok, ok, ok, Err(F), ok, ok, ok, ok],222 [ok, ok, ok, Err(F), ok, ok, ok, ok],
223 ),223 ),
224 (member("ada", Role::NoAccess, false, false), [Err(N); 8]),224 (member("ada", Role::NoAccess, false, false), [Err(N); 8]),
225+ (
226+ member("ada", Role::NoAccess, true, false),
227+ [ok, ok, ok, ok, ok, ok, ok, ok],
228+ ),
225 (member("ada", Role::Admin, false, true), [Err(N); 8]),229 (member("ada", Role::Admin, false, true), [Err(N); 8]),
226 ];230 ];
227 let actions = [231 let actions = [
crates/iz-core/src/store/members.rsmodified+19 -3
@@ -59,6 +59,17 @@ pub struct Member {
59 pub last_sign_in_at: Option<String>,59 pub last_sign_in_at: Option<String>,
60 }60 }
61 61
62+impl Member {
63+ /// The role iz acts on: an `im` administrator is always `admin`, whatever the stored role says.
64+ pub fn effective_role(&self) -> Role {
65+ if self.im_admin {
66+ Role::Admin
67+ } else {
68+ self.role
69+ }
70+ }
71+}
72+
62 /// What the directory (or a sign-in) says about one person. Validated before it is stored.73 /// What the directory (or a sign-in) says about one person. Validated before it is stored.
63 #[derive(Debug, Clone, PartialEq, Eq)]74 #[derive(Debug, Clone, PartialEq, Eq)]
64 pub struct DirectoryMember {75 pub struct DirectoryMember {
@@ -324,10 +335,18 @@ impl Store {
324 /// of the same conditional UPDATE, so two demotions cannot both pass.335 /// of the same conditional UPDATE, so two demotions cannot both pass.
325 ///336 ///
326 /// Moving to `viewer` or `none` also removes the member's assignments and pending reminders.337 /// Moving to `viewer` or `none` also removes the member's assignments and pending reminders.
338+ /// A member who is an `im` administrator keeps the admin role whatever is stored, so their role
339+ /// cannot be changed here (refused as a conflict; the page does not offer the change).
327 pub async fn set_role(&self, sub: &str, role: Role) -> Result<()> {340 pub async fn set_role(&self, sub: &str, role: Role) -> Result<()> {
328 let conn = self.inner.conn.lock().await;341 let conn = self.inner.conn.lock().await;
329 let tx = conn.unchecked_transaction().await.map_err(db_err)?;342 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
330 let outcome: Result<()> = async {343 let outcome: Result<()> = async {
344+ let member = select_member(&tx, sub).await?.ok_or(Error::NotFound)?;
345+ if member.im_admin {
346+ return Err(Error::Conflict(
347+ "the role of an im administrator is set in im".into(),
348+ ));
349+ }
331 let changed = tx350 let changed = tx
332 .execute(351 .execute(
333 "UPDATE members SET role = ?2 WHERE sub = ?1 AND (?2 = 'admin' OR EXISTS ( \352 "UPDATE members SET role = ?2 WHERE sub = ?1 AND (?2 = 'admin' OR EXISTS ( \
@@ -338,9 +357,6 @@ impl Store {
338 .await357 .await
339 .map_err(db_err)?;358 .map_err(db_err)?;
340 if changed == 0 {359 if changed == 0 {
341- if select_member(&tx, sub).await?.is_none() {
342- return Err(Error::NotFound);
343- }
344 return Err(Error::Conflict(360 return Err(Error::Conflict(
345 "the last administrator cannot be demoted".into(),361 "the last administrator cannot be demoted".into(),
346 ));362 ));
crates/iz-core/src/store/migrate.rsmodified+4 -0
@@ -24,6 +24,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
24 6,24 6,
25 include_str!("../../migrations/0006_decision_skipped.sql"),25 include_str!("../../migrations/0006_decision_skipped.sql"),
26 ),26 ),
27+ (
28+ 7,
29+ include_str!("../../migrations/0007_activity_restore_kinds.sql"),
30+ ),
27 ];31 ];
28 32
29 fn migration_err(e: turso::Error) -> Error {33 fn migration_err(e: turso::Error) -> Error {
crates/iz-core/src/store/mod.rsmodified+1 -1
@@ -404,7 +404,7 @@ mod tests {
404 })404 })
405 .await405 .await
406 .unwrap();406 .unwrap();
407- assert_eq!(versions, vec![1, 2, 3, 4, 5, 6]);407+ assert_eq!(versions, vec![1, 2, 3, 4, 5, 6, 7]);
408 }408 }
409 409
410 #[tokio::test]410 #[tokio::test]
crates/iz-core/src/store/outbox.rsmodified+4 -3
@@ -178,7 +178,8 @@ pub fn clamp_page(limit: usize) -> usize {
178 limit.clamp(1, PAGE_MAX)178 limit.clamp(1, PAGE_MAX)
179 }179 }
180 180
181-/// Decides whether a claimed recipient may still receive mail: enabled, role admin or member.181+/// Decides whether a claimed recipient may still receive mail: enabled, role admin or member. The role
182+/// read is the effective one (an `im` administrator is `admin`).
182 fn eligible_role(role: &str) -> bool {183 fn eligible_role(role: &str) -> bool {
183 matches!(role, "admin" | "member")184 matches!(role, "admin" | "member")
184 }185 }
@@ -196,7 +197,7 @@ impl Store {
196 let candidates = fetch_all(197 let candidates = fetch_all(
197 &tx,198 &tx,
198 &format!(199 &format!(
199- "SELECT {OUTBOX_COLS}, m.role FROM mail_outbox o JOIN members m ON m.sub = o.recipient \200+ "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 \
200 WHERE o.state IN ('pending', 'failed') AND o.next_attempt_at <= ?1 \201 WHERE o.state IN ('pending', 'failed') AND o.next_attempt_at <= ?1 \
201 AND (o.claimed_at IS NULL OR o.claimed_at <= ?2) \202 AND (o.claimed_at IS NULL OR o.claimed_at <= ?2) \
202 ORDER BY o.next_attempt_at, o.id LIMIT ?3"203 ORDER BY o.next_attempt_at, o.id LIMIT ?3"
@@ -387,7 +388,7 @@ impl Store {
387 }388 }
388 let recipients = fetch_all(389 let recipients = fetch_all(
389 &tx,390 &tx,
390- "SELECT sub FROM members WHERE disabled = 0 AND role IN ('admin', 'member') AND sub <> ?1 ORDER BY sub",391+ "SELECT sub FROM members WHERE disabled = 0 AND (im_admin = 1 OR role IN ('admin', 'member')) AND sub <> ?1 ORDER BY sub",
391 (actor.to_owned(),),392 (actor.to_owned(),),
392 |row| col_text(row, 0),393 |row| col_text(row, 0),
393 )394 )
crates/iz-core/src/store/reminders.rsmodified+2 -2
@@ -83,7 +83,7 @@ pub(super) async fn sync_reminders(tx: &Transaction<'_>, task_id: &str) -> Resul
83 "INSERT INTO reminders (task_id, sub, due_at, sent_at) \83 "INSERT INTO reminders (task_id, sub, due_at, sent_at) \
84 SELECT a.task_id, a.sub, ?2, NULL FROM task_assignees a \84 SELECT a.task_id, a.sub, ?2, NULL FROM task_assignees a \
85 WHERE a.task_id = ?1 AND EXISTS ( \85 WHERE a.task_id = ?1 AND EXISTS ( \
86- SELECT 1 FROM members m WHERE m.sub = a.sub AND m.disabled = 0 AND m.role IN ('admin', 'member')) \86+ 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'))) \
87 ON CONFLICT(task_id, sub) DO NOTHING",87 ON CONFLICT(task_id, sub) DO NOTHING",
88 (task_id.to_owned(), due),88 (task_id.to_owned(), due),
89 )89 )
@@ -112,7 +112,7 @@ impl Store {
112 "SELECT r.task_id, r.sub, t.key, t.title, t.meeting_at, m.zoneinfo, m.locale, m.locale_override \112 "SELECT r.task_id, r.sub, t.key, t.title, t.meeting_at, m.zoneinfo, m.locale, m.locale_override \
113 FROM reminders r JOIN tasks t ON t.id = r.task_id JOIN members m ON m.sub = r.sub \113 FROM reminders r JOIN tasks t ON t.id = r.task_id JOIN members m ON m.sub = r.sub \
114 WHERE r.sent_at IS NULL AND r.due_at <= ?1 AND t.deleted_at IS NULL \114 WHERE r.sent_at IS NULL AND r.due_at <= ?1 AND t.deleted_at IS NULL \
115- AND m.disabled = 0 AND m.role IN ('admin', 'member') \115+ AND m.disabled = 0 AND (m.im_admin = 1 OR m.role IN ('admin', 'member')) \
116 ORDER BY r.due_at, r.task_id, r.sub LIMIT ?2",116 ORDER BY r.due_at, r.task_id, r.sub LIMIT ?2",
117 (stamp.clone(), i64::try_from(batch).unwrap_or(i64::MAX)),117 (stamp.clone(), i64::try_from(batch).unwrap_or(i64::MAX)),
118 |row| {118 |row| {
crates/iz-core/src/store/rules_engine.rsmodified+1 -1
@@ -76,7 +76,7 @@ async fn eligible_members(tx: &Transaction<'_>) -> Result<Vec<Eligible>> {
76 fetch_all(76 fetch_all(
77 tx,77 tx,
78 "SELECT sub, locale, locale_override, zoneinfo FROM members \78 "SELECT sub, locale, locale_override, zoneinfo FROM members \
79- WHERE disabled = 0 AND role IN ('admin', 'member') ORDER BY sub",79+ WHERE disabled = 0 AND (im_admin = 1 OR role IN ('admin', 'member')) ORDER BY sub",
80 (),80 (),
81 |row| {81 |row| {
82 let locale = col_opt_text(row, 1)?;82 let locale = col_opt_text(row, 1)?;
crates/iz-core/src/store/sessions.rsmodified+4 -3
@@ -81,7 +81,7 @@ impl Store {
81 "INSERT INTO sessions (id, sub, token_hash, csrf_token, sid, created_at, expires_at, \81 "INSERT INTO sessions (id, sub, token_hash, csrf_token, sid, created_at, expires_at, \
82 last_seen, user_agent, ip, id_token_sealed) \82 last_seen, user_agent, ip, id_token_sealed) \
83 SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?6, ?8, ?9, ?10 FROM members \83 SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?6, ?8, ?9, ?10 FROM members \
84- WHERE sub = ?2 AND disabled = 0 AND role <> 'none'",84+ WHERE sub = ?2 AND disabled = 0 AND (im_admin = 1 OR role <> 'none')",
85 (85 (
86 id.clone(),86 id.clone(),
87 sub.to_owned(),87 sub.to_owned(),
@@ -107,7 +107,8 @@ impl Store {
107 })107 })
108 }108 }
109 109
110- /// The live session for a cookie token: unexpired, member enabled, role not `none`. `None` otherwise,110+ /// The live session for a cookie token: unexpired, member enabled, role not `none` (an `im` administrator
111+ /// always passes). `None` otherwise,
111 /// with no hint about which check failed.112 /// with no hint about which check failed.
112 pub async fn session_by_token(&self, token: &str) -> Result<Option<SessionRecord>> {113 pub async fn session_by_token(&self, token: &str) -> Result<Option<SessionRecord>> {
113 let conn = self.read_conn().await;114 let conn = self.read_conn().await;
@@ -115,7 +116,7 @@ impl Store {
115 &conn,116 &conn,
116 &format!(117 &format!(
117 "SELECT {SESSION_COLS} FROM sessions s JOIN members m ON m.sub = s.sub \118 "SELECT {SESSION_COLS} FROM sessions s JOIN members m ON m.sub = s.sub \
118- WHERE s.token_hash = ?1 AND s.expires_at > ?2 AND m.disabled = 0 AND m.role <> 'none'"119+ WHERE s.token_hash = ?1 AND s.expires_at > ?2 AND m.disabled = 0 AND (m.im_admin = 1 OR m.role <> 'none')"
119 ),120 ),
120 (hash_token(token), now_stamp()),121 (hash_token(token), now_stamp()),
121 map_session,122 map_session,
crates/iz-core/src/store/tasks.rsmodified+338 -9
@@ -7,6 +7,7 @@
7 //! transaction whenever the meeting time, the assignees, the done state or the deletion changes.7 //! transaction whenever the meeting time, the assignees, the done state or the deletion changes.
8 8
9 use std::collections::{HashMap, HashSet};9 use std::collections::{HashMap, HashSet};
10+use std::time::Duration;
10 11
11 use jiff::Timestamp;12 use jiff::Timestamp;
12 use jiff::civil::Date;13 use jiff::civil::Date;
@@ -26,7 +27,7 @@ use crate::clock::timestamp_of;
26 use crate::error::{Error, Result};27 use crate::error::{Error, Result};
27 use crate::limits::{DESCRIPTION_MAX, TITLE_MAX};28 use crate::limits::{DESCRIPTION_MAX, TITLE_MAX};
28 use crate::store::Store;29 use crate::store::Store;
29-use crate::time::now_stamp;30+use crate::time::{now_stamp, stamp_before};
30 31
31 /// A task row as read back. Deadline and meeting are typed; the rest is text or numbers.32 /// A task row as read back. Deadline and meeting are typed; the rest is text or numbers.
32 #[derive(Debug, Clone, PartialEq)]33 #[derive(Debug, Clone, PartialEq)]
@@ -126,7 +127,9 @@ pub struct TaskEdit {
126 pub enum MoveOutcome {127 pub enum MoveOutcome {
127 /// The task is now in the target column.128 /// The task is now in the target column.
128 Moved,129 Moved,
129- /// The task was already in the target column.130+ /// The task stayed in its column and took a new place in it (Manual sort only).
131+ Reordered,
132+ /// The task was already in the target column and no place was asked for.
130 Unchanged,133 Unchanged,
131 /// The task is no longer in the column the client last saw; someone else moved it.134 /// The task is no longer in the column the client last saw; someone else moved it.
132 Stale,135 Stale,
@@ -134,11 +137,45 @@ pub enum MoveOutcome {
134 SubtasksOpen,137 SubtasksOpen,
135 }138 }
136 139
140+/// Days a deleted task can be restored. Reason: there is no purge, so the recently deleted list covers the
141+/// last 30 days and older deletions are final.
142+pub const RESTORE_DAYS: u64 = 30;
143+
144+/// A deleted task as the recently deleted list shows it.
145+#[derive(Debug, Clone, PartialEq, Eq)]
146+pub struct DeletedTask {
147+ /// Task id (ULID).
148+ pub id: String,
149+ /// Readable key `PREFIX-n`.
150+ pub key: String,
151+ /// Title.
152+ pub title: String,
153+ /// The parent task, for a subtask.
154+ pub parent_id: Option<String>,
155+ /// When it was deleted (UTC stamp).
156+ pub deleted_at: String,
157+ /// The name of who deleted it, when the activity trail recorded it.
158+ pub deleted_by: Option<String>,
159+}
160+
161+/// The result of a restore that was not refused as missing.
162+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163+pub enum RestoreOutcome {
164+ /// The task and the subtasks deleted with it are live again.
165+ Restored,
166+ /// The parent task is still deleted. Restore the parent first.
167+ ParentDeleted,
168+ /// Deleted more than [`RESTORE_DAYS`] ago.
169+ Expired,
170+}
171+
137 /// Sorting of the board's cards.172 /// Sorting of the board's cards.
138 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]173 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
139 pub enum SortBy {174 pub enum SortBy {
140- /// Earliest deadline first; tasks without a deadline last.175+ /// The order the cards were placed in (`position`). The default. Only here can a card be reordered.
141 #[default]176 #[default]
177+ Manual,
178+ /// Earliest deadline first; tasks without a deadline last.
142 Deadline,179 Deadline,
143 /// Newest first.180 /// Newest first.
144 Created,181 Created,
@@ -331,7 +368,7 @@ async fn task_row(conn: &Connection, board_id: &str, task_id: &str) -> Result<Op
331 async fn assignable(conn: &Connection, sub: &str) -> Result<bool> {368 async fn assignable(conn: &Connection, sub: &str) -> Result<bool> {
332 let found = fetch_opt(369 let found = fetch_opt(
333 conn,370 conn,
334- "SELECT 1 FROM members WHERE sub = ?1 AND disabled = 0 AND role IN ('admin', 'member')",371+ "SELECT 1 FROM members WHERE sub = ?1 AND disabled = 0 AND (im_admin = 1 OR role IN ('admin', 'member'))",
335 (sub.to_owned(),),372 (sub.to_owned(),),
336 |row| col_int(row, 0),373 |row| col_int(row, 0),
337 )374 )
@@ -378,15 +415,19 @@ async fn next_position(conn: &Connection, column_id: &str) -> Result<f64> {
378 Ok(position_between(last, None))415 Ok(position_between(last, None))
379 }416 }
380 417
418+/// The smallest gap between two neighbours that a midpoint can still split. Below it the next card placed
419+/// between them would get the same float, so the column is renumbered first.
420+const MIN_GAP: f64 = 1e-9;
421+
381 /// Position for a task placed at `index` among the top-level cards of a column, between its neighbours422 /// Position for a task placed at `index` among the top-level cards of a column, between its neighbours
382 /// there. The moving task itself is left out, so a card never sits between itself and a neighbour. An423 /// there. The moving task itself is left out, so a card never sits between itself and a neighbour. An
383-/// index past the end places the task last.424+/// index past the end places the task last. `None` when the neighbours are too close to split.
384 async fn position_at(425 async fn position_at(
385 conn: &Connection,426 conn: &Connection,
386 column_id: &str,427 column_id: &str,
387 moving_id: &str,428 moving_id: &str,
388 index: usize,429 index: usize,
389-) -> Result<f64> {430+) -> Result<Option<f64>> {
390 let positions = fetch_all(431 let positions = fetch_all(
391 conn,432 conn,
392 "SELECT position FROM tasks WHERE column_id = ?1 AND id <> ?2 AND parent_id IS NULL \433 "SELECT position FROM tasks WHERE column_id = ?1 AND id <> ?2 AND parent_id IS NULL \
@@ -398,7 +439,51 @@ async fn position_at(
398 let index = index.min(positions.len());439 let index = index.min(positions.len());
399 let before = index.checked_sub(1).map(|i| positions[i]);440 let before = index.checked_sub(1).map(|i| positions[i]);
400 let after = positions.get(index).copied();441 let after = positions.get(index).copied();
401- Ok(position_between(before, after))442+ let too_close = matches!((before, after), (Some(b), Some(a)) if a - b < MIN_GAP);
443+ Ok((!too_close).then(|| position_between(before, after)))
444+}
445+
446+/// Renumbers the top-level live cards of a column to 1, 2, 3, ... in their current order, with the moving
447+/// task put at `index`. Returns the moving task's new position. Subtask positions are not touched.
448+async fn renumber_column(
449+ conn: &Connection,
450+ column_id: &str,
451+ moving_id: &str,
452+ index: usize,
453+) -> Result<f64> {
454+ let mut order = fetch_all(
455+ conn,
456+ "SELECT id FROM tasks WHERE column_id = ?1 AND id <> ?2 AND parent_id IS NULL \
457+ AND deleted_at IS NULL ORDER BY position, id",
458+ (column_id.to_owned(), moving_id.to_owned()),
459+ |row| col_text(row, 0),
460+ )
461+ .await?;
462+ let index = index.min(order.len());
463+ order.insert(index, moving_id.to_owned());
464+ for (number, id) in order.iter().enumerate() {
465+ conn.execute(
466+ "UPDATE tasks SET position = ?2 WHERE id = ?1",
467+ (id.clone(), (number + 1) as f64),
468+ )
469+ .await
470+ .map_err(db_err)?;
471+ }
472+ Ok((index + 1) as f64)
473+}
474+
475+/// The position of a task placed at `index` in a column: between its neighbours, or after a renumber when
476+/// they are too close to split.
477+async fn place_at(
478+ conn: &Connection,
479+ column_id: &str,
480+ moving_id: &str,
481+ index: usize,
482+) -> Result<f64> {
483+ match position_at(conn, column_id, moving_id, index).await? {
484+ Some(position) => Ok(position),
485+ None => renumber_column(conn, column_id, moving_id, index).await,
486+ }
402 }487 }
403 488
404 /// Appends a row to the transitions table. `from` is `None` for the first placement.489 /// Appends a row to the transitions table. `from` is `None` for the first placement.
@@ -703,7 +788,8 @@ impl Store {
703 /// one transition and one `task_moved` activity row.788 /// one transition and one `task_moved` activity row.
704 ///789 ///
705 /// `index` is the place among the column's top-level cards (0 is the top); `None` appends. A move790 /// `index` is the place among the column's top-level cards (0 is the top); `None` appends. A move
706- /// inside the same column is `Unchanged`: reordering within a column is not a move.791+ /// inside the same column is not a move: with a place it is a `Reordered` (one activity row, no
792+ /// transition); without one it is `Unchanged`. The caller asks for a place only under the Manual sort.
707 pub async fn move_task(793 pub async fn move_task(
708 &self,794 &self,
709 board_id: &str,795 board_id: &str,
@@ -725,7 +811,32 @@ impl Store {
725 return Ok(MoveOutcome::Stale);811 return Ok(MoveOutcome::Stale);
726 }812 }
727 if task.column_id == target.id {813 if task.column_id == target.id {
814+ let Some(index) = index else {
728 return Ok(MoveOutcome::Unchanged);815 return Ok(MoveOutcome::Unchanged);
816+ };
817+ let position = place_at(&tx, &target.id, task_id, index).await?;
818+ tx.execute(
819+ "UPDATE tasks SET position = ?3, updated_at = ?4 \
820+ WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL",
821+ (
822+ task_id.to_owned(),
823+ board_id.to_owned(),
824+ position,
825+ now_stamp(),
826+ ),
827+ )
828+ .await
829+ .map_err(db_err)?;
830+ log(
831+ &tx,
832+ task_id,
833+ actor,
834+ "task_reordered",
835+ None,
836+ serde_json::json!({ "column": target.id, "index": index }),
837+ )
838+ .await?;
839+ return Ok(MoveOutcome::Reordered);
729 }840 }
730 if target.is_done {841 if target.is_done {
731 let open = fetch_opt(842 let open = fetch_opt(
@@ -741,7 +852,7 @@ impl Store {
741 }852 }
742 }853 }
743 let position = match index {854 let position = match index {
744- Some(index) => position_at(&tx, &target.id, task_id, index).await?,855+ Some(index) => place_at(&tx, &target.id, task_id, index).await?,
745 None => next_position(&tx, &target.id).await?,856 None => next_position(&tx, &target.id).await?,
746 };857 };
747 let now = now_stamp();858 let now = now_stamp();
@@ -869,6 +980,152 @@ impl Store {
869 finish(tx, outcome).await980 finish(tx, outcome).await
870 }981 }
871 982
983+ /// The tasks deleted within [`RESTORE_DAYS`], newest deletion first. `deleted_by` is the name of the
984+ /// member on the task's last `task_deleted` activity row, when there is one.
985+ pub async fn deleted_tasks(&self, board_id: &str) -> Result<Vec<DeletedTask>> {
986+ let cutoff = stamp_before(Duration::from_secs(RESTORE_DAYS * 24 * 60 * 60));
987+ let conn = self.read_conn().await;
988+ let rows = fetch_all(
989+ &conn,
990+ "SELECT id, key, title, parent_id, deleted_at FROM tasks \
991+ WHERE board_id = ?1 AND deleted_at IS NOT NULL AND deleted_at >= ?2 \
992+ ORDER BY deleted_at DESC, key",
993+ (board_id.to_owned(), cutoff),
994+ |row| {
995+ Ok((
996+ col_text(row, 0)?,
997+ col_text(row, 1)?,
998+ col_text(row, 2)?,
999+ col_opt_text(row, 3)?,
1000+ col_text(row, 4)?,
1001+ ))
1002+ },
1003+ )
1004+ .await?;
1005+ let mut deleted = Vec::with_capacity(rows.len());
1006+ for (id, key, title, parent_id, deleted_at) in rows {
1007+ let deleted_by = fetch_opt(
1008+ &conn,
1009+ "SELECT m.name FROM activity a JOIN members m ON m.sub = a.actor \
1010+ WHERE a.task_id = ?1 AND a.kind = 'task_deleted' ORDER BY a.at DESC LIMIT 1",
1011+ (id.clone(),),
1012+ |row| col_text(row, 0),
1013+ )
1014+ .await?;
1015+ deleted.push(DeletedTask {
1016+ id,
1017+ key,
1018+ title,
1019+ parent_id,
1020+ deleted_at,
1021+ deleted_by,
1022+ });
1023+ }
1024+ Ok(deleted)
1025+ }
1026+
1027+ /// Brings a deleted task back in one transaction. The subtasks deleted with it (the same deletion
1028+ /// stamp) come back too. A task whose column was retired goes to the board's first column that is not
1029+ /// done, and loses `done_at` there. A task whose parent is still deleted is refused (`ParentDeleted`),
1030+ /// and so is one deleted more than [`RESTORE_DAYS`] ago (`Expired`). Reminders are rebuilt. Links cleared
1031+ /// by the deletion are not restored, and the files of a deleted task were removed with it.
1032+ pub async fn restore_task(
1033+ &self,
1034+ board_id: &str,
1035+ task_id: &str,
1036+ actor: &str,
1037+ ) -> Result<RestoreOutcome> {
1038+ let conn = self.inner.conn.lock().await;
1039+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
1040+ let outcome: Result<RestoreOutcome> = async {
1041+ let task = fetch_opt(
1042+ &tx,
1043+ &format!(
1044+ "SELECT {TASK_COLS} FROM tasks WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NOT NULL"
1045+ ),
1046+ (task_id.to_owned(), board_id.to_owned()),
1047+ map_task,
1048+ )
1049+ .await?
1050+ .ok_or(Error::NotFound)?;
1051+ let Some(deleted_at) = task.deleted_at.clone() else {
1052+ return Err(Error::NotFound);
1053+ };
1054+ if deleted_at < stamp_before(Duration::from_secs(RESTORE_DAYS * 24 * 60 * 60)) {
1055+ return Ok(RestoreOutcome::Expired);
1056+ }
1057+ if let Some(parent) = &task.parent_id {
1058+ let parent_deleted = fetch_opt(
1059+ &tx,
1060+ "SELECT 1 FROM tasks WHERE id = ?1 AND deleted_at IS NOT NULL",
1061+ (parent.clone(),),
1062+ |row| col_int(row, 0),
1063+ )
1064+ .await?;
1065+ if parent_deleted.is_some() {
1066+ return Ok(RestoreOutcome::ParentDeleted);
1067+ }
1068+ }
1069+ let mut rows = vec![task];
1070+ rows.extend(
1071+ fetch_all(
1072+ &tx,
1073+ &format!(
1074+ "SELECT {TASK_COLS} FROM tasks WHERE parent_id = ?1 AND board_id = ?2 \
1075+ AND deleted_at = ?3 ORDER BY position, id"
1076+ ),
1077+ (task_id.to_owned(), board_id.to_owned(), deleted_at),
1078+ map_task,
1079+ )
1080+ .await?,
1081+ );
1082+ let now = now_stamp();
1083+ let live = live_columns(&tx, board_id).await?;
1084+ for row in rows {
1085+ let column = column_in(&tx, board_id, &row.column_id)
1086+ .await?
1087+ .filter(|c| c.deleted_at.is_none());
1088+ let (column_id, is_done) = match column {
1089+ Some(column) => (column.id, column.is_done),
1090+ None => {
1091+ let first = live
1092+ .iter()
1093+ .find(|c| !c.is_done)
1094+ .ok_or_else(|| Error::Invalid("the board has no open column".into()))?;
1095+ (first.id.clone(), false)
1096+ }
1097+ };
1098+ let done_at = is_done.then(|| row.done_at.clone().unwrap_or_else(|| now.clone()));
1099+ tx.execute(
1100+ "UPDATE tasks SET deleted_at = NULL, column_id = ?3, done_at = ?4, updated_at = ?5 \
1101+ WHERE id = ?1 AND board_id = ?2",
1102+ (
1103+ row.id.clone(),
1104+ board_id.to_owned(),
1105+ column_id.clone(),
1106+ done_at,
1107+ now.clone(),
1108+ ),
1109+ )
1110+ .await
1111+ .map_err(db_err)?;
1112+ log(
1113+ &tx,
1114+ &row.id,
1115+ actor,
1116+ "task_restored",
1117+ None,
1118+ serde_json::json!({ "column": column_id }),
1119+ )
1120+ .await?;
1121+ sync_reminders(&tx, &row.id).await?;
1122+ }
1123+ Ok(RestoreOutcome::Restored)
1124+ }
1125+ .await;
1126+ finish(tx, outcome).await
1127+ }
1128+
872 /// Assigns members to a task, all or nothing: if any of them cannot be assigned, nothing changes.1129 /// Assigns members to a task, all or nothing: if any of them cannot be assigned, nothing changes.
873 pub async fn assign(1130 pub async fn assign(
874 &self,1131 &self,
@@ -1358,6 +1615,12 @@ impl Store {
1358 });1615 });
1359 }1616 }
1360 match filter.sort {1617 match filter.sort {
1618+ SortBy::Manual => cards.sort_by(|a, b| {
1619+ a.task
1620+ .position
1621+ .total_cmp(&b.task.position)
1622+ .then(a.task.id.cmp(&b.task.id))
1623+ }),
1361 SortBy::Deadline => cards.sort_by(|a, b| {1624 SortBy::Deadline => cards.sort_by(|a, b| {
1362 a.task1625 a.task
1363 .deadline1626 .deadline
@@ -1673,6 +1936,72 @@ mod tests {
1673 assert_eq!(after.blocked, 0);1936 assert_eq!(after.blocked, 0);
1674 }1937 }
1675 1938
1939+ /// A card moved to place 0 of its column is first under the Manual order (the default), and a move with no
1940+ /// place inside the column changes nothing.
1941+ #[tokio::test]
1942+ async fn manual_reorder_persists_the_place() {
1943+ let (_dir, store, board) = seeded().await;
1944+ let tag = default_tag(&store, &board).await;
1945+ let backlog = store.columns(&board).await.unwrap()[0].id.clone();
1946+ store
1947+ .create_task(&board, new_task("First", &backlog, &tag), "ada")
1948+ .await
1949+ .unwrap();
1950+ let second = store
1951+ .create_task(&board, new_task("Second", &backlog, &tag), "ada")
1952+ .await
1953+ .unwrap();
1954+ let outcome = store
1955+ .move_task(&board, &second.id, &backlog, &backlog, Some(0), "ada")
1956+ .await
1957+ .unwrap();
1958+ assert_eq!(outcome, MoveOutcome::Reordered);
1959+ let view = store
1960+ .board_view(&board, &BoardFilter::default(), &TimeZone::UTC)
1961+ .await
1962+ .unwrap();
1963+ let titles: Vec<&str> = view.columns[0]
1964+ .cards
1965+ .iter()
1966+ .map(|c| c.task.title.as_str())
1967+ .collect();
1968+ assert_eq!(titles, ["Second", "First"]);
1969+ let unchanged = store
1970+ .move_task(&board, &second.id, &backlog, &backlog, None, "ada")
1971+ .await
1972+ .unwrap();
1973+ assert_eq!(unchanged, MoveOutcome::Unchanged);
1974+ }
1975+
1976+ /// Restoring a parent brings back the subtask deleted with it. The subtask alone is refused while the
1977+ /// parent is still deleted.
1978+ #[tokio::test]
1979+ async fn restore_brings_back_the_subtasks_deleted_with_the_parent() {
1980+ let (_dir, store, board) = seeded().await;
1981+ let tag = default_tag(&store, &board).await;
1982+ let backlog = store.columns(&board).await.unwrap()[0].id.clone();
1983+ let parent = store
1984+ .create_task(&board, new_task("Parent", &backlog, &tag), "ada")
1985+ .await
1986+ .unwrap();
1987+ let mut child = new_task("Child", &backlog, &tag);
1988+ child.parent_id = Some(parent.id.clone());
1989+ let child = store.create_task(&board, child, "ada").await.unwrap();
1990+ store.delete_task(&board, &parent.id, "ada").await.unwrap();
1991+ assert_eq!(live_count(&store, &board).await, 0);
1992+ assert_eq!(
1993+ store.restore_task(&board, &child.id, "ada").await.unwrap(),
1994+ RestoreOutcome::ParentDeleted
1995+ );
1996+ assert_eq!(
1997+ store.restore_task(&board, &parent.id, "ada").await.unwrap(),
1998+ RestoreOutcome::Restored
1999+ );
2000+ // `live_count` sees top-level cards only; an empty deleted list shows the subtask is back too.
2001+ assert_eq!(live_count(&store, &board).await, 1);
2002+ assert!(store.deleted_tasks(&board).await.unwrap().is_empty());
2003+ }
2004+
1676 #[tokio::test]2005 #[tokio::test]
1677 async fn search_folds_turkish_dotted_and_dotless_i() {2006 async fn search_folds_turkish_dotted_and_dotless_i() {
1678 let (_dir, store, board) = seeded().await;2007 let (_dir, store, board) = seeded().await;
crates/iz-core/src/time.rsmodified+7 -0
@@ -44,6 +44,13 @@ pub fn stamp_after(after: Duration) -> String {
44 format_stamp(OffsetDateTime::now_utc().saturating_add(delta))44 format_stamp(OffsetDateTime::now_utc().saturating_add(delta))
45 }45 }
46 46
47+/// The stamp of the time `before` ago. Text order is time order, so `deleted_at >= stamp_before(d)` is
48+/// "deleted within the last `d`".
49+pub fn stamp_before(before: Duration) -> String {
50+ let delta = SignedDuration::try_from(before).unwrap_or(SignedDuration::MAX);
51+ format_stamp(OffsetDateTime::now_utc().saturating_sub(delta))
52+}
53+
47 #[cfg(test)]54 #[cfg(test)]
48 mod tests {55 mod tests {
49 use super::*;56 use super::*;
crates/iz-web/assets/board.jsmodified+32 -10
@@ -8,11 +8,15 @@
8 * column the page last showed (`from`), the target column (`to`) and the place (`position`), and8 * column the page last showed (`from`), the target column (`to`) and the place (`position`), and
9 * asks for JSON. The server's answer decides: {ok: true} keeps the card where it was dropped;9 * asks for JSON. The server's answer decides: {ok: true} keeps the card where it was dropped;
10 * anything else puts it back and shows a toast with the server's translated message.10 * anything else puts it back and shows a toast with the server's translated message.
11+ * - Under the Manual sort (data-sort on the section) a card can also be dropped at a new place in its own
12+ * column. That sends the same POST with `from` equal to `to` and the new place. Under any other sort a
13+ * drop in the same column changes nothing, and a card dropped in another column goes to its end (no
14+ * place is sent).
11 * - A drag that ends outside any column puts the card back where it was.15 * - A drag that ends outside any column puts the card back where it was.
12 *16 *
13 * 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, the17 * 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
14- * subtasks, the role and the token; this script only shows the result. Dropping onto the card's own18+ * subtasks, the role and the token, and it ignores a place unless the sort is manual; this script only
15- * column is nothing to send, so it puts the card back.19+ * shows the result. Dropping onto the card's own spot is nothing to send, so it puts the card back.
16 *20 *
17 * The CSRF token comes from data-csrf on the section, which the server renders for this session. The21 * The CSRF token comes from data-csrf on the section, which the server renders for this session. The
18 * file is one IIFE with no globals, and it is loaded with `defer`.22 * file is one IIFE with no globals, and it is loaded with `defer`.
@@ -47,6 +51,9 @@
47 /** The text shown when the request never got an answer. Rendered in the page's language. */51 /** The text shown when the request never got an answer. Rendered in the page's language. */
48 const failedText = board.dataset.msgFailed || "The card could not be moved. Try again.";52 const failedText = board.dataset.msgFailed || "The card could not be moved. Try again.";
49 53
54+ /** Whether the board shows the Manual order, the only order in which a place in a column is kept. */
55+ const manual = board.dataset.sort === "manual";
56+
50 /** The card being dragged, its place before the drag, and the column it started in. */57 /** The card being dragged, its place before the drag, and the column it started in. */
51 let dragged = null;58 let dragged = null;
52 let origin = null;59 let origin = null;
@@ -99,10 +106,17 @@
99 setTimeout(() => el.remove(), TOAST_MS);106 setTimeout(() => el.remove(), TOAST_MS);
100 }107 }
101 108
102- /** Sends the move and applies the answer. A card the server refused goes back to its place. */109+ /** Sends the move and applies the answer. A card the server refused goes back to its place. `index` is
110+ * null when no place is sent (any sort but Manual, or a drop that is not a reorder). */
103 async function send(card, start, from, to, index) {111 async function send(card, start, from, to, index) {
104 const id = card.dataset.taskId;112 const id = card.dataset.taskId;
105- const body = new URLSearchParams({ csrf, from, to, position: String(index) });113+ const body = new URLSearchParams({
114+ csrf,
115+ from,
116+ to,
117+ sort: board.dataset.sort || "",
118+ position: index === null ? "" : String(index),
119+ });
106 let answer = null;120 let answer = null;
107 let data = null;121 let data = null;
108 try {122 try {
@@ -130,27 +144,35 @@
130 const card = event.target.closest(".card[data-task-id]");144 const card = event.target.closest(".card[data-task-id]");
131 if (!card) return;145 if (!card) return;
132 dragged = card;146 dragged = card;
133- origin = { parent: card.parentNode, next: card.nextSibling };147+ origin = { parent: card.parentNode, next: card.nextSibling, index: indexIn(card.parentNode, card) };
134 card.classList.add("is-dragging");148 card.classList.add("is-dragging");
135 event.dataTransfer.effectAllowed = "move";149 event.dataTransfer.effectAllowed = "move";
136 event.dataTransfer.setData("text/plain", card.dataset.taskId || "");150 event.dataTransfer.setData("text/plain", card.dataset.taskId || "");
137 }151 }
138 152
139- /** Moves the card in the page while the pointer is over another column. */153+ /** Moves the card in the page while the pointer is over a column. Within its own column only the Manual
154+ * order places it by the pointer; any other order keeps it where it was. In another column it goes to the
155+ * place the pointer shows under Manual, and to the end otherwise (the server does the same). */
140 function onDragOver(event) {156 function onDragOver(event) {
141 if (!dragged) return;157 if (!dragged) return;
142 const list = event.currentTarget;158 const list = event.currentTarget;
143- if (columnOf(list) === columnOf(origin.parent)) {159+ const same = columnOf(list) === columnOf(origin.parent);
160+ if (same && !manual) {
144 restore(dragged, origin);161 restore(dragged, origin);
145 return;162 return;
146 }163 }
147 event.preventDefault();164 event.preventDefault();
148 event.dataTransfer.dropEffect = "move";165 event.dataTransfer.dropEffect = "move";
166+ if (manual) {
149 placeAt(list, dragged, event.clientY);167 placeAt(list, dragged, event.clientY);
168+ } else {
169+ list.appendChild(dragged);
170+ }
150 dragged.dataset.columnId = columnOf(list);171 dragged.dataset.columnId = columnOf(list);
151 }172 }
152 173
153- /** A drop in another column sends the move. A drop in the same column changes nothing. */174+ /** A drop in another column sends the move. A drop in the same column sends a reorder under Manual, when
175+ * the place changed; otherwise it changes nothing. */
154 function onDrop(event) {176 function onDrop(event) {
155 if (!dragged) return;177 if (!dragged) return;
156 const list = event.currentTarget;178 const list = event.currentTarget;
@@ -163,11 +185,11 @@
163 dragged = null;185 dragged = null;
164 origin = null;186 origin = null;
165 card.classList.remove("is-dragging");187 card.classList.remove("is-dragging");
166- if (from === to) {188+ if (from === to && (!manual || index === start.index)) {
167 restore(card, start);189 restore(card, start);
168 return;190 return;
169 }191 }
170- send(card, start, from, to, index);192+ send(card, start, from, to, manual ? index : null);
171 }193 }
172 194
173 /** A drag that ends without a drop (Escape, a drop outside) puts the card back. */195 /** A drag that ends without a drop (Escape, a drop outside) puts the card back. */
crates/iz-web/src/i18n/admin.rsmodified+54 -0
@@ -141,8 +141,24 @@ pub enum K {
141 ReasonColumn,141 ReasonColumn,
142 ReasonProject,142 ReasonProject,
143 FilterKind,143 FilterKind,
144+ // Recently deleted (settings card)
145+ DeletedHeading,
146+ DeletedHelp,
147+ DeletedEmpty,
148+ DeletedTaskHeader,
149+ DeletedAtHeader,
150+ DeletedByHeader,
151+ DeletedUnknown,
152+ RestoreButton,
153+ NoticeTaskRestored,
154+ // Members whose role im sets
155+ ImRoleLocked,
144 // Errors156 // Errors
145 ErrBackupOff,157 ErrBackupOff,
158+ ErrParentDeleted,
159+ ErrRestoreExpired,
160+ ErrRestoreFailed,
161+ ErrRestoreMissing,
146 }162 }
147 163
148 /// The text of `key` in `lang`. Placeholders are `{}` and are filled by [`fill`].164 /// 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 {
291 (K::ErrBackupOff, Tr) => {307 (K::ErrBackupOff, Tr) => {
292 "Yedekleme kapalı, başlatılacak bir şey yok. Önce [backup] dir ayarlayın."308 "Yedekleme kapalı, başlatılacak bir şey yok. Önce [backup] dir ayarlayın."
293 }309 }
310+ (K::DeletedHeading, En) => "Recently deleted",
311+ (K::DeletedHeading, Tr) => "Son silinenler",
312+ (K::DeletedHelp, En) => {
313+ "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."
314+ }
315+ (K::DeletedHelp, Tr) => {
316+ "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."
317+ }
318+ (K::DeletedEmpty, En) => "Nothing was deleted in the last 30 days.",
319+ (K::DeletedEmpty, Tr) => "Son 30 günde silinen görev yok.",
320+ (K::DeletedTaskHeader, En) => "Task",
321+ (K::DeletedTaskHeader, Tr) => "Görev",
322+ (K::DeletedAtHeader, En) => "Deleted",
323+ (K::DeletedAtHeader, Tr) => "Silinme",
324+ (K::DeletedByHeader, En) => "By",
325+ (K::DeletedByHeader, Tr) => "Silen",
326+ (K::DeletedUnknown, En) => "not recorded",
327+ (K::DeletedUnknown, Tr) => "kaydedilmemiş",
328+ (K::RestoreButton, En) => "Restore",
329+ (K::RestoreButton, Tr) => "Geri yükle",
330+ (K::NoticeTaskRestored, En) => "The task was restored.",
331+ (K::NoticeTaskRestored, Tr) => "Görev geri yüklendi.",
332+ (K::ImRoleLocked, En) => {
333+ "This person is an administrator in im, so the role stays admin here and cannot be changed."
334+ }
335+ (K::ImRoleLocked, Tr) => {
336+ "Bu kişi im'de yönetici. Buradaki rolü admin olarak kalır ve değiştirilemez."
337+ }
338+ (K::ErrParentDeleted, En) => "The parent task is still deleted. Restore the parent first.",
339+ (K::ErrParentDeleted, Tr) => "Üst görev hâlâ silinmiş. Önce üst görevi geri yükleyin.",
340+ (K::ErrRestoreExpired, En) => {
341+ "This task was deleted more than 30 days ago, so it cannot be restored."
342+ }
343+ (K::ErrRestoreExpired, Tr) => "Bu görev 30 günden önce silindi, geri yüklenemez.",
344+ (K::ErrRestoreFailed, En) => "The task could not be restored.",
345+ (K::ErrRestoreFailed, Tr) => "Görev geri yüklenemedi.",
346+ (K::ErrRestoreMissing, En) => "That task is not in the recently deleted list.",
347+ (K::ErrRestoreMissing, Tr) => "Bu görev son silinenler listesinde yok.",
294 (K::RulesTitle, En) => "Mail rules",348 (K::RulesTitle, En) => "Mail rules",
295 (K::RulesTitle, Tr) => "Mail kuralları",349 (K::RulesTitle, Tr) => "Mail kuralları",
296 (K::RulesHelp, En) => "A rule mails people when something happens on the board.",350 (K::RulesHelp, En) => "A rule mails people when something happens on the board.",
crates/iz-web/src/i18n/board.rsmodified+13 -1
@@ -41,12 +41,16 @@ pub enum K {
41 FilterNobody,41 FilterNobody,
42 /// The label of the sort order.42 /// The label of the sort order.
43 FilterSort,43 FilterSort,
44- /// The sort order by deadline (the default).44+ /// The sort order the cards were placed in (the default). The only order where a card can be reordered.
45+ SortManual,
46+ /// The sort order by deadline.
45 SortDeadline,47 SortDeadline,
46 /// The sort order newest first.48 /// The sort order newest first.
47 SortCreated,49 SortCreated,
48 /// The sort order by title.50 /// The sort order by title.
49 SortTitle,51 SortTitle,
52+ /// The hint under the board when the sort is not Manual: a drag can only move a card to another column.
53+ SortManualHint,
50 /// The label of the search box.54 /// The label of the search box.
51 FilterSearch,55 FilterSearch,
52 /// The placeholder of the search box.56 /// The placeholder of the search box.
@@ -148,6 +152,14 @@ pub fn t(lang: Lang, key: K) -> &'static str {
148 (K::FilterNobody, Lang::Tr) => "Kimse",152 (K::FilterNobody, Lang::Tr) => "Kimse",
149 (K::FilterSort, Lang::En) => "Sort",153 (K::FilterSort, Lang::En) => "Sort",
150 (K::FilterSort, Lang::Tr) => "Sırala",154 (K::FilterSort, Lang::Tr) => "Sırala",
155+ (K::SortManual, Lang::En) => "Manual",
156+ (K::SortManual, Lang::Tr) => "Elle",
157+ (K::SortManualHint, Lang::En) => {
158+ "Reordering a card needs the Manual sort. Here a card can only move to another column, at its end."
159+ }
160+ (K::SortManualHint, Lang::Tr) => {
161+ "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."
162+ }
151 (K::SortDeadline, Lang::En) => "Deadline",163 (K::SortDeadline, Lang::En) => "Deadline",
152 (K::SortDeadline, Lang::Tr) => "Son tarih",164 (K::SortDeadline, Lang::Tr) => "Son tarih",
153 (K::SortCreated, Lang::En) => "Newest first",165 (K::SortCreated, Lang::En) => "Newest first",
crates/iz-web/src/i18n/task.rsmodified+10 -0
@@ -117,6 +117,10 @@ pub enum K {
117 ActMoved,117 ActMoved,
118 /// Activity: the task was deleted.118 /// Activity: the task was deleted.
119 ActDeleted,119 ActDeleted,
120+ /// Activity: the task was placed at a new spot in its column (Manual sort).
121+ ActReordered,
122+ /// Activity: an administrator restored the deleted task.
123+ ActRestored,
120 /// Activity: someone was assigned.124 /// Activity: someone was assigned.
121 ActAssigned,125 ActAssigned,
122 /// Activity: someone was unassigned.126 /// Activity: someone was unassigned.
@@ -354,6 +358,10 @@ pub fn t(lang: Lang, key: K) -> &'static str {
354 (K::ActMoved, Lang::Tr) => "görevi taşıdı",358 (K::ActMoved, Lang::Tr) => "görevi taşıdı",
355 (K::ActDeleted, Lang::En) => "deleted the task",359 (K::ActDeleted, Lang::En) => "deleted the task",
356 (K::ActDeleted, Lang::Tr) => "görevi sildi",360 (K::ActDeleted, Lang::Tr) => "görevi sildi",
361+ (K::ActReordered, Lang::En) => "moved the card within its column",
362+ (K::ActReordered, Lang::Tr) => "kartı sütunu içinde taşıdı",
363+ (K::ActRestored, Lang::En) => "restored the deleted task",
364+ (K::ActRestored, Lang::Tr) => "silinen görevi geri yükledi",
357 (K::ActAssigned, Lang::En) => "assigned someone",365 (K::ActAssigned, Lang::En) => "assigned someone",
358 (K::ActAssigned, Lang::Tr) => "birini atadı",366 (K::ActAssigned, Lang::Tr) => "birini atadı",
359 (K::ActUnassigned, Lang::En) => "removed an assignee",367 (K::ActUnassigned, Lang::En) => "removed an assignee",
@@ -492,6 +500,8 @@ pub fn activity_kind(lang: Lang, kind: &str) -> &'static str {
492 "task_edited" => K::ActEdited,500 "task_edited" => K::ActEdited,
493 "task_moved" => K::ActMoved,501 "task_moved" => K::ActMoved,
494 "task_deleted" => K::ActDeleted,502 "task_deleted" => K::ActDeleted,
503+ "task_reordered" => K::ActReordered,
504+ "task_restored" => K::ActRestored,
495 "assigned" => K::ActAssigned,505 "assigned" => K::ActAssigned,
496 "unassigned" => K::ActUnassigned,506 "unassigned" => K::ActUnassigned,
497 "tag_changed" => K::ActTagChanged,507 "tag_changed" => K::ActTagChanged,
crates/iz-web/src/pages/admin.rsmodified+1 -0
@@ -55,6 +55,7 @@ pub fn notice_text(lang: Lang, code: &str, queued: Option<&str>) -> Option<Strin
55 "retried" => t(lang, K::NoticeRetried).to_owned(),55 "retried" => t(lang, K::NoticeRetried).to_owned(),
56 "backup" => t(lang, K::NoticeBackupStarted).to_owned(),56 "backup" => t(lang, K::NoticeBackupStarted).to_owned(),
57 "role_set" => structure_t(lang, StructureK::NoticeRoleSet).to_owned(),57 "role_set" => structure_t(lang, StructureK::NoticeRoleSet).to_owned(),
58+ "task_restored" => t(lang, K::NoticeTaskRestored).to_owned(),
58 "limits" => structure_t(lang, StructureK::NoticeLimitsSaved).to_owned(),59 "limits" => structure_t(lang, StructureK::NoticeLimitsSaved).to_owned(),
59 "storage" => structure_t(lang, StructureK::NoticeStorageSaved).to_owned(),60 "storage" => structure_t(lang, StructureK::NoticeStorageSaved).to_owned(),
60 "tag_added" | "tag_renamed" | "tag_coloured" | "tag_deleted" | "tag_moved" => {61 "tag_added" | "tag_renamed" | "tag_coloured" | "tag_deleted" | "tag_moved" => {
crates/iz-web/src/pages/board.rsmodified+11 -10
@@ -64,7 +64,7 @@ pub struct Filters {
64 pub tag: String,64 pub tag: String,
65 /// `none` for nobody, a member id, or empty for anyone.65 /// `none` for nobody, a member id, or empty for anyone.
66 pub assignee: String,66 pub assignee: String,
67- /// `deadline` (the default), `created` or `title`.67+ /// `manual` (the default: the order the cards were placed in), `deadline`, `created` or `title`.
68 pub sort: &'static str,68 pub sort: &'static str,
69 /// The search text, trimmed and at most [`SEARCH_MAX`] characters.69 /// The search text, trimmed and at most [`SEARCH_MAX`] characters.
70 pub query: String,70 pub query: String,
@@ -75,7 +75,7 @@ impl Filters {
75 pub fn active(&self) -> bool {75 pub fn active(&self) -> bool {
76 !self.tag.is_empty()76 !self.tag.is_empty()
77 || !self.assignee.is_empty()77 || !self.assignee.is_empty()
78- || self.sort != "deadline"78+ || self.sort != "manual"
79 || !self.query.is_empty()79 || !self.query.is_empty()
80 }80 }
81 }81 }
@@ -135,8 +135,8 @@ pub fn query_of(path: &str) -> Option<&str> {
135 }135 }
136 136
137 /// Reads the filters from a query string. A bogus project or member id is dropped, as the page would137 /// Reads the filters from a query string. A bogus project or member id is dropped, as the page would
138-/// otherwise show an empty board for a filter the viewer cannot see. An unknown sort falls back to the138+/// otherwise show an empty board for a filter the viewer cannot see. An unknown or missing sort is the
139-/// deadline order.139+/// Manual order.
140 pub fn parse_filters(query: Option<&str>, tags: &[Tag], members: &[Member]) -> Filters {140 pub fn parse_filters(query: Option<&str>, tags: &[Tag], members: &[Member]) -> Filters {
141 let pairs = pairs(query.unwrap_or(""));141 let pairs = pairs(query.unwrap_or(""));
142 let get = |name: &str| {142 let get = |name: &str| {
@@ -161,9 +161,10 @@ pub fn parse_filters(query: Option<&str>, tags: &[Tag], members: &[Member]) -> F
161 String::new()161 String::new()
162 };162 };
163 let (sort, sort_by) = match get("sort").as_str() {163 let (sort, sort_by) = match get("sort").as_str() {
164+ "deadline" => ("deadline", SortBy::Deadline),
164 "created" => ("created", SortBy::Created),165 "created" => ("created", SortBy::Created),
165 "title" => ("title", SortBy::Title),166 "title" => ("title", SortBy::Title),
166- _ => ("deadline", SortBy::Deadline),167+ _ => ("manual", SortBy::Manual),
167 };168 };
168 let query: String = get("q").chars().take(SEARCH_MAX).collect();169 let query: String = get("q").chars().take(SEARCH_MAX).collect();
169 let filter = BoardFilter {170 let filter = BoardFilter {
@@ -194,7 +195,7 @@ pub fn board_url(filters: &Filters, extra: &[(&str, &str)]) -> String {
194 if !filters.assignee.is_empty() {195 if !filters.assignee.is_empty() {
195 parts.push(format!("assignee={}", percent_encode(&filters.assignee)));196 parts.push(format!("assignee={}", percent_encode(&filters.assignee)));
196 }197 }
197- if filters.sort != "deadline" {198+ if filters.sort != "manual" {
198 parts.push(format!("sort={}", filters.sort));199 parts.push(format!("sort={}", filters.sort));
199 }200 }
200 if !filters.query.is_empty() {201 if !filters.query.is_empty() {
@@ -212,7 +213,7 @@ pub fn board_url(filters: &Filters, extra: &[(&str, &str)]) -> String {
212 213
213 /// Whether a member may be assigned: enabled, and an admin or a member (not a viewer or no-access).214 /// Whether a member may be assigned: enabled, and an admin or a member (not a viewer or no-access).
214 fn assignable(member: &Member) -> bool {215 fn assignable(member: &Member) -> bool {
215- !member.disabled && matches!(member.role, Role::Admin | Role::Member)216+ !member.disabled && matches!(member.effective_role(), Role::Admin | Role::Member)
216 }217 }
217 218
218 /// Loads the board for `me` with the filters of `query`. The caller sets the form, alert and notice.219 /// 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(
236 let can_write = authorize(&me.actor(), &Action::WriteTask).is_ok();237 let can_write = authorize(&me.actor(), &Action::WriteTask).is_ok();
237 let viewer = ViewerInfo {238 let viewer = ViewerInfo {
238 name: me.member.name.clone(),239 name: me.member.name.clone(),
239- is_admin: me.member.im_admin || me.member.role == Role::Admin,240+ is_admin: me.member.effective_role() == Role::Admin,
240 csrf: me.session.csrf_token.clone(),241 csrf: me.session.csrf_token.clone(),
241 };242 };
242 Ok(BoardPage {243 Ok(BoardPage {
@@ -407,7 +408,7 @@ mod tests {
407 #[test]408 #[test]
408 fn board_url_keeps_only_set_filters() {409 fn board_url_keeps_only_set_filters() {
409 let mut filters = Filters {410 let mut filters = Filters {
410- sort: "deadline",411+ sort: "manual",
411 ..Filters::default()412 ..Filters::default()
412 };413 };
413 assert_eq!(board_url(&filters, &[]), "/");414 assert_eq!(board_url(&filters, &[]), "/");
@@ -419,7 +420,7 @@ mod tests {
419 #[test]420 #[test]
420 fn unknown_sort_and_empty_filters_fall_back() {421 fn unknown_sort_and_empty_filters_fall_back() {
421 let filters = parse_filters(Some("sort=bogus&tag=nope&assignee=nobody-here"), &[], &[]);422 let filters = parse_filters(Some("sort=bogus&tag=nope&assignee=nobody-here"), &[], &[]);
422- assert_eq!(filters.sort, "deadline");423+ assert_eq!(filters.sort, "manual");
423 assert!(filters.tag.is_empty());424 assert!(filters.tag.is_empty());
424 assert!(filters.assignee.is_empty());425 assert!(filters.assignee.is_empty());
425 assert!(!filters.active());426 assert!(!filters.active());
crates/iz-web/src/pages/files.rsmodified+1 -1
@@ -694,7 +694,7 @@ async fn viewer_page(cx: &Cx) -> Result<Response> {
694 let view = load_view(state, &attachment, &base, sheet).await?;694 let view = load_view(state, &attachment, &base, sheet).await?;
695 let viewer = ViewerInfo {695 let viewer = ViewerInfo {
696 name: me.member.name.clone(),696 name: me.member.name.clone(),
697- is_admin: me.member.im_admin || me.member.role == iz_core::authz::Role::Admin,697+ is_admin: me.member.effective_role() == iz_core::authz::Role::Admin,
698 csrf: me.session.csrf_token.clone(),698 csrf: me.session.csrf_token.clone(),
699 };699 };
700 let back_to = format!("/?task={}", percent_encode(&key));700 let back_to = format!("/?task={}", percent_encode(&key));
crates/iz-web/src/pages/people.rsmodified+6 -2
@@ -48,7 +48,11 @@ async fn person_page(cx: &Cx) -> Result<Response> {
48 48
49 // The target must be a member of this board. Anything else is a plain 404.49 // The target must be a member of this board. Anything else is a plain 404.
50 let target: Member = match state.store.member(&sub).await.map_err(core_err)? {50 let target: Member = match state.store.member(&sub).await.map_err(core_err)? {
51- Some(member) if member.role != iz_core::authz::Role::NoAccess && !member.disabled => member,51+ Some(member)
52+ if member.effective_role() != iz_core::authz::Role::NoAccess && !member.disabled =>
53+ {
54+ member
55+ }
52 _ => return Err(not_found().into()),56 _ => return Err(not_found().into()),
53 };57 };
54 if authorize(&me.actor(), &Action::ViewPerson).is_err() {58 if authorize(&me.actor(), &Action::ViewPerson).is_err() {
@@ -94,7 +98,7 @@ async fn person_page(cx: &Cx) -> Result<Response> {
94 .map(|stamp| local_text(stamp, &zone))98 .map(|stamp| local_text(stamp, &zone))
95 .filter(|text| !text.is_empty())99 .filter(|text| !text.is_empty())
96 .unwrap_or_else(|| t(language, K::PersonNeverSignedIn).to_owned());100 .unwrap_or_else(|| t(language, K::PersonNeverSignedIn).to_owned());
97- let role = role_word(language, target.role.as_str()).to_owned();101+ let role = role_word(language, target.effective_role().as_str()).to_owned();
98 let viewer = ViewerInfo {102 let viewer = ViewerInfo {
99 name: me.member.name.clone(),103 name: me.member.name.clone(),
100 is_admin: authorize(&me.actor(), &Action::Administer).is_ok(),104 is_admin: authorize(&me.actor(), &Action::Administer).is_ok(),
crates/iz-web/src/pages/photo.rsmodified+1 -1
@@ -41,7 +41,7 @@ async fn photo(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
41 return Err(not_found().into());41 return Err(not_found().into());
42 };42 };
43 // A disabled member, or one with no role, has no access to the board, so no photo either.43 // A disabled member, or one with no role, has no access to the board, so no photo either.
44- if member.disabled || member.role == Role::NoAccess {44+ if member.disabled || member.effective_role() == Role::NoAccess {
45 return Err(not_found().into());45 return Err(not_found().into());
46 }46 }
47 47
crates/iz-web/src/pages/settings.rsmodified+71 -2
@@ -11,6 +11,7 @@ use iz_core::sender::{
11 DEFAULT_FROM_NAME, DEFAULT_PORT, SenderInput, TlsMode, validate_password, validate_sender,11 DEFAULT_FROM_NAME, DEFAULT_PORT, SenderInput, TlsMode, validate_password, validate_sender,
12 };12 };
13 use iz_core::store::sender::{ReminderSettings, SenderState};13 use iz_core::store::sender::{ReminderSettings, SenderState};
14+use iz_core::store::tasks::RestoreOutcome;
14 use jiff::Timestamp;15 use jiff::Timestamp;
15 use serde::Deserialize;16 use serde::Deserialize;
16 use topcoat::Result;17 use topcoat::Result;
@@ -30,7 +31,7 @@ use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, record, user_tex
30 use crate::pages::board::the_board;31 use crate::pages::board::the_board;
31 use crate::pages::task::local_text;32 use crate::pages::task::local_text;
32 use crate::state::AppState;33 use crate::state::AppState;
33-use crate::views::admin::{BackupCard, SenderForm, SettingsView, settings_content};34+use crate::views::admin::{BackupCard, DeletedRow, SenderForm, SettingsView, settings_content};
34 use crate::views::structure::{MemberRow, ServerInfo, StorageInfo};35 use crate::views::structure::{MemberRow, ServerInfo, StorageInfo};
35 use crate::views::{ViewerInfo, respond, shell};36 use crate::views::{ViewerInfo, respond, shell};
36 use iz_core::authz::Role;37 use iz_core::authz::Role;
@@ -119,16 +120,31 @@ async fn settings_view(
119 .await?120 .await?
120 .into_iter()121 .into_iter()
121 .map(|m| MemberRow {122 .map(|m| MemberRow {
123+ role: m.effective_role().as_str().to_owned(),
122 sub: m.sub,124 sub: m.sub,
123 name: m.name,125 name: m.name,
124 email: m.email,126 email: m.email,
125- role: m.role.as_str().to_owned(),
126 im_admin: m.im_admin,127 im_admin: m.im_admin,
127 disabled: m.disabled,128 disabled: m.disabled,
128 })129 })
129 .collect();130 .collect();
130 let limit_mib = (policy.limit_bytes / (1024 * 1024)).to_string();131 let limit_mib = (policy.limit_bytes / (1024 * 1024)).to_string();
131 let extensions = policy.extensions.join(" ");132 let extensions = policy.extensions.join(" ");
133+ let zone = parse_zone(&me.member.zoneinfo).unwrap_or(TimeZone::UTC);
134+ let board = the_board(&state.store).await?;
135+ let deleted = state
136+ .store
137+ .deleted_tasks(&board.id)
138+ .await?
139+ .into_iter()
140+ .map(|task| DeletedRow {
141+ id: task.id,
142+ key: task.key,
143+ title: task.title,
144+ at: local_text(&task.deleted_at, &zone),
145+ by: task.deleted_by,
146+ })
147+ .collect();
132 Ok(SettingsView {148 Ok(SettingsView {
133 lang,149 lang,
134 configured: stored.sender.is_some(),150 configured: stored.sender.is_some(),
@@ -143,6 +159,7 @@ async fn settings_view(
143 server: server_info(state).await?,159 server: server_info(state).await?,
144 storage,160 storage,
145 backup: backup_card(state, me).await?,161 backup: backup_card(state, me).await?,
162+ deleted,
146 })163 })
147 }164 }
148 165
@@ -531,6 +548,17 @@ async fn save_role(cx: &Cx, form: Option<Form<RoleSubmit>>) -> Result<Response>
531 let target = path_param_segment(cx, "sub").to_owned();548 let target = path_param_segment(cx, "sub").to_owned();
532 let me = require_csrf(cx, Need::Admin, &form.csrf).await?;549 let me = require_csrf(cx, Need::Admin, &form.csrf).await?;
533 let language = lang(cx, me.member.locale_override.as_deref());550 let language = lang(cx, me.member.locale_override.as_deref());
551+ // An im administrator's role is not changed here: the page shows it read-only, and a forged post is refused too.
552+ if state
553+ .store
554+ .member(&target)
555+ .await?
556+ .is_some_and(|member| member.im_admin)
557+ {
558+ let message = t(language, K::ImRoleLocked).to_owned();
559+ let page = settings_view(state, &me, language, None, None, Some(message)).await?;
560+ return render(cx, &me, page, REFUSED).await;
561+ }
534 let outcome: iz_core::Result<()> = async {562 let outcome: iz_core::Result<()> = async {
535 let role = Role::parse(&form.role)563 let role = Role::parse(&form.role)
536 .ok_or_else(|| iz_core::Error::Invalid("unknown role".into()))?;564 .ok_or_else(|| iz_core::Error::Invalid("unknown role".into()))?;
@@ -566,6 +594,47 @@ async fn save_role(cx: &Cx, form: Option<Form<RoleSubmit>>) -> Result<Response>
566 }594 }
567 }595 }
568 596
597+/// `POST /settings/deleted/{id}/restore`: brings a task deleted in the last 30 days back. Administrators
598+/// only (`require_csrf` with `Need::Admin` is the `Administer` check of `authz`), CSRF first. A refusal the
599+/// admin can read (a deleted parent, an expired deletion) re-renders the page with its reason.
600+#[route(POST "/settings/deleted/{id}/restore")]
601+async fn restore_deleted(cx: &Cx, form: Option<Form<CsrfForm>>) -> Result<Response> {
602+ let state = app_context::<AppState>(cx);
603+ let form = form.map(|Form(form)| form).unwrap_or_default();
604+ let task_id = path_param_segment(cx, "id").to_owned();
605+ let me = require_csrf(cx, Need::Admin, &form.csrf).await?;
606+ let language = lang(cx, me.member.locale_override.as_deref());
607+ let board = the_board(&state.store).await?;
608+ let outcome = state
609+ .store
610+ .restore_task(&board.id, &task_id, &me.member.sub)
611+ .await;
612+ let refusal = match outcome {
613+ Ok(RestoreOutcome::Restored) => {
614+ record(
615+ state,
616+ &me,
617+ "task.restore",
618+ "task",
619+ Some(&task_id),
620+ serde_json::json!({}),
621+ )
622+ .await;
623+ state.live.bump(&Topic::Board(board.id.clone()));
624+ state.live.bump(&Topic::Admin(AdminSection::Settings));
625+ return back("/settings?notice=task_restored#deleted");
626+ }
627+ Ok(RestoreOutcome::ParentDeleted) => K::ErrParentDeleted,
628+ Ok(RestoreOutcome::Expired) => K::ErrRestoreExpired,
629+ Err(iz_core::Error::NotFound) => K::ErrRestoreMissing,
630+ Err(iz_core::Error::Invalid(_)) => K::ErrRestoreFailed,
631+ Err(error) => return Err(error.into()),
632+ };
633+ let message = t(language, refusal).to_owned();
634+ let page = settings_view(state, &me, language, None, None, Some(message)).await?;
635+ render(cx, &me, page, REFUSED).await
636+}
637+
569 /// `POST /settings/attachments`: where attachments are kept. Saving only records the choice; the mover brings the638 /// `POST /settings/attachments`: where attachments are kept. Saving only records the choice; the mover brings the
570 /// files over in the background. `in` needs the Files service to be set up on this server.639 /// files over in the background. `in` needs the Files service to be set up on this server.
571 #[route(POST "/settings/attachments")]640 #[route(POST "/settings/attachments")]
crates/iz-web/src/pages/sign_in.rsmodified+1 -1
@@ -263,7 +263,7 @@ async fn callback(cx: &Cx) -> Result<impl View> {
263 }263 }
264 Err(error) => return Err(error.into()),264 Err(error) => return Err(error.into()),
265 };265 };
266- if stored.disabled || stored.role == Role::NoAccess {266+ if stored.disabled || stored.effective_role() == Role::NoAccess {
267 tracing::info!(sub = %stored.sub, "sign-in: no access for this member");267 tracing::info!(sub = %stored.sub, "sign-in: no access for this member");
268 return message(268 return message(
269 cx,269 cx,
crates/iz-web/src/pages/tasks.rsmodified+7 -2
@@ -79,6 +79,10 @@ struct MoveForm {
79 /// The place among the column's cards, from the top. Empty appends.79 /// The place among the column's cards, from the top. Empty appends.
80 #[serde(default)]80 #[serde(default)]
81 position: String,81 position: String,
82+ /// The sort the board was showing. A place counts only under `manual`; otherwise a card that moves
83+ /// to another column goes to its end, and a drop inside a column changes nothing.
84+ #[serde(default)]
85+ sort: String,
82 /// The board URL the form was on, so a form answer returns there.86 /// The board URL the form was on, so a form answer returns there.
83 #[serde(default)]87 #[serde(default)]
84 next: String,88 next: String,
@@ -366,6 +370,7 @@ async fn move_task(cx: &Cx, form: Option<Form<MoveForm>>) -> Result<Response> {
366 let refusal = refused(422, "invalid", K::InvalidForm);370 let refusal = refused(422, "invalid", K::InvalidForm);
367 return refuse_write(&at, refusal, None).await;371 return refuse_write(&at, refusal, None).await;
368 };372 };
373+ let index = if form.sort == "manual" { index } else { None };
369 let outcome = state374 let outcome = state
370 .store375 .store
371 .move_task(376 .move_task(
@@ -390,8 +395,8 @@ async fn move_task(cx: &Cx, form: Option<Form<MoveForm>>) -> Result<Response> {
390 Err(error) => return Err(error.into()),395 Err(error) => return Err(error.into()),
391 };396 };
392 let refusal = match outcome {397 let refusal = match outcome {
393- MoveOutcome::Moved | MoveOutcome::Unchanged => {398+ MoveOutcome::Moved | MoveOutcome::Reordered | MoveOutcome::Unchanged => {
394- if outcome == MoveOutcome::Moved {399+ if matches!(outcome, MoveOutcome::Moved | MoveOutcome::Reordered) {
395 state.live.bump(&Topic::Board(board.id.clone()));400 state.live.bump(&Topic::Board(board.id.clone()));
396 }401 }
397 if json {402 if json {
crates/iz-web/src/views/admin.rsmodified+56 -0
@@ -140,6 +140,23 @@ pub struct SettingsView {
140 pub storage: crate::views::structure::StorageInfo,140 pub storage: crate::views::structure::StorageInfo,
141 /// The Backups card: whether backups are on, and the outcome of the last runs.141 /// The Backups card: whether backups are on, and the outcome of the last runs.
142 pub backup: BackupCard,142 pub backup: BackupCard,
143+ /// The Recently deleted card: tasks deleted within the restore window, newest first.
144+ pub deleted: Vec<DeletedRow>,
145+}
146+
147+/// One row of the Recently deleted card. `at` is already in the viewer's zone.
148+#[derive(Debug, Clone, Default)]
149+pub struct DeletedRow {
150+ /// Task id, for the restore form.
151+ pub id: String,
152+ /// Readable key `PREFIX-n`.
153+ pub key: String,
154+ /// Title.
155+ pub title: String,
156+ /// When it was deleted, as `YYYY-MM-DD HH:MM`.
157+ pub at: String,
158+ /// The name of who deleted it, when the activity trail recorded it.
159+ pub by: Option<String>,
143 }160 }
144 161
145 /// The Backups card. Times are already in the viewer's zone; an empty text means nothing was recorded.162 /// 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<impl Vi
366 <p class="field-hint">(t(lang, K::BackupOff))</p>383 <p class="field-hint">(t(lang, K::BackupOff))</p>
367 }384 }
368 </section>385 </section>
386+ <section class="card" id="deleted">
387+ <h2>(t(lang, K::DeletedHeading))</h2>
388+ <p class="field-hint">(t(lang, K::DeletedHelp))</p>
389+ if page.deleted.is_empty() {
390+ <p class="field-hint">(t(lang, K::DeletedEmpty))</p>
391+ } else {
392+ <table class="admin-table">
393+ <thead>
394+ <tr>
395+ <th>(t(lang, K::DeletedTaskHeader))</th>
396+ <th>(t(lang, K::DeletedAtHeader))</th>
397+ <th>(t(lang, K::DeletedByHeader))</th>
398+ <th></th>
399+ </tr>
400+ </thead>
401+ <tbody>
402+ for row in page.deleted.iter() {
403+ <tr>
404+ <td>(row.key.as_str()) " " (row.title.as_str())</td>
405+ <td>(row.at.as_str())</td>
406+ <td>
407+ if let Some(name) = &row.by {
408+ (name.as_str())
409+ } else {
410+ (t(lang, K::DeletedUnknown))
411+ }
412+ </td>
413+ <td>
414+ <form method="post" action=(format!("/settings/deleted/{}/restore", row.id)) class="inline">
415+ <input type="hidden" name="csrf" value=(csrf)>
416+ <button class="button" type="submit">(t(lang, K::RestoreButton))</button>
417+ </form>
418+ </td>
419+ </tr>
420+ }
421+ </tbody>
422+ </table>
423+ }
424+ </section>
369 members_section(lang: lang, members: &page.members, csrf: csrf)425 members_section(lang: lang, members: &page.members, csrf: csrf)
370 storage_section(lang: lang, info: &page.storage, csrf: csrf)426 storage_section(lang: lang, info: &page.storage, csrf: csrf)
371 limits_section(lang: lang, limit_mib: page.limit_mib.as_str(), extensions: page.extensions.as_str(), csrf: csrf)427 limits_section(lang: lang, limit_mib: page.limit_mib.as_str(), extensions: page.extensions.as_str(), csrf: csrf)
crates/iz-web/src/views/board.rsmodified+5 -0
@@ -63,6 +63,7 @@ pub async fn board_content(page: &BoardPage) -> Result<impl View> {
63 <section class="board" data-live="/board/live"63 <section class="board" data-live="/board/live"
64 data-board-write=(flag(page.can_write))64 data-board-write=(flag(page.can_write))
65 data-csrf=(page.viewer.csrf.as_str())65 data-csrf=(page.viewer.csrf.as_str())
66+ data-sort=(page.filters.sort)
66 data-msg-failed=(t(lang, K::MoveFailed))>67 data-msg-failed=(t(lang, K::MoveFailed))>
67 <div class="board-toolbar">68 <div class="board-toolbar">
68 <div class="board-summary">69 <div class="board-summary">
@@ -85,6 +86,9 @@ pub async fn board_content(page: &BoardPage) -> Result<impl View> {
85 }86 }
86 if page.can_write {87 if page.can_write {
87 <p class="muted">(t(lang, K::DragHint))</p>88 <p class="muted">(t(lang, K::DragHint))</p>
89+ if page.filters.sort != "manual" {
90+ <p class="muted">(t(lang, K::SortManualHint))</p>
91+ }
88 } else {92 } else {
89 <p class="muted">(t(lang, K::ReadOnly))</p>93 <p class="muted">(t(lang, K::ReadOnly))</p>
90 }94 }
@@ -138,6 +142,7 @@ pub async fn filter_bar(page: &BoardPage) -> Result<impl View> {
138 <div class="field">142 <div class="field">
139 <label for="f-sort">(t(lang, K::FilterSort))</label>143 <label for="f-sort">(t(lang, K::FilterSort))</label>
140 <select id="f-sort" name="sort">144 <select id="f-sort" name="sort">
145+ <option value="manual" selected=(flag(filters.sort == "manual"))>(t(lang, K::SortManual))</option>
141 <option value="deadline" selected=(flag(filters.sort == "deadline"))>(t(lang, K::SortDeadline))</option>146 <option value="deadline" selected=(flag(filters.sort == "deadline"))>(t(lang, K::SortDeadline))</option>
142 <option value="created" selected=(flag(filters.sort == "created"))>(t(lang, K::SortCreated))</option>147 <option value="created" selected=(flag(filters.sort == "created"))>(t(lang, K::SortCreated))</option>
143 <option value="title" selected=(flag(filters.sort == "title"))>(t(lang, K::SortTitle))</option>148 <option value="title" selected=(flag(filters.sort == "title"))>(t(lang, K::SortTitle))</option>
crates/iz-web/src/views/structure.rsmodified+4 -0
@@ -360,6 +360,9 @@ pub async fn members_section(lang: Lang, members: &[MemberRow], csrf: &str) -> R
360 }360 }
361 </td>361 </td>
362 <td>362 <td>
363+ if member.im_admin {
364+ <span>(t(lang, K::RoleAdmin))</span>
365+ } else {
363 <form method="post" action=(format!("/settings/members/{}/role", member.sub)) class="inline">366 <form method="post" action=(format!("/settings/members/{}/role", member.sub)) class="inline">
364 <input type="hidden" name="csrf" value=(csrf)>367 <input type="hidden" name="csrf" value=(csrf)>
365 <select name="role" aria-label=(t(lang, K::MemberRole))>368 <select name="role" aria-label=(t(lang, K::MemberRole))>
@@ -370,6 +373,7 @@ pub async fn members_section(lang: Lang, members: &[MemberRow], csrf: &str) -> R
370 </select>373 </select>
371 <button class="button" type="submit">(t(lang, K::MemberSave))</button>374 <button class="button" type="submit">(t(lang, K::MemberSave))</button>
372 </form>375 </form>
376+ }
373 </td>377 </td>
374 </tr>378 </tr>
375 }379 }
docs/architecture.mdmodified+26 -10
@@ -90,7 +90,7 @@ board (partial unique index). Admin can add, rename, reorder, delete (only when
90 90
91 **tasks**: `id`, `board_id`, `key` (UNIQUE per board, `PREFIX-<n>` from a per-board counter: readable and never91 **tasks**: `id`, `board_id`, `key` (UNIQUE per board, `PREFIX-<n>` from a per-board counter: readable and never
92 reused), `parent_id` NULL (one level, enforced by trigger and by store), `title` (1–200), `description` (≤20 000),92 reused), `parent_id` NULL (one level, enforced by trigger and by store), `title` (1–200), `description` (≤20 000),
93-`column_id`, `tag_id` NOT NULL, `deadline` NULL (date), `meeting_at` NULL (UTC instant), `position` REAL,93+`column_id`, `tag_id` NOT NULL, `deadline` NULL (date), `meeting_at` NULL (UTC instant), `position` REAL (the Manual order, section 5),
94 `created_by`, `created_at`, `updated_at`, `done_at` NULL, `deleted_at` NULL.94 `created_by`, `created_at`, `updated_at`, `done_at` NULL, `deleted_at` NULL.
95 95
96 **task_assignees** (task, sub) PK. **task_watchers** (task, sub) PK — watchers receive "board" audience mail96 **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).
108 108
109 **transitions**: `id`, `task_id`, `from_column` NULL, `to_column`, `actor`, `at`.109 **transitions**: `id`, `task_id`, `from_column` NULL, `to_column`, `actor`, `at`.
110 110
111-**activity**: `id`, `task_id` NULL, `actor` NULL (NULL = system), `subject` NULL, `kind` (enum with CHECK),111+**activity**: `id`, `task_id` NULL, `actor` NULL (NULL = system), `subject` NULL, `kind` (enum with CHECK; migration
112-`detail` JSON, `at`. Rendered into sentences in the viewer's language at read time.112+0007 added `task_reordered` and `task_restored`), `detail` JSON, `at`. Rendered into sentences in the viewer's
113+language at read time.
113 114
114 **mail_rules**: `id`, `board_id`, `name`, `trigger` (enum CHECK, 12 triggers from inventory 2.9), `column_id`115 **mail_rules**: `id`, `board_id`, `name`, `trigger` (enum CHECK, 12 triggers from inventory 2.9), `column_id`
115 NULL (only for `status`, CHECK), `tag_id` NULL (new: limit a rule to one project), `audience` CHECK IN116 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
137 138
138 | Path | What |139 | Path | What |
139 |---|---|140 |---|---|
140-| `GET /` | board (inventory 2.2): columns, cards, filters (`tag`, `assignee`, `sort`, `q`), overdue/blocked chips, card menus, drag and drop; `?task=<key>` opens the task modal, `?new=1` the new-task modal |141+| `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=<key>` opens the task modal, `?new=1` the new-task modal |
141 | `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 |142 | `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 |
142 | `POST /tasks/{id}/comments`, `/comments/{id}/edit`, `/comments/{id}/delete` | comments |143 | `POST /tasks/{id}/comments`, `/comments/{id}/edit`, `/comments/{id}/delete` | comments |
143 | `POST /tasks/{id}/files` (multipart, streamed), `/files/{id}/delete`; `GET /files/{id}` | attachments |144 | `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
147 | `GET /columns` + POSTs | columns (admin) |148 | `GET /columns` + POSTs | columns (admin) |
148 | `GET /rules` + POSTs | mail rules (admin), sentence rendering, enable switch, edit |149 | `GET /rules` + POSTs | mail rules (admin), sentence rendering, enable switch, edit |
149 | `GET /logs` | admin: outbox (retry), decisions, activity (filters, keyset paging) |150 | `GET /logs` | admin: outbox (retry), decisions, activity (filters, keyset paging) |
150-| `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) |151+| `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) |
151 | `GET /avatar/{sub}` | photo proxy with disk cache, only for members of this board |152 | `GET /avatar/{sub}` | photo proxy with disk cache, only for members of this board |
152 | OIDC client routes, `/-/alive`, live streams, `/healthz`, `/assets/*` | |153 | OIDC client routes, `/-/alive`, live streams, `/healthz`, `/assets/*` | |
153 154
154-`POST /tasks/{id}/move` carries the column the client last saw; a stale move is refused (`moved_already`), a155+`POST /tasks/{id}/move` carries the column the client last saw, the sort the board showed and, for a drop, the
155-move into the done column with open subtasks is refused (`subtasks_open`), as in old iz.156+place (`position`). A stale move is refused (`moved_already`), a move into the done column with open subtasks is
157+refused (`subtasks_open`), as in old iz. The place is used only under `sort=manual`: then a drop in the same column
158+is a reorder (`Reordered`, activity `task_reordered`), and a drop in another column lands at the place. Under any
159+other sort the place is ignored: a card moved to another column goes to the end of it, and a drop within its own
160+column changes nothing.
156 161
157 ---162 ---
158 163
@@ -162,6 +167,14 @@ move into the done column with open subtasks is refused (`subtasks_open`), as in
162 overdue when the day is before today in the viewer's zone.167 overdue when the day is before today in the viewer's zone.
163 - Done: entering the done column stamps `done_at`; leaving it clears it; a card with open subtasks cannot enter.168 - Done: entering the done column stamps `done_at`; leaving it clears it; a card with open subtasks cannot enter.
164 - Subtasks: one level; a parent with children cannot become a subtask; deleting a parent deletes its children.169 - Subtasks: one level; a parent with children cannot become a subtask; deleting a parent deletes its children.
170+- Order: the default sort is Manual (`position`, then id). Each column's cards take their `position` from the
171+ neighbours they are placed between; a column is renumbered (1, 2, 3, ...) only when two neighbours are less than
172+ 1e-9 apart. Under deadline, created or title the only drag is to another column, which lands at its end.
173+- Restore: a deleted task can be restored for 30 days after its deletion (`RESTORE_DAYS`); there is no purge, so
174+ older deletions are final. One transaction clears `deleted_at` on the task and on the subtasks that share its
175+ deletion stamp. A task whose column was retired goes to the first column that is not done (and loses `done_at`
176+ there). A subtask whose parent is still deleted is refused. Reminders are rebuilt. Links cleared by the deletion
177+ and the files of the task (removed with it) do not come back. Only administrators (`Administer`).
165 - Dependencies: no cycles over live edges; soft clear; a finished blocker stops blocking; deleting a blocker178 - Dependencies: no cycles over live edges; soft clear; a finished blocker stops blocking; deleting a blocker
166 frees its dependents and fires `unblocked`.179 frees its dependents and fires `unblocked`.
167 - Viewers: read-only, never assigned, never mailed. Members with role `none` or disabled: no access, not mailed.180 - 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
178 191
179 `authz::authorize(actor, action)` with `actor` = `Anonymous | Member { sub, role, im_admin, disabled }` and192 `authz::authorize(actor, action)` with `actor` = `Anonymous | Member { sub, role, im_admin, disabled }` and
180 `action` from: `ReadBoard`, `WriteTask`, `Comment`, `EditComment { author }`, `UploadFile`,193 `action` from: `ReadBoard`, `WriteTask`, `Comment`, `EditComment { author }`, `UploadFile`,
181-`DeleteFile { uploader }`, `Administer`, `ViewPerson { sub }`. Roles: Admin ⊇ Member ⊇ Viewer; `none` and194+`DeleteFile { uploader }`, `Administer`, `ViewPerson { sub }`. Roles: Admin ⊇ Member ⊇ Viewer. An `im`
182-disabled are denied everything (404 for pages, the sign-in card for `/`). Deleting a file: uploader while still a195+administrator (`im_admin`) acts as Admin whatever the stored role is, `none` included; the store applies the same
183-Member, or Admin. Truth-table tested.196+rule in its own queries (sessions, assignees, reminders, mail recipients) and the members page does not offer
197+their role for change (a forged change is refused too). A disabled account is denied everything (404 for pages,
198+the sign-in card for `/`), and so is a member with role `none` who is not an `im` administrator. Deleting a file:
199+uploader while still a Member, or Admin. Truth-table tested.
184 200
185 ---201 ---
186 202