diff --git a/crates/izlek-core/src/store/mod.rs b/crates/izlek-core/src/store/mod.rs index ce50956..a564d88 100644 --- a/crates/izlek-core/src/store/mod.rs +++ b/crates/izlek-core/src/store/mod.rs @@ -983,6 +983,15 @@ pub trait Store: BoardReads + DetailReads + 'static { /// Every send a rule has made, newest first, for the admin's trail. async fn sends_for_rule(&self, rule_id: &str, limit: u32) -> Result>; + /// Every send this task's events have caused, newest first, for the task + /// detail's notifications block. + async fn sends_for_task(&self, task_id: &str, limit: u32) -> Result>; + + /// Puts a failed or abandoned send back in play: pending, due at `at`. + /// `attempts` is left alone — this is a new try, not a rewrite of the + /// ones already spent. A send that already went out is untouched. + async fn requeue_send(&self, send_id: &str, at: OffsetDateTime) -> Result<()>; + // -- mail decisions and observability ----------------------------------- /// Records what a rule decided about one event and task. Idempotent: a @@ -1002,6 +1011,10 @@ pub trait Store: BoardReads + DetailReads + 'static { /// The most recent decisions across every rule, newest first. async fn recent_mail_decisions(&self, limit: u32, page: FeedPage) -> Result>; + /// Every decision written about one task, newest first, for its + /// notifications block. + async fn decisions_for_task(&self, task_id: &str, limit: u32) -> Result>; + /// When each rule last decided anything, for the "last checked" line. async fn mail_rule_last_decision(&self) -> Result>; diff --git a/crates/izlek-core/src/store/turso_store.rs b/crates/izlek-core/src/store/turso_store.rs index a58f1d1..c8a6ebe 100644 --- a/crates/izlek-core/src/store/turso_store.rs +++ b/crates/izlek-core/src/store/turso_store.rs @@ -2694,6 +2694,36 @@ impl Store for TursoStore { Ok(out) } + async fn sends_for_task(&self, task_id: &str, limit: u32) -> Result> { + let conn = self.conn.lock().await; + let sql = format!( + "SELECT {SEND_COLUMNS} FROM mail_send WHERE task_id = ?1 \ + ORDER BY claimed_at DESC, rowid DESC LIMIT ?2" + ); + let mut rows = conn + .query(&sql, params![task_id, i64::from(limit)]) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(send_from(&row)?); + } + Ok(out) + } + + async fn requeue_send(&self, send_id: &str, at: OffsetDateTime) -> Result<()> { + let conn = self.conn.lock().await; + conn + .execute( + "UPDATE mail_send SET state = 'pending', next_attempt_at = ?1 \ + WHERE id = ?2 AND state IN ('failed', 'abandoned')", + params![stamp(at)?, send_id], + ) + .await + .map_err(backend)?; + Ok(()) + } + // -- mail decisions and observability ----------------------------------- async fn record_mail_decision( @@ -2767,6 +2797,23 @@ impl Store for TursoStore { Ok(out) } + async fn decisions_for_task(&self, task_id: &str, limit: u32) -> Result> { + let conn = self.conn.lock().await; + let sql = format!( + "SELECT {DECISION_COLUMNS} FROM mail_decision WHERE task_id = ?1 \ + ORDER BY created_at DESC, id DESC LIMIT ?2" + ); + let mut rows = conn + .query(&sql, params![task_id, i64::from(limit)]) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(decision_from(&row)?); + } + Ok(out) + } + async fn count_mail_decisions(&self) -> Result { let row = self .one_row("SELECT COUNT(*) FROM mail_decision", ()) diff --git a/crates/izlek-core/tests/store.rs b/crates/izlek-core/tests/store.rs index 04627ff..5511105 100644 --- a/crates/izlek-core/tests/store.rs +++ b/crates/izlek-core/tests/store.rs @@ -5098,3 +5098,91 @@ async fn a_created_activity_does_not_fire_a_status_rule() { assert!(!row.detail.is_empty(), "the reason is not left blank"); let _ = std::fs::remove_dir_all(&dir); } + +#[tokio::test] +async fn decisions_and_sends_for_task_read_only_that_tasks_own_rows() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let task = add_task(store, &workspace, "Backlog", "Ship it", None, &admin).await; + let other_task = add_task(store, &workspace, "Backlog", "Something else", None, &admin).await; + let rule = a_rule(store, &workspace, "Done", "Task completed").await; + let transition = moved_to(store, &workspace, &task, "Backlog", "Done", &admin).await; + let other_transition = + moved_to(store, &workspace, &other_task, "Backlog", "Done", &admin).await; + let now = OffsetDateTime::now_utc(); + + store + .record_mail_decision(&rule.id, &transition.id, &task, MailOutcome::Owed, "", now) + .await + .unwrap(); + store + .record_mail_decision( + &rule.id, + &other_transition.id, + &other_task, + MailOutcome::Owed, + "", + now, + ) + .await + .unwrap(); + let send = store + .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now) + .await + .unwrap() + .unwrap(); + store + .claim_send(&rule.id, &other_transition.id, &other_task, "emre@izlek.sh", now) + .await + .unwrap(); + + let decisions = store.decisions_for_task(&task, 10).await.unwrap(); + assert_eq!(decisions.len(), 1); + assert_eq!(decisions[0].task_id, task); + + let sends = store.sends_for_task(&task, 10).await.unwrap(); + assert_eq!(sends.len(), 1); + assert_eq!(sends[0].id, send.id); + assert_eq!(sends[0].task_id.as_deref(), Some(task.as_str())); +} + +#[tokio::test] +async fn requeuing_a_send_puts_it_back_in_play_but_leaves_a_sent_one_alone() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let task = add_task(store, &workspace, "Backlog", "Ship it", None, &admin).await; + let rule = a_rule(store, &workspace, "Done", "Task completed").await; + let transition = moved_to(store, &workspace, &task, "Backlog", "Done", &admin).await; + let now = OffsetDateTime::now_utc(); + + let failed = store + .claim_send(&rule.id, &transition.id, &task, "failed@izlek.sh", now) + .await + .unwrap() + .unwrap(); + store + .record_send_refused(&failed.id, "timeout", None, now) + .await + .unwrap(); + + let sent = store + .claim_send(&rule.id, &transition.id, &task, "sent@izlek.sh", now) + .await + .unwrap() + .unwrap(); + store.record_send_accepted(&sent.id, now).await.unwrap(); + + store.requeue_send(&failed.id, now).await.unwrap(); + store.requeue_send(&sent.id, now).await.unwrap(); + + let sends = store.sends_for_task(&task, 10).await.unwrap(); + let reread_failed = sends.iter().find(|s| s.id == failed.id).unwrap(); + assert_eq!(reread_failed.state, SendState::Pending); + assert!(reread_failed.next_attempt_at.is_some_and(|at| at <= now)); + + let reread_sent = sends.iter().find(|s| s.id == sent.id).unwrap(); + assert_eq!(reread_sent.state, SendState::Sent, "a sent send is untouched"); + + let owed = store.sends_owed(now, 10).await.unwrap(); + assert!(owed.iter().any(|s| s.id == failed.id), "the requeued send is now due"); +} diff --git a/crates/izlek-web/src/detail.rs b/crates/izlek-web/src/detail.rs index 2eed4de..b40a584 100644 --- a/crates/izlek-web/src/detail.rs +++ b/crates/izlek-web/src/detail.rs @@ -82,6 +82,34 @@ pub struct DetailSnapshot { pub may_delete: bool, pub allowed_file_types: Vec, pub attachment_limit_mb: u64, + pub notifications: Vec, + pub may_administer: bool, +} + +/// One send's fate, joined to the sends of its decision's event. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SendLine { + pub recipient: String, + pub state: String, + /// The chip's tone — see `logs.rs`'s `QueueLine::state_kind`. + pub state_kind: String, + pub attempts: u32, + pub last_error: Option, + pub sent_at: Option, +} + +/// One decision the task's rules made about one event, with what happened to +/// any mail it owed. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct NotificationLine { + /// What caused it — "moved to Done" — absent when the event is gone. + pub happened: Option, + pub at: String, + /// Shown only to an admin. + pub rule_name: Option, + pub outcome: String, + pub outcome_kind: String, + pub sends: Vec, } /// Which way round a dependency runs, as it travels in a form. @@ -269,6 +297,70 @@ async fn load_snapshot( } let may_write = user.role.can_write_tasks(); + let may_administer = user.role.can_administer(); + let lang = Lang::from_code(&user.language); + let zone = parse_zone(&user.timezone); + + let decisions = store.decisions_for_task(&detail.id, 10).await?; + let sends = store.sends_for_task(&detail.id, 50).await?; + let mut columns_cache: std::collections::HashMap> = + std::collections::HashMap::new(); + let mut notifications = Vec::with_capacity(decisions.len()); + for decision in decisions { + let rule = store.mail_rule(&decision.rule_id).await?; + let rule_name = may_administer.then(|| { + rule.as_ref() + .map(|rule| rule.subject.clone()) + .unwrap_or_else(|| t(lang, Key::RuleGone).to_string()) + }); + let outcome_detail = crate::logs::decision_detail( + &store, + &mut columns_cache, + rule.as_ref().map(|rule| rule.board_id.as_str()), + decision.outcome, + &decision.detail, + lang, + ) + .await?; + let happened = crate::logs::event_happened(&store, &decision.event_id, lang).await?; + let matching: Vec = sends + .iter() + .filter(|s| s.event_id.as_deref() == Some(decision.event_id.as_str())) + .map(|send| { + use izlek_core::store::SendState; + let (state, state_kind) = match send.state { + SendState::Pending => (t(lang, Key::QueueStatePending), "pending"), + SendState::Failed if send.attempts == 0 => { + (t(lang, Key::QueueStateHeld), "held") + } + SendState::Failed => (t(lang, Key::QueueStateFailed), "failed"), + SendState::Sent => (t(lang, Key::QueueStateSent), "sent"), + SendState::Abandoned => (t(lang, Key::QueueStateAbandoned), "abandoned"), + }; + SendLine { + recipient: send.recipient.clone(), + state: state.to_string(), + state_kind: state_kind.to_string(), + attempts: send.attempts, + last_error: send.last_error.clone(), + sent_at: send.sent_at.map(|at| moment_label_in(at, zone)), + } + }) + .collect(); + let outcome = crate::logs::outcome_word(decision.outcome, lang).to_string(); + notifications.push(NotificationLine { + happened, + at: moment_label_in(decision.at, zone), + rule_name, + outcome: if outcome_detail.is_empty() { + outcome + } else { + format!("{outcome} · {outcome_detail}") + }, + outcome_kind: decision.outcome.as_str().to_string(), + sends: matching, + }); + } const MB: u64 = 1024 * 1024; let workspace = store.workspace().await?; @@ -288,6 +380,8 @@ async fn load_snapshot( may_delete: may_write, allowed_file_types, attachment_limit_mb, + notifications, + may_administer, me: Me::from(&user), today: OffsetDateTime::now_utc().date(), zone: parse_zone(&user.timezone), @@ -1268,6 +1362,8 @@ pub async fn task_modal(cx: &Cx, task_id: &str, confirm_delete: bool) -> Result may_delete, allowed_file_types, attachment_limit_mb: _, + notifications, + may_administer: _, } = snapshot; let lang = Lang::from_code(&me.language); @@ -1447,6 +1543,49 @@ pub async fn task_modal(cx: &Cx, task_id: &str, confirm_delete: bool) -> Result +
+ (t(lang, Key::Notifications)) +
+ for line in ¬ifications { +
+ (line.at.clone()) + if let Some(rule_name) = &line.rule_name { + (rule_name.clone()) + } + + (line.happened.clone().unwrap_or_else(|| t(lang, Key::TaskGoneLabel).to_string())) + // The outcome word only speaks when no mail was owed: once a + // send exists its own state is the truth, and printing both + // reads as a contradiction ("queued" beside a mail long sent). + if line.sends.is_empty() { + " — " + (line.outcome.clone()) + } + + if !line.sends.is_empty() { + + for send in &line.sends { + (send.recipient.clone()) + + (if send.state_kind == "failed" || send.state_kind == "abandoned" { + send.last_error.clone().unwrap_or_else(|| send.state.clone()) + } else if send.state_kind == "sent" { + format!("{} {}", send.state, send.sent_at.clone().unwrap_or_default()) + } else { + send.state.clone() + }) + + } + + } +
+ } + if notifications.is_empty() { +

(t(lang, Key::NothingYet))

+ } +
+
+ (refused(cx, "delete_task", lang).await?)