diff --git a/crates/izlek-core/src/store/mod.rs b/crates/izlek-core/src/store/mod.rs index 1bd32c3..107fc8b 100644 --- a/crates/izlek-core/src/store/mod.rs +++ b/crates/izlek-core/src/store/mod.rs @@ -1088,6 +1088,11 @@ pub trait Store: BoardReads + DetailReads + 'static { /// Every tag on the board, in the admin's hand-set order. async fn tags(&self, board_id: &str) -> Result>; + /// How many live cards wear each of the board's tags, keyed by tag id. A + /// tag nobody uses is absent rather than zero — the caller reads a + /// missing key as none, which is what a fresh tag is. + async fn tag_task_counts(&self, board_id: &str) -> Result>; + /// Appends a tag at the end of the board's order. The name is unique per /// board: two tags with one name are one project spelled twice. async fn create_tag(&self, board_id: &str, name: &str, at: OffsetDateTime) -> Result; @@ -1096,6 +1101,11 @@ pub trait Store: BoardReads + DetailReads + 'static { /// Deletes a tag. Its tasks move to the board's default tag; the default /// itself is refused — it is where they would go. + /// Retires a tag. A tag with cards on it is refused with + /// [`StoreError::Conflict`] — the cards are the reason it exists, and + /// moving somebody's whole project onto the default because one menu item + /// was clicked is not a deletion the admin asked for. The default tag is + /// refused as well: it is where a card with no project of its own lives. async fn delete_tag(&self, tag_id: &str) -> Result<()>; /// Swaps a tag with its neighbour in the order. A tag already at that end @@ -1322,6 +1332,11 @@ pub trait Store: BoardReads + DetailReads + 'static { /// settled. Only rows that are still pending and have never been /// attempted move — a mail already refused is on its own retry clock, and /// a batch must not drag it back. + /// + /// It only ever postpones. A delivery pass writes its lease into the same + /// column, so a hold that moved a row *earlier* would hand the mail a + /// second pass is composing to a third one, and the reader would get it + /// twice. async fn hold_batch( &self, task_id: &str, diff --git a/crates/izlek-core/src/store/turso_store.rs b/crates/izlek-core/src/store/turso_store.rs index 460c275..54f2b4a 100644 --- a/crates/izlek-core/src/store/turso_store.rs +++ b/crates/izlek-core/src/store/turso_store.rs @@ -3733,7 +3733,7 @@ impl Store for TursoStore { // date-format trick rather than a calculation. let mut rows = conn .query( - "SELECT id, claimed_at FROM mail_send \ + "SELECT id, claimed_at, next_attempt_at FROM mail_send \ WHERE task_id = ?1 AND recipient = ?2 AND kind = 'rule' \ AND state = 'pending' AND attempts = 0 \ AND next_attempt_at IS NOT NULL", @@ -3745,15 +3745,25 @@ impl Store for TursoStore { while let Some(row) = rows.next().await.map_err(backend)? { let id = text(&row, 0)?; let born = parse_stamp(&text(&row, 1)?)?; - held.push((id, born)); + let due = parse_stamp(&text(&row, 2)?)?; + held.push((id, born, due)); } drop(rows); - for (id, born) in held { + for (id, born, due) in held { let ceiling = born + cap; let when = if until > ceiling { ceiling } else { until }; + // Only ever later. A row a delivery pass is holding — its lease is + // written in this same column — must not be pulled back under the + // pass that took it, or the mail it is composing right now becomes + // due for a second pass and goes out twice. The `<` in the update + // is the guard, not the read above it: the two are one statement. + if when <= due { + continue; + } conn.execute( "UPDATE mail_send SET next_attempt_at = ?1 \ - WHERE id = ?2 AND state = 'pending' AND attempts = 0", + WHERE id = ?2 AND state = 'pending' AND attempts = 0 \ + AND next_attempt_at < ?1", params![stamp(when)?, id], ) .await @@ -3816,6 +3826,23 @@ impl Store for TursoStore { Ok(out) } + async fn tag_task_counts(&self, board_id: &str) -> Result> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT tag_id, COUNT(*) FROM task \ + WHERE board_id = ?1 AND deleted_at IS NULL GROUP BY tag_id", + params![board_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push((text(&row, 0)?, row.get::(1).map_err(backend)? as u32)); + } + Ok(out) + } + async fn create_tag(&self, board_id: &str, name: &str, at: OffsetDateTime) -> Result { let id = Ulid::new().to_string(); let now = stamp(at)?; @@ -3903,8 +3930,12 @@ impl Store for TursoStore { .map_err(backend)?; // The default is the board's fallback, not a project anyone can // retire: deleting it would leave its board's tasks nowhere to go. - // Any other tag's tasks move to that default, in the one write set: - // no task is ever seen pointing at a project that is not there. + // Any other tag is deletable only while it is empty — a tag with + // cards on it is a project somebody is working in, and a delete that + // quietly re-files that work is not a delete they asked for. Cards + // already thrown away are the exception: they are nobody's work any + // more, and they move to the default so the reference they still hold + // points at something. let deleted = async { let mut rows = tx .query( @@ -3921,6 +3952,20 @@ impl Store for TursoStore { if is_default != 0 { return Ok(Err(StoreError::Conflict("default_tag"))); } + let mut rows = tx + .query( + "SELECT COUNT(*) FROM task WHERE tag_id = ?1 AND deleted_at IS NULL", + params![tag_id], + ) + .await?; + let live: i64 = match rows.next().await? { + Some(row) => row.get(0)?, + None => 0, + }; + drop(rows); + if live > 0 { + return Ok(Err(StoreError::Conflict("tag_in_use"))); + } tx.execute( "UPDATE task SET tag_id = \ (SELECT id FROM tag WHERE board_id = ?1 AND is_default = 1) \ diff --git a/crates/izlek-core/tests/store.rs b/crates/izlek-core/tests/store.rs index 2902f4c..3be28a7 100644 --- a/crates/izlek-core/tests/store.rs +++ b/crates/izlek-core/tests/store.rs @@ -2905,7 +2905,7 @@ fn card_of<'a>( } #[tokio::test] -async fn deleting_a_tag_moves_its_tasks_to_the_default_and_a_foreign_tag_is_not_found() { +async fn a_tag_is_worn_a_foreign_one_is_not_found_and_a_worn_one_is_not_deletable() { let (scratch, workspace, admin) = workspace_with_admin().await; let store = &scratch.store; let board = store.board(&workspace).await.unwrap().unwrap(); @@ -2956,14 +2956,88 @@ async fn deleting_a_tag_moves_its_tasks_to_the_default_and_a_foreign_tag_is_not_ Err(StoreError::NotFound) )); - // Deleting a worn tag leaves the task on the board's default, and the - // task survives. - store.delete_tag(&tag.id).await.unwrap(); + // A tag with a card on it is not deletable: the card is the reason the + // project exists, and nothing about it moves. + assert!(matches!( + store.delete_tag(&tag.id).await, + Err(StoreError::Conflict("tag_in_use")) + )); let view = board_of(store, &workspace).await; assert_eq!( card_of(&view, &task).tag.as_ref().map(|t| t.name.as_str()), - Some("General") + Some("ops"), + "the refused delete moved the card anyway" ); + assert_eq!(store.tags(&board.id).await.unwrap().len(), 2); + + // Emptied, it goes. + let default = store + .tags(&board.id) + .await + .unwrap() + .into_iter() + .find(|t| t.is_default) + .unwrap(); + store.set_task_tag(&task, &default.id).await.unwrap(); + store.delete_tag(&tag.id).await.unwrap(); + assert_eq!(store.tags(&board.id).await.unwrap().len(), 1); +} + +/// The counts the tags screen draws, and the one card that stops counting. +#[tokio::test] +async fn tag_counts_hold_the_live_cards_and_a_thrown_away_card_stops_blocking() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let board = store.board(&workspace).await.unwrap().unwrap(); + let tag = store + .create_tag(&board.id, "ops", OffsetDateTime::now_utc()) + .await + .unwrap(); + let first = add_task(store, &workspace, "Backlog", "one", None, &admin).await; + let second = add_task(store, &workspace, "Backlog", "two", None, &admin).await; + store.set_task_tag(&first, &tag.id).await.unwrap(); + store.set_task_tag(&second, &tag.id).await.unwrap(); + + let counts = store.tag_task_counts(&board.id).await.unwrap(); + assert_eq!( + counts.iter().find(|(id, _)| id == &tag.id).map(|(_, n)| *n), + Some(2) + ); + + // A card thrown away is nobody's work any more: it stops counting, and + // once the last live one is gone the tag can be retired — the deleted + // card's own reference moves to the default rather than dangling. + store + .delete_task(&first, &admin, OffsetDateTime::now_utc()) + .await + .unwrap(); + assert!(matches!( + store.delete_tag(&tag.id).await, + Err(StoreError::Conflict("tag_in_use")), + )); + store + .delete_task(&second, &admin, OffsetDateTime::now_utc()) + .await + .unwrap(); + assert_eq!( + store + .tag_task_counts(&board.id) + .await + .unwrap() + .iter() + .find(|(id, _)| id == &tag.id), + None, + "a tag nobody wears is absent, not zero" + ); + store.delete_tag(&tag.id).await.unwrap(); + + // Nothing points at a tag that is not there. + let mut broken = raw_conn(&scratch) + .await + .query("PRAGMA foreign_key_check", ()) + .await + .unwrap(); + assert!(broken.next().await.unwrap().is_none()); } #[tokio::test] @@ -7503,6 +7577,65 @@ async fn the_hold_has_a_ceiling_measured_from_the_oldest_mail() { let _ = std::fs::remove_dir_all(&dir); } +/// A hold only ever postpones. The delivery pass writes its lease into the +/// same column, so a hold that pulled a leased row back would make the mail +/// one pass is composing due for another — and the reader would get it twice. +#[tokio::test] +async fn a_hold_never_pulls_a_leased_row_back_under_the_pass_that_took_it() { + let (dir, store, workspace, admin) = waiting(1).await; + let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await; + store.assign_task(&task, &mate).await.unwrap(); + let rule = a_rule(&store, &workspace, "Done", "Card is done").await; + + let now = OffsetDateTime::now_utc(); + store + .claim_send(&rule.id, "event-1", &task, "emre@izlek.sh", now, now) + .await + .unwrap() + .expect("a fresh row is claimed"); + // A delivery pass takes it: the lease is five minutes out. + let taken = store + .claim_sends_owed(now + Duration::seconds(1), now + izlek_core::mail::LEASE, 10) + .await + .unwrap(); + assert_eq!(taken.len(), 1, "the pass did not take the row"); + let leased = the_one_row(&store).await.next_attempt_at.unwrap(); + + // A new trigger on the same card, one quiet minute out: earlier than the + // lease, so it must change nothing. + store + .hold_batch( + &task, + "emre@izlek.sh", + now + Duration::minutes(1), + Duration::minutes(4), + ) + .await + .unwrap(); + assert_eq!( + the_one_row(&store).await.next_attempt_at.unwrap(), + leased, + "the hold pulled a row out from under the pass holding it" + ); + + // A hold past the lease is a postponement, and does apply. + store + .hold_batch( + &task, + "emre@izlek.sh", + now + Duration::minutes(30), + Duration::hours(2), + ) + .await + .unwrap(); + assert!( + the_one_row(&store).await.next_attempt_at.unwrap() > leased, + "a real postponement was refused too" + ); + let _ = std::fs::remove_dir_all(&dir); +} + /// A workspace with no window is İzlek as it was: a trigger is a mail, sent /// the moment it is owed. #[tokio::test] diff --git a/crates/izlek-web/src/server.rs b/crates/izlek-web/src/server.rs index aa426da..f92c87f 100644 --- a/crates/izlek-web/src/server.rs +++ b/crates/izlek-web/src/server.rs @@ -359,6 +359,9 @@ pub enum Refusal { EmptySubject, /// A tag with no name is not a tag the board can show. EmptyTag, + /// A tag with cards on it stays. Emptying it is the admin's job, and it + /// is one they can see the size of. + TagInUse, /// A message with no body: there is nothing for the recipient to read. EmptyBody, /// The date field did not hold a date. @@ -422,6 +425,7 @@ impl Refusal { Refusal::NotAnImage => "That is not an image.".to_string(), Refusal::EmptySubject => "Give the rule a subject line.".to_string(), Refusal::EmptyTag => "Give the tag a name.".to_string(), + Refusal::TagInUse => "This tag still has cards.".to_string(), Refusal::EmptyBody => "Write something first.".to_string(), Refusal::BadDeadline => "That is not a date.".to_string(), Refusal::Cycle => "That link would put this task behind itself.".to_string(), @@ -481,6 +485,7 @@ impl Refusal { Refusal::BadSender(_) => self.message(), Refusal::EmptySubject => "Kurala bir konu ver.".to_string(), Refusal::EmptyTag => "Etikete bir ad ver.".to_string(), + Refusal::TagInUse => "Bu etikette kartlar var.".to_string(), Refusal::EmptyBody => "Önce bir şey yaz.".to_string(), Refusal::Rejected => "Bu işe yaramadı.".to_string(), Refusal::RateLimited => { @@ -531,6 +536,7 @@ impl Refusal { "not-an-image" => Refusal::NotAnImage, "empty-subject" => Refusal::EmptySubject, "empty-tag" => Refusal::EmptyTag, + "tag-in-use" => Refusal::TagInUse, "empty-body" => Refusal::EmptyBody, "bad-deadline" => Refusal::BadDeadline, "cycle" => Refusal::Cycle, @@ -587,6 +593,7 @@ impl Refusal { Refusal::NotAnImage => "not-an-image", Refusal::EmptySubject => "empty-subject", Refusal::EmptyTag => "empty-tag", + Refusal::TagInUse => "tag-in-use", Refusal::EmptyBody => "empty-body", Refusal::BadDeadline => "bad-deadline", Refusal::Cycle => "cycle", @@ -874,6 +881,7 @@ mod refusal_message_tests { Refusal::NotNestable, Refusal::NotFound, Refusal::NoSuchMember, + Refusal::TagInUse, Refusal::Unavailable, ]; for refusal in all { diff --git a/crates/izlek-web/src/tags.rs b/crates/izlek-web/src/tags.rs index dbb1944..d13df83 100644 --- a/crates/izlek-web/src/tags.rs +++ b/crates/izlek-web/src/tags.rs @@ -39,6 +39,9 @@ struct TagLine { name: String, position: i64, is_default: bool, + /// Cards wearing this tag. A tag with any is not deletable, and the row + /// says how many rather than leaving the admin to guess why. + tasks: u32, } /// Every tag on the workspace's own board, in the admin's hand-set order. @@ -53,12 +56,21 @@ async fn tags_of( else { return Err(Refusal::Unavailable); }; + let counts = store + .tag_task_counts(&board.id) + .await + .map_err(|_| Refusal::Unavailable)?; Ok(store .tags(&board.id) .await .map_err(|_| Refusal::Unavailable)? .into_iter() .map(|tag| TagLine { + tasks: counts + .iter() + .find(|(id, _)| id == &tag.id) + .map(|(_, count)| *count) + .unwrap_or(0), id: tag.id, name: tag.name, position: tag.position, @@ -179,19 +191,24 @@ struct DeleteTagForm { tag_id: String, } -/// Removes a tag. The store refuses to delete the default — every task -/// without a tag wears it — and that refusal lands here as "unavailable"; -/// the row itself ships no delete control in the first place. +/// Removes a tag. The store refuses two of them: the default — every task +/// without a project of its own wears it — and any tag that still has cards, +/// which comes back named so the admin reads why rather than "something went +/// wrong". Neither row ships a delete control in the first place; this is +/// the same rule where it is actually enforced. #[route(POST "/api/delete_tag")] async fn delete_tag(cx: &Cx, Form(input): Form) -> Redirect { let (store, _, _) = match tag_of_this_workspace(cx, &input.tag_id).await { Ok(triple) => triple, Err(refusal) => return redirect(cx, Some(refusal)), }; - if store.delete_tag(&input.tag_id).await.is_err() { - return redirect(cx, Some(Refusal::Unavailable)); + match store.delete_tag(&input.tag_id).await { + Ok(()) => redirect(cx, None), + Err(izlek_core::store::StoreError::Conflict("tag_in_use")) => { + redirect(cx, Some(Refusal::TagInUse)) + } + Err(_) => redirect(cx, Some(Refusal::Unavailable)), } - redirect(cx, None) } #[derive(Deserialize)] @@ -251,8 +268,10 @@ async fn composer(cx: &Cx, refusal: Option<&Refusal>, lang: Lang) -> Result { } /// One tag's row: the rename form in place of it when `editing`, its display -/// otherwise. The default tag draws no delete form — the store would refuse -/// it, and a control that cannot act is not drawn. +/// otherwise. The default tag draws no delete form, and neither does a tag +/// with cards on it — the store would refuse both, and a control that cannot +/// act is not drawn. The card count sits on the row, so a missing delete is +/// a number the admin can already see rather than a control that vanished. async fn tag_row(cx: &Cx, tag: &TagLine, editing: bool, refusal: Option<&Refusal>, lang: Lang) -> Result { if editing { return view! { @@ -280,6 +299,7 @@ async fn tag_row(cx: &Cx, tag: &TagLine, editing: bool, refusal: Option<&Refusal cx =>
(tag.name.clone()) + (tag.tasks) (t(lang, Key::EditLabel)) @@ -294,7 +314,7 @@ async fn tag_row(cx: &Cx, tag: &TagLine, editing: bool, refusal: Option<&Refusal - if !tag.is_default { + if !tag.is_default && tag.tasks == 0 {
diff --git a/crates/izlek-web/tests/http.rs b/crates/izlek-web/tests/http.rs index 70a83bf..590bc91 100644 --- a/crates/izlek-web/tests/http.rs +++ b/crates/izlek-web/tests/http.rs @@ -7525,6 +7525,74 @@ async fn the_default_tag_cannot_be_deleted_and_ships_no_delete_button() { assert!(page.contains("Aurora"), "the created tag is not listed: {page}"); } +/// A tag with cards on it stays: no delete control on its row, and the call +/// itself refused by name if somebody posts it anyway. Emptying it is what +/// makes it deletable. +#[tokio::test] +async fn a_tag_with_cards_on_it_cannot_be_deleted() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let aurora = a_tag(&app, &admin_cookie, "Aurora").await; + let workspace_id = app.workspace_id().await; + let board = app.store.board(&workspace_id).await.unwrap().expect("no board"); + let open = app.store.columns(&board.id).await.unwrap()[0].id.clone(); + let admin_id = app + .store + .users(&workspace_id) + .await + .unwrap() + .into_iter() + .find(|user| user.role == Role::Admin) + .unwrap() + .id; + let task = a_task_by(&app, &board.id, &open, "Hold the door", &admin_id).await; + app.store.set_task_tag(&task, &aurora.id).await.unwrap(); + + let page = String::from_utf8(app.get("/tags", Some(&admin_cookie)).await.bytes).unwrap(); + assert_eq!( + page.matches(r#"action="/api/delete_tag""#).count(), + 0, + "a tag with a card on it still offers a delete: {page}" + ); + assert!( + page.contains(r#"1"#), + "the row does not say how many cards are on it: {page}" + ); + + let refused = app + .post("/api/delete_tag", Some(&admin_cookie), &[("tag_id", &aurora.id)]) + .await; + assert!( + refused.body.contains("TagInUse"), + "the refusal does not name itself: {}", + refused.body + ); + assert_eq!( + app.store.tags(&board.id).await.unwrap().len(), + 2, + "the tag went anyway" + ); + + // Moved off it, the tag is deletable again — control and call both. + let default_id = app + .store + .tags(&board.id) + .await + .unwrap() + .into_iter() + .find(|tag| tag.is_default) + .unwrap() + .id; + app.store.set_task_tag(&task, &default_id).await.unwrap(); + let page = String::from_utf8(app.get("/tags", Some(&admin_cookie)).await.bytes).unwrap(); + assert_eq!(page.matches(r#"action="/api/delete_tag""#).count(), 1); + let gone = app + .post("/api/delete_tag", Some(&admin_cookie), &[("tag_id", &aurora.id)]) + .await; + assert!(!gone.body.contains("TagInUse"), "{}", gone.body); + assert_eq!(app.store.tags(&board.id).await.unwrap().len(), 1); +} + /// An open live stream must not be something the shutdown has to wait out. /// /// The server stops accepting connections and then gives in-flight requests diff --git a/style/main.scss b/style/main.scss index 48977dc..b785cc0 100644 --- a/style/main.scss +++ b/style/main.scss @@ -3134,7 +3134,11 @@ input[type="radio"] { } // Danger modifier for a `.quiet` button — the "Delete" action in a rule row. -.quiet-danger { +// Written `.quiet.quiet-danger` for the same reason the avatar sizes are: +// the skins style `.quiet` from a `[data-ui]` scope, which outweighs a lone +// modifier class — on the Ledger skin a delete button lost its red border, +// and its red text on hover, to a rule about ordinary quiet buttons. +.quiet.quiet-danger { border-color: var(--danger-border); color: var(--danger); @@ -3524,6 +3528,20 @@ input[type="radio"] { white-space: nowrap; } +// How many cards are on the project, in the same chip the board counts its +// columns with. It is also the reason the delete control beside it is or is +// not there. +.tag-count { + flex: none; + font-family: var(--font-mono); + font-size: 11px; + font-variant-numeric: tabular-nums; + color: var(--muted-soft); + background: var(--panel-sunken); + border-radius: var(--radius); + padding: 1px 6px; +} + .tag-new { background: var(--surface); border: 1px solid var(--border);