forge
Explore
Log in

Don't you dare go Hollow

A project with cards on it is not something you delete

Browse files at this commit

faea59ea60db7b81651ad1c8607e9700e88a7345Ahmet Kaan GümüşParent: 3019970
  • fix
    • a project with cards on it is not something you delete
Show full message
🐛 fix(tags): a project with cards on it is not something you delete

Deleting a tag moved every card on it to the default and took the tag away.
One click on a row with no confirmation behind it re-filed somebody's whole
project, and nothing on the screen said how much work was about to move.

A tag with live cards is refused now — `Conflict("tag_in_use")`, which the
page shows as "This tag still has cards" rather than "something went wrong"
— and its row ships no delete control, the same rule the default tag has
always had. The row carries the card count in the board's own count chip, so
a missing delete is a number the admin can already read instead of a control
that mysteriously is not there. Emptying the tag is what makes it deletable,
and that is a decision made one card at a time.

Cards already thrown away are the exception: a soft-deleted card is nobody's
work any more, it does not count, and its tag reference moves to the default
as the tag goes — so nothing is ever left pointing at a project that is not
there. `PRAGMA foreign_key_check` is part of the test that says so.

Two other things this hunt turned up, both the same defect class as the
avatar sizes — a skin rule in a `[data-ui]` scope outweighing a modifier
class on the same node:

`.quiet-danger` lost to `[data-ui=ledger] .quiet`, so on the Ledger skin a
delete button had no red border and lost its red text on hover. Written
`.quiet.quiet-danger` now.

And `hold_batch` could pull a mail *back*: a delivery pass writes its lease
into `next_attempt_at`, the same column the batch debounce postpones, so a
new trigger with a one-minute window could make a row a pass was already
composing due again — and the reader would get that mail twice. It only ever
postpones now, in the read and in the `UPDATE`'s own `WHERE`, with a test
that leases a row and then holds it.
crates/izlek-core/src/store/mod.rsmodified+15 -0
@@ -1088,6 +1088,11 @@ pub trait Store: BoardReads + DetailReads + 'static {
1088 /// Every tag on the board, in the admin's hand-set order.1088 /// Every tag on the board, in the admin's hand-set order.
1089 async fn tags(&self, board_id: &str) -> Result<Vec<Tag>>;1089 async fn tags(&self, board_id: &str) -> Result<Vec<Tag>>;
1090 1090
1091+ /// How many live cards wear each of the board's tags, keyed by tag id. A
1092+ /// tag nobody uses is absent rather than zero — the caller reads a
1093+ /// missing key as none, which is what a fresh tag is.
1094+ async fn tag_task_counts(&self, board_id: &str) -> Result<Vec<(String, u32)>>;
1095+
1091 /// Appends a tag at the end of the board's order. The name is unique per1096 /// Appends a tag at the end of the board's order. The name is unique per
1092 /// board: two tags with one name are one project spelled twice.1097 /// board: two tags with one name are one project spelled twice.
1093 async fn create_tag(&self, board_id: &str, name: &str, at: OffsetDateTime) -> Result<Tag>;1098 async fn create_tag(&self, board_id: &str, name: &str, at: OffsetDateTime) -> Result<Tag>;
@@ -1096,6 +1101,11 @@ pub trait Store: BoardReads + DetailReads + 'static {
1096 1101
1097 /// Deletes a tag. Its tasks move to the board's default tag; the default1102 /// Deletes a tag. Its tasks move to the board's default tag; the default
1098 /// itself is refused — it is where they would go.1103 /// itself is refused — it is where they would go.
1104+ /// Retires a tag. A tag with cards on it is refused with
1105+ /// [`StoreError::Conflict`] — the cards are the reason it exists, and
1106+ /// moving somebody's whole project onto the default because one menu item
1107+ /// was clicked is not a deletion the admin asked for. The default tag is
1108+ /// refused as well: it is where a card with no project of its own lives.
1099 async fn delete_tag(&self, tag_id: &str) -> Result<()>;1109 async fn delete_tag(&self, tag_id: &str) -> Result<()>;
1100 1110
1101 /// Swaps a tag with its neighbour in the order. A tag already at that end1111 /// 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 {
1322 /// settled. Only rows that are still pending and have never been1332 /// settled. Only rows that are still pending and have never been
1323 /// attempted move — a mail already refused is on its own retry clock, and1333 /// attempted move — a mail already refused is on its own retry clock, and
1324 /// a batch must not drag it back.1334 /// a batch must not drag it back.
1335+ ///
1336+ /// It only ever postpones. A delivery pass writes its lease into the same
1337+ /// column, so a hold that moved a row *earlier* would hand the mail a
1338+ /// second pass is composing to a third one, and the reader would get it
1339+ /// twice.
1325 async fn hold_batch(1340 async fn hold_batch(
1326 &self,1341 &self,
1327 task_id: &str,1342 task_id: &str,
crates/izlek-core/src/store/turso_store.rsmodified+51 -6
@@ -3733,7 +3733,7 @@ impl Store for TursoStore {
3733 // date-format trick rather than a calculation.3733 // date-format trick rather than a calculation.
3734 let mut rows = conn3734 let mut rows = conn
3735 .query(3735 .query(
3736- "SELECT id, claimed_at FROM mail_send \3736+ "SELECT id, claimed_at, next_attempt_at FROM mail_send \
3737 WHERE task_id = ?1 AND recipient = ?2 AND kind = 'rule' \3737 WHERE task_id = ?1 AND recipient = ?2 AND kind = 'rule' \
3738 AND state = 'pending' AND attempts = 0 \3738 AND state = 'pending' AND attempts = 0 \
3739 AND next_attempt_at IS NOT NULL",3739 AND next_attempt_at IS NOT NULL",
@@ -3745,15 +3745,25 @@ impl Store for TursoStore {
3745 while let Some(row) = rows.next().await.map_err(backend)? {3745 while let Some(row) = rows.next().await.map_err(backend)? {
3746 let id = text(&row, 0)?;3746 let id = text(&row, 0)?;
3747 let born = parse_stamp(&text(&row, 1)?)?;3747 let born = parse_stamp(&text(&row, 1)?)?;
3748- held.push((id, born));3748+ let due = parse_stamp(&text(&row, 2)?)?;
3749+ held.push((id, born, due));
3749 }3750 }
3750 drop(rows);3751 drop(rows);
3751- for (id, born) in held {3752+ for (id, born, due) in held {
3752 let ceiling = born + cap;3753 let ceiling = born + cap;
3753 let when = if until > ceiling { ceiling } else { until };3754 let when = if until > ceiling { ceiling } else { until };
3755+ // Only ever later. A row a delivery pass is holding — its lease is
3756+ // written in this same column — must not be pulled back under the
3757+ // pass that took it, or the mail it is composing right now becomes
3758+ // due for a second pass and goes out twice. The `<` in the update
3759+ // is the guard, not the read above it: the two are one statement.
3760+ if when <= due {
3761+ continue;
3762+ }
3754 conn.execute(3763 conn.execute(
3755 "UPDATE mail_send SET next_attempt_at = ?1 \3764 "UPDATE mail_send SET next_attempt_at = ?1 \
3756- WHERE id = ?2 AND state = 'pending' AND attempts = 0",3765+ WHERE id = ?2 AND state = 'pending' AND attempts = 0 \
3766+ AND next_attempt_at < ?1",
3757 params![stamp(when)?, id],3767 params![stamp(when)?, id],
3758 )3768 )
3759 .await3769 .await
@@ -3816,6 +3826,23 @@ impl Store for TursoStore {
3816 Ok(out)3826 Ok(out)
3817 }3827 }
3818 3828
3829+ async fn tag_task_counts(&self, board_id: &str) -> Result<Vec<(String, u32)>> {
3830+ let conn = self.conn.lock().await;
3831+ let mut rows = conn
3832+ .query(
3833+ "SELECT tag_id, COUNT(*) FROM task \
3834+ WHERE board_id = ?1 AND deleted_at IS NULL GROUP BY tag_id",
3835+ params![board_id],
3836+ )
3837+ .await
3838+ .map_err(backend)?;
3839+ let mut out = Vec::new();
3840+ while let Some(row) = rows.next().await.map_err(backend)? {
3841+ out.push((text(&row, 0)?, row.get::<i64>(1).map_err(backend)? as u32));
3842+ }
3843+ Ok(out)
3844+ }
3845+
3819 async fn create_tag(&self, board_id: &str, name: &str, at: OffsetDateTime) -> Result<Tag> {3846 async fn create_tag(&self, board_id: &str, name: &str, at: OffsetDateTime) -> Result<Tag> {
3820 let id = Ulid::new().to_string();3847 let id = Ulid::new().to_string();
3821 let now = stamp(at)?;3848 let now = stamp(at)?;
@@ -3903,8 +3930,12 @@ impl Store for TursoStore {
3903 .map_err(backend)?;3930 .map_err(backend)?;
3904 // The default is the board's fallback, not a project anyone can3931 // The default is the board's fallback, not a project anyone can
3905 // retire: deleting it would leave its board's tasks nowhere to go.3932 // retire: deleting it would leave its board's tasks nowhere to go.
3906- // Any other tag's tasks move to that default, in the one write set:3933+ // Any other tag is deletable only while it is empty — a tag with
3907- // no task is ever seen pointing at a project that is not there.3934+ // cards on it is a project somebody is working in, and a delete that
3935+ // quietly re-files that work is not a delete they asked for. Cards
3936+ // already thrown away are the exception: they are nobody's work any
3937+ // more, and they move to the default so the reference they still hold
3938+ // points at something.
3908 let deleted = async {3939 let deleted = async {
3909 let mut rows = tx3940 let mut rows = tx
3910 .query(3941 .query(
@@ -3921,6 +3952,20 @@ impl Store for TursoStore {
3921 if is_default != 0 {3952 if is_default != 0 {
3922 return Ok(Err(StoreError::Conflict("default_tag")));3953 return Ok(Err(StoreError::Conflict("default_tag")));
3923 }3954 }
3955+ let mut rows = tx
3956+ .query(
3957+ "SELECT COUNT(*) FROM task WHERE tag_id = ?1 AND deleted_at IS NULL",
3958+ params![tag_id],
3959+ )
3960+ .await?;
3961+ let live: i64 = match rows.next().await? {
3962+ Some(row) => row.get(0)?,
3963+ None => 0,
3964+ };
3965+ drop(rows);
3966+ if live > 0 {
3967+ return Ok(Err(StoreError::Conflict("tag_in_use")));
3968+ }
3924 tx.execute(3969 tx.execute(
3925 "UPDATE task SET tag_id = \3970 "UPDATE task SET tag_id = \
3926 (SELECT id FROM tag WHERE board_id = ?1 AND is_default = 1) \3971 (SELECT id FROM tag WHERE board_id = ?1 AND is_default = 1) \
crates/izlek-core/tests/store.rsmodified+138 -5
@@ -2905,7 +2905,7 @@ fn card_of<'a>(
2905 }2905 }
2906 2906
2907 #[tokio::test]2907 #[tokio::test]
2908-async fn deleting_a_tag_moves_its_tasks_to_the_default_and_a_foreign_tag_is_not_found() {2908+async fn a_tag_is_worn_a_foreign_one_is_not_found_and_a_worn_one_is_not_deletable() {
2909 let (scratch, workspace, admin) = workspace_with_admin().await;2909 let (scratch, workspace, admin) = workspace_with_admin().await;
2910 let store = &scratch.store;2910 let store = &scratch.store;
2911 let board = store.board(&workspace).await.unwrap().unwrap();2911 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_
2956 Err(StoreError::NotFound)2956 Err(StoreError::NotFound)
2957 ));2957 ));
2958 2958
2959- // Deleting a worn tag leaves the task on the board's default, and the2959+ // A tag with a card on it is not deletable: the card is the reason the
2960- // task survives.2960+ // project exists, and nothing about it moves.
2961- store.delete_tag(&tag.id).await.unwrap();2961+ assert!(matches!(
2962+ store.delete_tag(&tag.id).await,
2963+ Err(StoreError::Conflict("tag_in_use"))
2964+ ));
2962 let view = board_of(store, &workspace).await;2965 let view = board_of(store, &workspace).await;
2963 assert_eq!(2966 assert_eq!(
2964 card_of(&view, &task).tag.as_ref().map(|t| t.name.as_str()),2967 card_of(&view, &task).tag.as_ref().map(|t| t.name.as_str()),
2965- Some("General")2968+ Some("ops"),
2969+ "the refused delete moved the card anyway"
2966 );2970 );
2971+ assert_eq!(store.tags(&board.id).await.unwrap().len(), 2);
2972+
2973+ // Emptied, it goes.
2974+ let default = store
2975+ .tags(&board.id)
2976+ .await
2977+ .unwrap()
2978+ .into_iter()
2979+ .find(|t| t.is_default)
2980+ .unwrap();
2981+ store.set_task_tag(&task, &default.id).await.unwrap();
2982+ store.delete_tag(&tag.id).await.unwrap();
2983+ assert_eq!(store.tags(&board.id).await.unwrap().len(), 1);
2984+}
2985+
2986+/// The counts the tags screen draws, and the one card that stops counting.
2987+#[tokio::test]
2988+async fn tag_counts_hold_the_live_cards_and_a_thrown_away_card_stops_blocking() {
2989+ let (scratch, workspace, admin) = workspace_with_admin().await;
2990+ let store = &scratch.store;
2991+ let board = store.board(&workspace).await.unwrap().unwrap();
2992+ let tag = store
2993+ .create_tag(&board.id, "ops", OffsetDateTime::now_utc())
2994+ .await
2995+ .unwrap();
2996+ let first = add_task(store, &workspace, "Backlog", "one", None, &admin).await;
2997+ let second = add_task(store, &workspace, "Backlog", "two", None, &admin).await;
2998+ store.set_task_tag(&first, &tag.id).await.unwrap();
2999+ store.set_task_tag(&second, &tag.id).await.unwrap();
3000+
3001+ let counts = store.tag_task_counts(&board.id).await.unwrap();
3002+ assert_eq!(
3003+ counts.iter().find(|(id, _)| id == &tag.id).map(|(_, n)| *n),
3004+ Some(2)
3005+ );
3006+
3007+ // A card thrown away is nobody's work any more: it stops counting, and
3008+ // once the last live one is gone the tag can be retired — the deleted
3009+ // card's own reference moves to the default rather than dangling.
3010+ store
3011+ .delete_task(&first, &admin, OffsetDateTime::now_utc())
3012+ .await
3013+ .unwrap();
3014+ assert!(matches!(
3015+ store.delete_tag(&tag.id).await,
3016+ Err(StoreError::Conflict("tag_in_use")),
3017+ ));
3018+ store
3019+ .delete_task(&second, &admin, OffsetDateTime::now_utc())
3020+ .await
3021+ .unwrap();
3022+ assert_eq!(
3023+ store
3024+ .tag_task_counts(&board.id)
3025+ .await
3026+ .unwrap()
3027+ .iter()
3028+ .find(|(id, _)| id == &tag.id),
3029+ None,
3030+ "a tag nobody wears is absent, not zero"
3031+ );
3032+ store.delete_tag(&tag.id).await.unwrap();
3033+
3034+ // Nothing points at a tag that is not there.
3035+ let mut broken = raw_conn(&scratch)
3036+ .await
3037+ .query("PRAGMA foreign_key_check", ())
3038+ .await
3039+ .unwrap();
3040+ assert!(broken.next().await.unwrap().is_none());
2967 }3041 }
2968 3042
2969 #[tokio::test]3043 #[tokio::test]
@@ -7503,6 +7577,65 @@ async fn the_hold_has_a_ceiling_measured_from_the_oldest_mail() {
7503 let _ = std::fs::remove_dir_all(&dir);7577 let _ = std::fs::remove_dir_all(&dir);
7504 }7578 }
7505 7579
7580+/// A hold only ever postpones. The delivery pass writes its lease into the
7581+/// same column, so a hold that pulled a leased row back would make the mail
7582+/// one pass is composing due for another — and the reader would get it twice.
7583+#[tokio::test]
7584+async fn a_hold_never_pulls_a_leased_row_back_under_the_pass_that_took_it() {
7585+ let (dir, store, workspace, admin) = waiting(1).await;
7586+ let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await;
7587+ let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await;
7588+ store.assign_task(&task, &mate).await.unwrap();
7589+ let rule = a_rule(&store, &workspace, "Done", "Card is done").await;
7590+
7591+ let now = OffsetDateTime::now_utc();
7592+ store
7593+ .claim_send(&rule.id, "event-1", &task, "emre@izlek.sh", now, now)
7594+ .await
7595+ .unwrap()
7596+ .expect("a fresh row is claimed");
7597+ // A delivery pass takes it: the lease is five minutes out.
7598+ let taken = store
7599+ .claim_sends_owed(now + Duration::seconds(1), now + izlek_core::mail::LEASE, 10)
7600+ .await
7601+ .unwrap();
7602+ assert_eq!(taken.len(), 1, "the pass did not take the row");
7603+ let leased = the_one_row(&store).await.next_attempt_at.unwrap();
7604+
7605+ // A new trigger on the same card, one quiet minute out: earlier than the
7606+ // lease, so it must change nothing.
7607+ store
7608+ .hold_batch(
7609+ &task,
7610+ "emre@izlek.sh",
7611+ now + Duration::minutes(1),
7612+ Duration::minutes(4),
7613+ )
7614+ .await
7615+ .unwrap();
7616+ assert_eq!(
7617+ the_one_row(&store).await.next_attempt_at.unwrap(),
7618+ leased,
7619+ "the hold pulled a row out from under the pass holding it"
7620+ );
7621+
7622+ // A hold past the lease is a postponement, and does apply.
7623+ store
7624+ .hold_batch(
7625+ &task,
7626+ "emre@izlek.sh",
7627+ now + Duration::minutes(30),
7628+ Duration::hours(2),
7629+ )
7630+ .await
7631+ .unwrap();
7632+ assert!(
7633+ the_one_row(&store).await.next_attempt_at.unwrap() > leased,
7634+ "a real postponement was refused too"
7635+ );
7636+ let _ = std::fs::remove_dir_all(&dir);
7637+}
7638+
7506 /// A workspace with no window is İzlek as it was: a trigger is a mail, sent7639 /// A workspace with no window is İzlek as it was: a trigger is a mail, sent
7507 /// the moment it is owed.7640 /// the moment it is owed.
7508 #[tokio::test]7641 #[tokio::test]
crates/izlek-web/src/server.rsmodified+8 -0
@@ -359,6 +359,9 @@ pub enum Refusal {
359 EmptySubject,359 EmptySubject,
360 /// A tag with no name is not a tag the board can show.360 /// A tag with no name is not a tag the board can show.
361 EmptyTag,361 EmptyTag,
362+ /// A tag with cards on it stays. Emptying it is the admin's job, and it
363+ /// is one they can see the size of.
364+ TagInUse,
362 /// A message with no body: there is nothing for the recipient to read.365 /// A message with no body: there is nothing for the recipient to read.
363 EmptyBody,366 EmptyBody,
364 /// The date field did not hold a date.367 /// The date field did not hold a date.
@@ -422,6 +425,7 @@ impl Refusal {
422 Refusal::NotAnImage => "That is not an image.".to_string(),425 Refusal::NotAnImage => "That is not an image.".to_string(),
423 Refusal::EmptySubject => "Give the rule a subject line.".to_string(),426 Refusal::EmptySubject => "Give the rule a subject line.".to_string(),
424 Refusal::EmptyTag => "Give the tag a name.".to_string(),427 Refusal::EmptyTag => "Give the tag a name.".to_string(),
428+ Refusal::TagInUse => "This tag still has cards.".to_string(),
425 Refusal::EmptyBody => "Write something first.".to_string(),429 Refusal::EmptyBody => "Write something first.".to_string(),
426 Refusal::BadDeadline => "That is not a date.".to_string(),430 Refusal::BadDeadline => "That is not a date.".to_string(),
427 Refusal::Cycle => "That link would put this task behind itself.".to_string(),431 Refusal::Cycle => "That link would put this task behind itself.".to_string(),
@@ -481,6 +485,7 @@ impl Refusal {
481 Refusal::BadSender(_) => self.message(),485 Refusal::BadSender(_) => self.message(),
482 Refusal::EmptySubject => "Kurala bir konu ver.".to_string(),486 Refusal::EmptySubject => "Kurala bir konu ver.".to_string(),
483 Refusal::EmptyTag => "Etikete bir ad ver.".to_string(),487 Refusal::EmptyTag => "Etikete bir ad ver.".to_string(),
488+ Refusal::TagInUse => "Bu etikette kartlar var.".to_string(),
484 Refusal::EmptyBody => "Önce bir şey yaz.".to_string(),489 Refusal::EmptyBody => "Önce bir şey yaz.".to_string(),
485 Refusal::Rejected => "Bu işe yaramadı.".to_string(),490 Refusal::Rejected => "Bu işe yaramadı.".to_string(),
486 Refusal::RateLimited => {491 Refusal::RateLimited => {
@@ -531,6 +536,7 @@ impl Refusal {
531 "not-an-image" => Refusal::NotAnImage,536 "not-an-image" => Refusal::NotAnImage,
532 "empty-subject" => Refusal::EmptySubject,537 "empty-subject" => Refusal::EmptySubject,
533 "empty-tag" => Refusal::EmptyTag,538 "empty-tag" => Refusal::EmptyTag,
539+ "tag-in-use" => Refusal::TagInUse,
534 "empty-body" => Refusal::EmptyBody,540 "empty-body" => Refusal::EmptyBody,
535 "bad-deadline" => Refusal::BadDeadline,541 "bad-deadline" => Refusal::BadDeadline,
536 "cycle" => Refusal::Cycle,542 "cycle" => Refusal::Cycle,
@@ -587,6 +593,7 @@ impl Refusal {
587 Refusal::NotAnImage => "not-an-image",593 Refusal::NotAnImage => "not-an-image",
588 Refusal::EmptySubject => "empty-subject",594 Refusal::EmptySubject => "empty-subject",
589 Refusal::EmptyTag => "empty-tag",595 Refusal::EmptyTag => "empty-tag",
596+ Refusal::TagInUse => "tag-in-use",
590 Refusal::EmptyBody => "empty-body",597 Refusal::EmptyBody => "empty-body",
591 Refusal::BadDeadline => "bad-deadline",598 Refusal::BadDeadline => "bad-deadline",
592 Refusal::Cycle => "cycle",599 Refusal::Cycle => "cycle",
@@ -874,6 +881,7 @@ mod refusal_message_tests {
874 Refusal::NotNestable,881 Refusal::NotNestable,
875 Refusal::NotFound,882 Refusal::NotFound,
876 Refusal::NoSuchMember,883 Refusal::NoSuchMember,
884+ Refusal::TagInUse,
877 Refusal::Unavailable,885 Refusal::Unavailable,
878 ];886 ];
879 for refusal in all {887 for refusal in all {
crates/izlek-web/src/tags.rsmodified+29 -9
@@ -39,6 +39,9 @@ struct TagLine {
39 name: String,39 name: String,
40 position: i64,40 position: i64,
41 is_default: bool,41 is_default: bool,
42+ /// Cards wearing this tag. A tag with any is not deletable, and the row
43+ /// says how many rather than leaving the admin to guess why.
44+ tasks: u32,
42 }45 }
43 46
44 /// Every tag on the workspace's own board, in the admin's hand-set order.47 /// Every tag on the workspace's own board, in the admin's hand-set order.
@@ -53,12 +56,21 @@ async fn tags_of(
53 else {56 else {
54 return Err(Refusal::Unavailable);57 return Err(Refusal::Unavailable);
55 };58 };
59+ let counts = store
60+ .tag_task_counts(&board.id)
61+ .await
62+ .map_err(|_| Refusal::Unavailable)?;
56 Ok(store63 Ok(store
57 .tags(&board.id)64 .tags(&board.id)
58 .await65 .await
59 .map_err(|_| Refusal::Unavailable)?66 .map_err(|_| Refusal::Unavailable)?
60 .into_iter()67 .into_iter()
61 .map(|tag| TagLine {68 .map(|tag| TagLine {
69+ tasks: counts
70+ .iter()
71+ .find(|(id, _)| id == &tag.id)
72+ .map(|(_, count)| *count)
73+ .unwrap_or(0),
62 id: tag.id,74 id: tag.id,
63 name: tag.name,75 name: tag.name,
64 position: tag.position,76 position: tag.position,
@@ -179,19 +191,24 @@ struct DeleteTagForm {
179 tag_id: String,191 tag_id: String,
180 }192 }
181 193
182-/// Removes a tag. The store refuses to delete the default — every task194+/// Removes a tag. The store refuses two of them: the default — every task
183-/// without a tag wears it — and that refusal lands here as "unavailable";195+/// without a project of its own wears it — and any tag that still has cards,
184-/// the row itself ships no delete control in the first place.196+/// which comes back named so the admin reads why rather than "something went
197+/// wrong". Neither row ships a delete control in the first place; this is
198+/// the same rule where it is actually enforced.
185 #[route(POST "/api/delete_tag")]199 #[route(POST "/api/delete_tag")]
186 async fn delete_tag(cx: &Cx, Form(input): Form<DeleteTagForm>) -> Redirect {200 async fn delete_tag(cx: &Cx, Form(input): Form<DeleteTagForm>) -> Redirect {
187 let (store, _, _) = match tag_of_this_workspace(cx, &input.tag_id).await {201 let (store, _, _) = match tag_of_this_workspace(cx, &input.tag_id).await {
188 Ok(triple) => triple,202 Ok(triple) => triple,
189 Err(refusal) => return redirect(cx, Some(refusal)),203 Err(refusal) => return redirect(cx, Some(refusal)),
190 };204 };
191- if store.delete_tag(&input.tag_id).await.is_err() {205+ match store.delete_tag(&input.tag_id).await {
192- return redirect(cx, Some(Refusal::Unavailable));206+ Ok(()) => redirect(cx, None),
207+ Err(izlek_core::store::StoreError::Conflict("tag_in_use")) => {
208+ redirect(cx, Some(Refusal::TagInUse))
209+ }
210+ Err(_) => redirect(cx, Some(Refusal::Unavailable)),
193 }211 }
194- redirect(cx, None)
195 }212 }
196 213
197 #[derive(Deserialize)]214 #[derive(Deserialize)]
@@ -251,8 +268,10 @@ async fn composer(cx: &Cx, refusal: Option<&Refusal>, lang: Lang) -> Result {
251 }268 }
252 269
253 /// One tag's row: the rename form in place of it when `editing`, its display270 /// One tag's row: the rename form in place of it when `editing`, its display
254-/// otherwise. The default tag draws no delete form — the store would refuse271+/// otherwise. The default tag draws no delete form, and neither does a tag
255-/// it, and a control that cannot act is not drawn.272+/// with cards on it — the store would refuse both, and a control that cannot
273+/// act is not drawn. The card count sits on the row, so a missing delete is
274+/// a number the admin can already see rather than a control that vanished.
256 async fn tag_row(cx: &Cx, tag: &TagLine, editing: bool, refusal: Option<&Refusal>, lang: Lang) -> Result {275 async fn tag_row(cx: &Cx, tag: &TagLine, editing: bool, refusal: Option<&Refusal>, lang: Lang) -> Result {
257 if editing {276 if editing {
258 return view! {277 return view! {
@@ -280,6 +299,7 @@ async fn tag_row(cx: &Cx, tag: &TagLine, editing: bool, refusal: Option<&Refusal
280 cx =>299 cx =>
281 <div class="tag-row">300 <div class="tag-row">
282 <span class="tag-name">(tag.name.clone())</span>301 <span class="tag-name">(tag.name.clone())</span>
302+ <span class="tag-count">(tag.tasks)</span>
283 303
284 <a class="quiet" href=(format!("/tags?edit={}", tag.id)) title=(t(lang, Key::EditThisTag))>(t(lang, Key::EditLabel))</a>304 <a class="quiet" href=(format!("/tags?edit={}", tag.id)) title=(t(lang, Key::EditThisTag))>(t(lang, Key::EditLabel))</a>
285 305
@@ -294,7 +314,7 @@ async fn tag_row(cx: &Cx, tag: &TagLine, editing: bool, refusal: Option<&Refusal
294 <button class="quiet" type="submit" title=(t(lang, Key::MoveTagDown)) aria-label=(t(lang, Key::MoveTagDown))>("\u{2193}")</button>314 <button class="quiet" type="submit" title=(t(lang, Key::MoveTagDown)) aria-label=(t(lang, Key::MoveTagDown))>("\u{2193}")</button>
295 </form>315 </form>
296 316
297- if !tag.is_default {317+ if !tag.is_default && tag.tasks == 0 {
298 <form method="post" action="/api/delete_tag">318 <form method="post" action="/api/delete_tag">
299 <input type="hidden" name="tag_id" value=(tag.id.clone())>319 <input type="hidden" name="tag_id" value=(tag.id.clone())>
300 <button class="quiet quiet-danger" type="submit" title=(t(lang, Key::DeleteThisTag))>(t(lang, Key::Delete))</button>320 <button class="quiet quiet-danger" type="submit" title=(t(lang, Key::DeleteThisTag))>(t(lang, Key::Delete))</button>
crates/izlek-web/tests/http.rsmodified+68 -0
@@ -7525,6 +7525,74 @@ async fn the_default_tag_cannot_be_deleted_and_ships_no_delete_button() {
7525 assert!(page.contains("Aurora"), "the created tag is not listed: {page}");7525 assert!(page.contains("Aurora"), "the created tag is not listed: {page}");
7526 }7526 }
7527 7527
7528+/// A tag with cards on it stays: no delete control on its row, and the call
7529+/// itself refused by name if somebody posts it anyway. Emptying it is what
7530+/// makes it deletable.
7531+#[tokio::test]
7532+async fn a_tag_with_cards_on_it_cannot_be_deleted() {
7533+ let app = App::open().await;
7534+ let admin_cookie = admin(&app).await;
7535+ let aurora = a_tag(&app, &admin_cookie, "Aurora").await;
7536+ let workspace_id = app.workspace_id().await;
7537+ let board = app.store.board(&workspace_id).await.unwrap().expect("no board");
7538+ let open = app.store.columns(&board.id).await.unwrap()[0].id.clone();
7539+ let admin_id = app
7540+ .store
7541+ .users(&workspace_id)
7542+ .await
7543+ .unwrap()
7544+ .into_iter()
7545+ .find(|user| user.role == Role::Admin)
7546+ .unwrap()
7547+ .id;
7548+ let task = a_task_by(&app, &board.id, &open, "Hold the door", &admin_id).await;
7549+ app.store.set_task_tag(&task, &aurora.id).await.unwrap();
7550+
7551+ let page = String::from_utf8(app.get("/tags", Some(&admin_cookie)).await.bytes).unwrap();
7552+ assert_eq!(
7553+ page.matches(r#"action="/api/delete_tag""#).count(),
7554+ 0,
7555+ "a tag with a card on it still offers a delete: {page}"
7556+ );
7557+ assert!(
7558+ page.contains(r#"<span class="tag-count">1</span>"#),
7559+ "the row does not say how many cards are on it: {page}"
7560+ );
7561+
7562+ let refused = app
7563+ .post("/api/delete_tag", Some(&admin_cookie), &[("tag_id", &aurora.id)])
7564+ .await;
7565+ assert!(
7566+ refused.body.contains("TagInUse"),
7567+ "the refusal does not name itself: {}",
7568+ refused.body
7569+ );
7570+ assert_eq!(
7571+ app.store.tags(&board.id).await.unwrap().len(),
7572+ 2,
7573+ "the tag went anyway"
7574+ );
7575+
7576+ // Moved off it, the tag is deletable again — control and call both.
7577+ let default_id = app
7578+ .store
7579+ .tags(&board.id)
7580+ .await
7581+ .unwrap()
7582+ .into_iter()
7583+ .find(|tag| tag.is_default)
7584+ .unwrap()
7585+ .id;
7586+ app.store.set_task_tag(&task, &default_id).await.unwrap();
7587+ let page = String::from_utf8(app.get("/tags", Some(&admin_cookie)).await.bytes).unwrap();
7588+ assert_eq!(page.matches(r#"action="/api/delete_tag""#).count(), 1);
7589+ let gone = app
7590+ .post("/api/delete_tag", Some(&admin_cookie), &[("tag_id", &aurora.id)])
7591+ .await;
7592+ assert!(!gone.body.contains("TagInUse"), "{}", gone.body);
7593+ assert_eq!(app.store.tags(&board.id).await.unwrap().len(), 1);
7594+}
7595+
7528 /// An open live stream must not be something the shutdown has to wait out.7596 /// An open live stream must not be something the shutdown has to wait out.
7529 ///7597 ///
7530 /// The server stops accepting connections and then gives in-flight requests7598 /// The server stops accepting connections and then gives in-flight requests
style/main.scssmodified+19 -1
@@ -3134,7 +3134,11 @@ input[type="radio"] {
3134 }3134 }
3135 3135
3136 // Danger modifier for a `.quiet` button — the "Delete" action in a rule row.3136 // Danger modifier for a `.quiet` button — the "Delete" action in a rule row.
3137-.quiet-danger {3137+// Written `.quiet.quiet-danger` for the same reason the avatar sizes are:
3138+// the skins style `.quiet` from a `[data-ui]` scope, which outweighs a lone
3139+// modifier class — on the Ledger skin a delete button lost its red border,
3140+// and its red text on hover, to a rule about ordinary quiet buttons.
3141+.quiet.quiet-danger {
3138 border-color: var(--danger-border);3142 border-color: var(--danger-border);
3139 color: var(--danger);3143 color: var(--danger);
3140 3144
@@ -3524,6 +3528,20 @@ input[type="radio"] {
3524 white-space: nowrap;3528 white-space: nowrap;
3525 }3529 }
3526 3530
3531+// How many cards are on the project, in the same chip the board counts its
3532+// columns with. It is also the reason the delete control beside it is or is
3533+// not there.
3534+.tag-count {
3535+ flex: none;
3536+ font-family: var(--font-mono);
3537+ font-size: 11px;
3538+ font-variant-numeric: tabular-nums;
3539+ color: var(--muted-soft);
3540+ background: var(--panel-sunken);
3541+ border-radius: var(--radius);
3542+ padding: 1px 6px;
3543+}
3544+
3527 .tag-new {3545 .tag-new {
3528 background: var(--surface);3546 background: var(--surface);
3529 border: 1px solid var(--border);3547 border: 1px solid var(--border);