forge
Explore
Log in

Don't you dare go Hollow

The task says whether the mail left, and the queue can try again

Browse files at this commit

751237dacc6771f539cb37a1ec5ad090d96a79d9Ahmet Kaan GümüşParent: ce0b3d8
  • feat
    • the task says whether the mail left, and the queue can try again
Show full message
✨ feat(web): the task says whether the mail left, and the queue can try again
crates/izlek-core/src/store/mod.rsmodified+13 -0
@@ -983,6 +983,15 @@ pub trait Store: BoardReads + DetailReads + 'static {
983 /// Every send a rule has made, newest first, for the admin's trail.983 /// Every send a rule has made, newest first, for the admin's trail.
984 async fn sends_for_rule(&self, rule_id: &str, limit: u32) -> Result<Vec<MailSend>>;984 async fn sends_for_rule(&self, rule_id: &str, limit: u32) -> Result<Vec<MailSend>>;
985 985
986+ /// Every send this task's events have caused, newest first, for the task
987+ /// detail's notifications block.
988+ async fn sends_for_task(&self, task_id: &str, limit: u32) -> Result<Vec<MailSend>>;
989+
990+ /// Puts a failed or abandoned send back in play: pending, due at `at`.
991+ /// `attempts` is left alone — this is a new try, not a rewrite of the
992+ /// ones already spent. A send that already went out is untouched.
993+ async fn requeue_send(&self, send_id: &str, at: OffsetDateTime) -> Result<()>;
994+
986 // -- mail decisions and observability -----------------------------------995 // -- mail decisions and observability -----------------------------------
987 996
988 /// Records what a rule decided about one event and task. Idempotent: a997 /// Records what a rule decided about one event and task. Idempotent: a
@@ -1002,6 +1011,10 @@ pub trait Store: BoardReads + DetailReads + 'static {
1002 /// The most recent decisions across every rule, newest first.1011 /// The most recent decisions across every rule, newest first.
1003 async fn recent_mail_decisions(&self, limit: u32, page: FeedPage) -> Result<Vec<MailDecision>>;1012 async fn recent_mail_decisions(&self, limit: u32, page: FeedPage) -> Result<Vec<MailDecision>>;
1004 1013
1014+ /// Every decision written about one task, newest first, for its
1015+ /// notifications block.
1016+ async fn decisions_for_task(&self, task_id: &str, limit: u32) -> Result<Vec<MailDecision>>;
1017+
1005 /// When each rule last decided anything, for the "last checked" line.1018 /// When each rule last decided anything, for the "last checked" line.
1006 async fn mail_rule_last_decision(&self) -> Result<Vec<(String, OffsetDateTime)>>;1019 async fn mail_rule_last_decision(&self) -> Result<Vec<(String, OffsetDateTime)>>;
1007 1020
crates/izlek-core/src/store/turso_store.rsmodified+47 -0
@@ -2694,6 +2694,36 @@ impl Store for TursoStore {
2694 Ok(out)2694 Ok(out)
2695 }2695 }
2696 2696
2697+ async fn sends_for_task(&self, task_id: &str, limit: u32) -> Result<Vec<MailSend>> {
2698+ let conn = self.conn.lock().await;
2699+ let sql = format!(
2700+ "SELECT {SEND_COLUMNS} FROM mail_send WHERE task_id = ?1 \
2701+ ORDER BY claimed_at DESC, rowid DESC LIMIT ?2"
2702+ );
2703+ let mut rows = conn
2704+ .query(&sql, params![task_id, i64::from(limit)])
2705+ .await
2706+ .map_err(backend)?;
2707+ let mut out = Vec::new();
2708+ while let Some(row) = rows.next().await.map_err(backend)? {
2709+ out.push(send_from(&row)?);
2710+ }
2711+ Ok(out)
2712+ }
2713+
2714+ async fn requeue_send(&self, send_id: &str, at: OffsetDateTime) -> Result<()> {
2715+ let conn = self.conn.lock().await;
2716+ conn
2717+ .execute(
2718+ "UPDATE mail_send SET state = 'pending', next_attempt_at = ?1 \
2719+ WHERE id = ?2 AND state IN ('failed', 'abandoned')",
2720+ params![stamp(at)?, send_id],
2721+ )
2722+ .await
2723+ .map_err(backend)?;
2724+ Ok(())
2725+ }
2726+
2697 // -- mail decisions and observability -----------------------------------2727 // -- mail decisions and observability -----------------------------------
2698 2728
2699 async fn record_mail_decision(2729 async fn record_mail_decision(
@@ -2767,6 +2797,23 @@ impl Store for TursoStore {
2767 Ok(out)2797 Ok(out)
2768 }2798 }
2769 2799
2800+ async fn decisions_for_task(&self, task_id: &str, limit: u32) -> Result<Vec<MailDecision>> {
2801+ let conn = self.conn.lock().await;
2802+ let sql = format!(
2803+ "SELECT {DECISION_COLUMNS} FROM mail_decision WHERE task_id = ?1 \
2804+ ORDER BY created_at DESC, id DESC LIMIT ?2"
2805+ );
2806+ let mut rows = conn
2807+ .query(&sql, params![task_id, i64::from(limit)])
2808+ .await
2809+ .map_err(backend)?;
2810+ let mut out = Vec::new();
2811+ while let Some(row) = rows.next().await.map_err(backend)? {
2812+ out.push(decision_from(&row)?);
2813+ }
2814+ Ok(out)
2815+ }
2816+
2770 async fn count_mail_decisions(&self) -> Result<u64> {2817 async fn count_mail_decisions(&self) -> Result<u64> {
2771 let row = self2818 let row = self
2772 .one_row("SELECT COUNT(*) FROM mail_decision", ())2819 .one_row("SELECT COUNT(*) FROM mail_decision", ())
crates/izlek-core/tests/store.rsmodified+88 -0
@@ -5098,3 +5098,91 @@ async fn a_created_activity_does_not_fire_a_status_rule() {
5098 assert!(!row.detail.is_empty(), "the reason is not left blank");5098 assert!(!row.detail.is_empty(), "the reason is not left blank");
5099 let _ = std::fs::remove_dir_all(&dir);5099 let _ = std::fs::remove_dir_all(&dir);
5100 }5100 }
5101+
5102+#[tokio::test]
5103+async fn decisions_and_sends_for_task_read_only_that_tasks_own_rows() {
5104+ let (scratch, workspace, admin) = workspace_with_admin().await;
5105+ let store = &scratch.store;
5106+ let task = add_task(store, &workspace, "Backlog", "Ship it", None, &admin).await;
5107+ let other_task = add_task(store, &workspace, "Backlog", "Something else", None, &admin).await;
5108+ let rule = a_rule(store, &workspace, "Done", "Task completed").await;
5109+ let transition = moved_to(store, &workspace, &task, "Backlog", "Done", &admin).await;
5110+ let other_transition =
5111+ moved_to(store, &workspace, &other_task, "Backlog", "Done", &admin).await;
5112+ let now = OffsetDateTime::now_utc();
5113+
5114+ store
5115+ .record_mail_decision(&rule.id, &transition.id, &task, MailOutcome::Owed, "", now)
5116+ .await
5117+ .unwrap();
5118+ store
5119+ .record_mail_decision(
5120+ &rule.id,
5121+ &other_transition.id,
5122+ &other_task,
5123+ MailOutcome::Owed,
5124+ "",
5125+ now,
5126+ )
5127+ .await
5128+ .unwrap();
5129+ let send = store
5130+ .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now)
5131+ .await
5132+ .unwrap()
5133+ .unwrap();
5134+ store
5135+ .claim_send(&rule.id, &other_transition.id, &other_task, "emre@izlek.sh", now)
5136+ .await
5137+ .unwrap();
5138+
5139+ let decisions = store.decisions_for_task(&task, 10).await.unwrap();
5140+ assert_eq!(decisions.len(), 1);
5141+ assert_eq!(decisions[0].task_id, task);
5142+
5143+ let sends = store.sends_for_task(&task, 10).await.unwrap();
5144+ assert_eq!(sends.len(), 1);
5145+ assert_eq!(sends[0].id, send.id);
5146+ assert_eq!(sends[0].task_id.as_deref(), Some(task.as_str()));
5147+}
5148+
5149+#[tokio::test]
5150+async fn requeuing_a_send_puts_it_back_in_play_but_leaves_a_sent_one_alone() {
5151+ let (scratch, workspace, admin) = workspace_with_admin().await;
5152+ let store = &scratch.store;
5153+ let task = add_task(store, &workspace, "Backlog", "Ship it", None, &admin).await;
5154+ let rule = a_rule(store, &workspace, "Done", "Task completed").await;
5155+ let transition = moved_to(store, &workspace, &task, "Backlog", "Done", &admin).await;
5156+ let now = OffsetDateTime::now_utc();
5157+
5158+ let failed = store
5159+ .claim_send(&rule.id, &transition.id, &task, "failed@izlek.sh", now)
5160+ .await
5161+ .unwrap()
5162+ .unwrap();
5163+ store
5164+ .record_send_refused(&failed.id, "timeout", None, now)
5165+ .await
5166+ .unwrap();
5167+
5168+ let sent = store
5169+ .claim_send(&rule.id, &transition.id, &task, "sent@izlek.sh", now)
5170+ .await
5171+ .unwrap()
5172+ .unwrap();
5173+ store.record_send_accepted(&sent.id, now).await.unwrap();
5174+
5175+ store.requeue_send(&failed.id, now).await.unwrap();
5176+ store.requeue_send(&sent.id, now).await.unwrap();
5177+
5178+ let sends = store.sends_for_task(&task, 10).await.unwrap();
5179+ let reread_failed = sends.iter().find(|s| s.id == failed.id).unwrap();
5180+ assert_eq!(reread_failed.state, SendState::Pending);
5181+ assert!(reread_failed.next_attempt_at.is_some_and(|at| at <= now));
5182+
5183+ let reread_sent = sends.iter().find(|s| s.id == sent.id).unwrap();
5184+ assert_eq!(reread_sent.state, SendState::Sent, "a sent send is untouched");
5185+
5186+ let owed = store.sends_owed(now, 10).await.unwrap();
5187+ assert!(owed.iter().any(|s| s.id == failed.id), "the requeued send is now due");
5188+}
crates/izlek-web/src/detail.rsmodified+139 -0
@@ -82,6 +82,34 @@ pub struct DetailSnapshot {
82 pub may_delete: bool,82 pub may_delete: bool,
83 pub allowed_file_types: Vec<String>,83 pub allowed_file_types: Vec<String>,
84 pub attachment_limit_mb: u64,84 pub attachment_limit_mb: u64,
85+ pub notifications: Vec<NotificationLine>,
86+ pub may_administer: bool,
87+}
88+
89+/// One send's fate, joined to the sends of its decision's event.
90+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
91+pub struct SendLine {
92+ pub recipient: String,
93+ pub state: String,
94+ /// The chip's tone — see `logs.rs`'s `QueueLine::state_kind`.
95+ pub state_kind: String,
96+ pub attempts: u32,
97+ pub last_error: Option<String>,
98+ pub sent_at: Option<String>,
99+}
100+
101+/// One decision the task's rules made about one event, with what happened to
102+/// any mail it owed.
103+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
104+pub struct NotificationLine {
105+ /// What caused it — "moved to Done" — absent when the event is gone.
106+ pub happened: Option<String>,
107+ pub at: String,
108+ /// Shown only to an admin.
109+ pub rule_name: Option<String>,
110+ pub outcome: String,
111+ pub outcome_kind: String,
112+ pub sends: Vec<SendLine>,
85 }113 }
86 114
87 /// Which way round a dependency runs, as it travels in a form.115 /// Which way round a dependency runs, as it travels in a form.
@@ -269,6 +297,70 @@ async fn load_snapshot(
269 }297 }
270 298
271 let may_write = user.role.can_write_tasks();299 let may_write = user.role.can_write_tasks();
300+ let may_administer = user.role.can_administer();
301+ let lang = Lang::from_code(&user.language);
302+ let zone = parse_zone(&user.timezone);
303+
304+ let decisions = store.decisions_for_task(&detail.id, 10).await?;
305+ let sends = store.sends_for_task(&detail.id, 50).await?;
306+ let mut columns_cache: std::collections::HashMap<String, Vec<izlek_core::board::Column>> =
307+ std::collections::HashMap::new();
308+ let mut notifications = Vec::with_capacity(decisions.len());
309+ for decision in decisions {
310+ let rule = store.mail_rule(&decision.rule_id).await?;
311+ let rule_name = may_administer.then(|| {
312+ rule.as_ref()
313+ .map(|rule| rule.subject.clone())
314+ .unwrap_or_else(|| t(lang, Key::RuleGone).to_string())
315+ });
316+ let outcome_detail = crate::logs::decision_detail(
317+ &store,
318+ &mut columns_cache,
319+ rule.as_ref().map(|rule| rule.board_id.as_str()),
320+ decision.outcome,
321+ &decision.detail,
322+ lang,
323+ )
324+ .await?;
325+ let happened = crate::logs::event_happened(&store, &decision.event_id, lang).await?;
326+ let matching: Vec<SendLine> = sends
327+ .iter()
328+ .filter(|s| s.event_id.as_deref() == Some(decision.event_id.as_str()))
329+ .map(|send| {
330+ use izlek_core::store::SendState;
331+ let (state, state_kind) = match send.state {
332+ SendState::Pending => (t(lang, Key::QueueStatePending), "pending"),
333+ SendState::Failed if send.attempts == 0 => {
334+ (t(lang, Key::QueueStateHeld), "held")
335+ }
336+ SendState::Failed => (t(lang, Key::QueueStateFailed), "failed"),
337+ SendState::Sent => (t(lang, Key::QueueStateSent), "sent"),
338+ SendState::Abandoned => (t(lang, Key::QueueStateAbandoned), "abandoned"),
339+ };
340+ SendLine {
341+ recipient: send.recipient.clone(),
342+ state: state.to_string(),
343+ state_kind: state_kind.to_string(),
344+ attempts: send.attempts,
345+ last_error: send.last_error.clone(),
346+ sent_at: send.sent_at.map(|at| moment_label_in(at, zone)),
347+ }
348+ })
349+ .collect();
350+ let outcome = crate::logs::outcome_word(decision.outcome, lang).to_string();
351+ notifications.push(NotificationLine {
352+ happened,
353+ at: moment_label_in(decision.at, zone),
354+ rule_name,
355+ outcome: if outcome_detail.is_empty() {
356+ outcome
357+ } else {
358+ format!("{outcome} · {outcome_detail}")
359+ },
360+ outcome_kind: decision.outcome.as_str().to_string(),
361+ sends: matching,
362+ });
363+ }
272 364
273 const MB: u64 = 1024 * 1024;365 const MB: u64 = 1024 * 1024;
274 let workspace = store.workspace().await?;366 let workspace = store.workspace().await?;
@@ -288,6 +380,8 @@ async fn load_snapshot(
288 may_delete: may_write,380 may_delete: may_write,
289 allowed_file_types,381 allowed_file_types,
290 attachment_limit_mb,382 attachment_limit_mb,
383+ notifications,
384+ may_administer,
291 me: Me::from(&user),385 me: Me::from(&user),
292 today: OffsetDateTime::now_utc().date(),386 today: OffsetDateTime::now_utc().date(),
293 zone: parse_zone(&user.timezone),387 zone: parse_zone(&user.timezone),
@@ -1268,6 +1362,8 @@ pub async fn task_modal(cx: &Cx, task_id: &str, confirm_delete: bool) -> Result
1268 may_delete,1362 may_delete,
1269 allowed_file_types,1363 allowed_file_types,
1270 attachment_limit_mb: _,1364 attachment_limit_mb: _,
1365+ notifications,
1366+ may_administer: _,
1271 } = snapshot;1367 } = snapshot;
1272 let lang = Lang::from_code(&me.language);1368 let lang = Lang::from_code(&me.language);
1273 1369
@@ -1447,6 +1543,49 @@ pub async fn task_modal(cx: &Cx, task_id: &str, confirm_delete: bool) -> Result
1447 </div>1543 </div>
1448 </section>1544 </section>
1449 1545
1546+ <section class="detail-block">
1547+ <span class="detail-label">(t(lang, Key::Notifications))</span>
1548+ <div class="activity-list">
1549+ for line in &notifications {
1550+ <div class="activity-line">
1551+ <span class="activity-stamp">(line.at.clone())</span>
1552+ if let Some(rule_name) = &line.rule_name {
1553+ <strong class="activity-who">(rule_name.clone())</strong>
1554+ }
1555+ <span class="activity-what">
1556+ (line.happened.clone().unwrap_or_else(|| t(lang, Key::TaskGoneLabel).to_string()))
1557+ // The outcome word only speaks when no mail was owed: once a
1558+ // send exists its own state is the truth, and printing both
1559+ // reads as a contradiction ("queued" beside a mail long sent).
1560+ if line.sends.is_empty() {
1561+ " — "
1562+ <span class=(format!("rule-term rule-term-{}", line.outcome_kind))>(line.outcome.clone())</span>
1563+ }
1564+ </span>
1565+ if !line.sends.is_empty() {
1566+ <span class="activity-what">
1567+ for send in &line.sends {
1568+ <span class="rule-term">(send.recipient.clone())</span>
1569+ <span class=(format!("rule-term rule-term-{}", send.state_kind))>
1570+ (if send.state_kind == "failed" || send.state_kind == "abandoned" {
1571+ send.last_error.clone().unwrap_or_else(|| send.state.clone())
1572+ } else if send.state_kind == "sent" {
1573+ format!("{} {}", send.state, send.sent_at.clone().unwrap_or_default())
1574+ } else {
1575+ send.state.clone()
1576+ })
1577+ </span>
1578+ }
1579+ </span>
1580+ }
1581+ </div>
1582+ }
1583+ if notifications.is_empty() {
1584+ <p class="rules-quiet">(t(lang, Key::NothingYet))</p>
1585+ }
1586+ </div>
1587+ </section>
1588+
1450 (refused(cx, "delete_task", lang).await?)1589 (refused(cx, "delete_task", lang).await?)
1451 1590
1452 <footer class="detail-foot">1591 <footer class="detail-foot">
crates/izlek-web/src/i18n.rsmodified+6 -0
@@ -79,6 +79,8 @@ pub enum Key {
79 WriteAComment,79 WriteAComment,
80 Comment,80 Comment,
81 Activity,81 Activity,
82+ Notifications,
83+ Retry,
82 DeleteTask,84 DeleteTask,
83 CommentGoesWithIt,85 CommentGoesWithIt,
84 CommentsGoWithIt,86 CommentsGoWithIt,
@@ -411,6 +413,10 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
411 (WriteAComment, Tr) => "Bir yorum yaz…",413 (WriteAComment, Tr) => "Bir yorum yaz…",
412 (Comment, En) => "Comment",414 (Comment, En) => "Comment",
413 (Comment, Tr) => "Yorum yap",415 (Comment, Tr) => "Yorum yap",
416+ (Notifications, En) => "NOTIFICATIONS",
417+ (Notifications, Tr) => "BİLDİRİMLER",
418+ (Retry, En) => "Retry",
419+ (Retry, Tr) => "Yeniden dene",
414 (Activity, En) => "ACTIVITY",420 (Activity, En) => "ACTIVITY",
415 (Activity, Tr) => "ETKİNLİK",421 (Activity, Tr) => "ETKİNLİK",
416 (DeleteTask, En) => "Delete task",422 (DeleteTask, En) => "Delete task",
crates/izlek-web/src/logs.rsmodified+56 -5
@@ -14,8 +14,9 @@ use time::OffsetDateTime;
14 use time::format_description::well_known::Rfc3339;14 use time::format_description::well_known::Rfc3339;
15 use topcoat::Result;15 use topcoat::Result;
16 use topcoat::context::Cx;16 use topcoat::context::Cx;
17-use topcoat::router::content::Json;17+use topcoat::router::content::{Form, Json};
18-use topcoat::router::{page, route};18+use topcoat::router::request::headers;
19+use topcoat::router::{HeaderName, StatusCode, header, page, route};
19 use topcoat::view::view;20 use topcoat::view::view;
20 21
21 use crate::detail::{Me, datepicker_grid};22 use crate::detail::{Me, datepicker_grid};
@@ -26,6 +27,7 @@ use crate::settings::{decode_q, encode_q};
26 /// One send still owed or refused, as the queue panel reads it.27 /// One send still owed or refused, as the queue panel reads it.
27 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]28 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
28 struct QueueLine {29 struct QueueLine {
30+ id: String,
29 recipient: String,31 recipient: String,
30 subject: String,32 subject: String,
31 /// The localized word shown to the admin.33 /// The localized word shown to the admin.
@@ -124,7 +126,7 @@ const ACTIVITY_KINDS: &[&str] = &[
124 126
125 /// The word the decisions panel prints for an outcome. Terse: the panel is127 /// The word the decisions panel prints for an outcome. Terse: the panel is
126 /// read, not explained.128 /// read, not explained.
127-fn outcome_word(outcome: izlek_core::store::MailOutcome, lang: Lang) -> &'static str {129+pub(crate) fn outcome_word(outcome: izlek_core::store::MailOutcome, lang: Lang) -> &'static str {
128 use izlek_core::store::MailOutcome;130 use izlek_core::store::MailOutcome;
129 match outcome {131 match outcome {
130 MailOutcome::Owed => t(lang, Key::OutcomeQueued),132 MailOutcome::Owed => t(lang, Key::OutcomeQueued),
@@ -182,7 +184,7 @@ fn activity_sentence(kind: &izlek_core::detail::ActivityKind, detail: &str, lang
182 /// What an event did, in the decisions panel's own words — "moved to184 /// What an event did, in the decisions panel's own words — "moved to
183 /// Review" — or nothing when the event or its destination column is gone:185 /// Review" — or nothing when the event or its destination column is gone:
184 /// the panel names what it can still read, never a guess.186 /// the panel names what it can still read, never a guess.
185-async fn event_happened(187+pub(crate) async fn event_happened(
186 store: &std::sync::Arc<dyn izlek_core::store::Store>,188 store: &std::sync::Arc<dyn izlek_core::store::Store>,
187 event_id: &str,189 event_id: &str,
188 lang: Lang,190 lang: Lang,
@@ -217,7 +219,7 @@ async fn event_happened(
217 /// one fetch per board no matter how many decisions share it. A detail that219 /// one fetch per board no matter how many decisions share it. A detail that
218 /// is empty or does not parse as a known token — including every row a220 /// is empty or does not parse as a known token — including every row a
219 /// version before this scheme wrote — is shown exactly as stored.221 /// version before this scheme wrote — is shown exactly as stored.
220-async fn decision_detail(222+pub(crate) async fn decision_detail(
221 store: &std::sync::Arc<dyn izlek_core::store::Store>,223 store: &std::sync::Arc<dyn izlek_core::store::Store>,
222 columns_cache: &mut std::collections::HashMap<String, Vec<izlek_core::board::Column>>,224 columns_cache: &mut std::collections::HashMap<String, Vec<izlek_core::board::Column>>,
223 board_id: Option<&str>,225 board_id: Option<&str>,
@@ -536,6 +538,7 @@ async fn snapshot(
536 SendState::Abandoned => (t(lang, Key::QueueStateAbandoned), "abandoned"),538 SendState::Abandoned => (t(lang, Key::QueueStateAbandoned), "abandoned"),
537 };539 };
538 queue.push(QueueLine {540 queue.push(QueueLine {
541+ id: send.id,
539 recipient: send.recipient,542 recipient: send.recipient,
540 subject,543 subject,
541 state: state.to_string(),544 state: state.to_string(),
@@ -719,6 +722,48 @@ async fn current_logs(cx: &Cx) -> Result<Json<std::result::Result<LogsSnapshot,
719 ))722 ))
720 }723 }
721 724
725+/// The page a retry form was posted from, or the queue tab when there is no
726+/// `Referer` to read.
727+fn back_to(cx: &Cx) -> String {
728+ headers(cx)
729+ .get(header::REFERER)
730+ .and_then(|value| value.to_str().ok())
731+ .unwrap_or("/logs?section=queue")
732+ .to_string()
733+}
734+
735+/// A 303 to [`back_to`], carrying `refusal` as the body for
736+/// `crate::server::carry_refusal_on_redirect` to read and copy onto the query.
737+type Redirect = Result<(StatusCode, [(HeaderName, String); 1], Json<Option<Refusal>>)>;
738+
739+fn redirect(cx: &Cx, refusal: Option<Refusal>) -> Redirect {
740+ Ok((
741+ StatusCode::SEE_OTHER,
742+ [(header::LOCATION, back_to(cx))],
743+ Json(refusal),
744+ ))
745+}
746+
747+#[derive(Deserialize)]
748+struct RetrySendForm {
749+ send_id: String,
750+}
751+
752+/// Puts a failed or abandoned send back in play, admin only. No trail event:
753+/// no `ActivityKind` fits a retry, so none is written rather than one being
754+/// invented.
755+#[route(POST "/api/retry_send")]
756+async fn retry_send(cx: &Cx, Form(input): Form<RetrySendForm>) -> Redirect {
757+ if let Err(refusal) = require_admin(cx).await {
758+ return redirect(cx, Some(refusal));
759+ }
760+ let store = accounts(cx).store().clone();
761+ let _ = store
762+ .requeue_send(&input.send_id, OffsetDateTime::now_utc())
763+ .await;
764+ redirect(cx, None)
765+}
766+
722 fn query_value<'q>(query: &'q str, key: &str) -> Option<&'q str> {767 fn query_value<'q>(query: &'q str, key: &str) -> Option<&'q str> {
723 query.split('&').find_map(|pair| {768 query.split('&').find_map(|pair| {
724 pair.split_once('=')769 pair.split_once('=')
@@ -907,6 +952,12 @@ async fn logs_screen(
907 <span>(crate::i18n::attempt_label(lang, line.attempts))</span>952 <span>(crate::i18n::attempt_label(lang, line.attempts))</span>
908 </div>953 </div>
909 <span class="rule-stamp">(next_attempt)</span>954 <span class="rule-stamp">(next_attempt)</span>
955+ if line.state_kind == "failed" || line.state_kind == "abandoned" {
956+ <form method="post" action="/api/retry_send">
957+ <input type="hidden" name="send_id" value=(line.id.clone())>
958+ <button class="quiet" type="submit">(t(lang, Key::Retry))</button>
959+ </form>
960+ }
910 </div>961 </div>
911 }962 }
912 if queue_empty {963 if queue_empty {
crates/izlek-web/tests/http.rsmodified+183 -1
@@ -24,7 +24,8 @@ use std::sync::Arc;
24 use http::{HeaderValue, Request, StatusCode, header};24 use http::{HeaderValue, Request, StatusCode, header};
25 use izlek_core::Role;25 use izlek_core::Role;
26 use izlek_core::accounts::Accounts;26 use izlek_core::accounts::Accounts;
27-use izlek_core::store::{SendKind, Store, TursoStore};27+use izlek_core::board::Moved;
28+use izlek_core::store::{Audience, MailOutcome, SendKind, SendState, Store, Trigger, TursoStore};
28 use izlek_web::server::{Mail, SESSION_COOKIE};29 use izlek_web::server::{Mail, SESSION_COOKIE};
29 use topcoat::asset::{AssetBundle, RouterBuilderAssetExt};30 use topcoat::asset::{AssetBundle, RouterBuilderAssetExt};
30 use topcoat::cookie::RouterBuilderCookieExt;31 use topcoat::cookie::RouterBuilderCookieExt;
@@ -5210,3 +5211,184 @@ async fn an_invite_refusal_lands_on_the_members_section() {
5210 assert!(html.contains("field-error"), "{html}");5211 assert!(html.contains("field-error"), "{html}");
5211 assert!(html.contains("emre@izlek.sh"), "{html}");5212 assert!(html.contains("emre@izlek.sh"), "{html}");
5212 }5213 }
5214+
5215+/// Seeds one decision and one accepted send directly on the store — the
5216+/// engine's own timing is not what these notification tests are about — and
5217+/// hands back the task and the send's id.
5218+async fn a_task_with_a_notification(app: &App, admin_cookie: &str, subject: &str) -> (String, String) {
5219+ let columns = columns_of(app).await;
5220+ let task = a_task(app, admin_cookie, &columns[0], "Ship it").await;
5221+ let admin_id = person_id(app, admin_cookie, &task, "Ada Lovelace").await;
5222+ let workspace_id = app.workspace_id().await;
5223+ let board = app.store.board(&workspace_id).await.unwrap().unwrap();
5224+ let rule = app
5225+ .store
5226+ .create_mail_rule(
5227+ &board.id,
5228+ &Trigger::StatusBecomes(columns[1].clone()),
5229+ subject,
5230+ Audience::Assignees,
5231+ time::OffsetDateTime::now_utc(),
5232+ false,
5233+ )
5234+ .await
5235+ .unwrap();
5236+ let transition = match app
5237+ .store
5238+ .move_task(
5239+ &task,
5240+ &columns[0],
5241+ &columns[1],
5242+ &admin_id,
5243+ time::OffsetDateTime::now_utc(),
5244+ )
5245+ .await
5246+ .unwrap()
5247+ {
5248+ Moved::Recorded(transition) => transition,
5249+ other => panic!("the move did not happen: {other:?}"),
5250+ };
5251+ let now = time::OffsetDateTime::now_utc();
5252+ app.store
5253+ .record_mail_decision(&rule.id, &transition.id, &task, MailOutcome::Owed, "", now)
5254+ .await
5255+ .unwrap();
5256+ let send = app
5257+ .store
5258+ .claim_send(&rule.id, &transition.id, &task, "ada@izlek.sh", now)
5259+ .await
5260+ .unwrap()
5261+ .unwrap();
5262+ app.store.record_send_accepted(&send.id, now).await.unwrap();
5263+ (task, send.id)
5264+}
5265+
5266+/// A task's detail page shows its notifications: the recipient and a state
5267+/// chip for a send its rules made, to anyone who can read the task — but the
5268+/// rule's own name only to an admin.
5269+#[tokio::test]
5270+async fn a_tasks_notifications_show_the_recipient_and_the_rule_name_is_admin_only() {
5271+ let app = App::open().await;
5272+ let admin_cookie = admin(&app).await;
5273+ let member = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await;
5274+ let (task, _send_id) =
5275+ a_task_with_a_notification(&app, &admin_cookie, "Wraps up the sprint").await;
5276+
5277+ let member_page = app.get(&format!("/?task={task}"), Some(&member)).await;
5278+ let member_html = String::from_utf8_lossy(&member_page.bytes);
5279+ assert!(member_html.contains("ada@izlek.sh"), "{member_html}");
5280+ assert!(
5281+ member_html.contains("rule-term-sent"),
5282+ "no state chip on the member's page: {member_html}"
5283+ );
5284+ assert!(
5285+ !member_html.contains("Wraps up the sprint"),
5286+ "a member was shown the rule's name: {member_html}"
5287+ );
5288+
5289+ let admin_page = app.get(&format!("/?task={task}"), Some(&admin_cookie)).await;
5290+ let admin_html = String::from_utf8_lossy(&admin_page.bytes);
5291+ assert!(admin_html.contains("ada@izlek.sh"), "{admin_html}");
5292+ assert!(admin_html.contains("Wraps up the sprint"), "{admin_html}");
5293+}
5294+
5295+/// A task with no mail at all renders the same quiet empty line the other
5296+/// blocks use, under the notifications heading.
5297+#[tokio::test]
5298+async fn a_task_with_no_mail_shows_the_quiet_notifications_line() {
5299+ let app = App::open().await;
5300+ let admin_cookie = admin(&app).await;
5301+ let column = first_column(&app).await;
5302+ let task = a_task(&app, &admin_cookie, &column, "Nobody mails me").await;
5303+
5304+ let page = app.get(&format!("/?task={task}"), Some(&admin_cookie)).await;
5305+ let html = String::from_utf8_lossy(&page.bytes);
5306+ assert!(html.contains("NOTIFICATIONS"), "{html}");
5307+ assert!(html.contains("Nothing yet."), "{html}");
5308+}
5309+
5310+/// An admin's retry puts a failed send back in play — pending, due right
5311+/// away — and the queue tab picks it back up.
5312+#[tokio::test]
5313+async fn an_admin_retries_a_failed_send_and_it_rejoins_the_queue() {
5314+ let app = App::open().await;
5315+ let admin_cookie = admin(&app).await;
5316+ let (task, send_id) =
5317+ a_task_with_a_notification(&app, &admin_cookie, "Never got there").await;
5318+ let now = time::OffsetDateTime::now_utc();
5319+ app.store
5320+ .record_send_refused(&send_id, "timeout", Some(now), now)
5321+ .await
5322+ .unwrap();
5323+
5324+ let answer = app
5325+ .post("/api/retry_send", Some(&admin_cookie), &[("send_id", &send_id)])
5326+ .await;
5327+ assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
5328+ assert_eq!(answer.body, "null", "{}", answer.body);
5329+
5330+ let sends = app.store.sends_for_task(&task, 10).await.unwrap();
5331+ let reread = sends.iter().find(|s| s.id == send_id).unwrap();
5332+ assert_eq!(reread.state, SendState::Pending);
5333+ assert!(
5334+ reread
5335+ .next_attempt_at
5336+ .is_some_and(|at| at <= time::OffsetDateTime::now_utc()),
5337+ "the retry is not due right away: {reread:?}"
5338+ );
5339+
5340+ let logs = app.post("/api/current_logs", Some(&admin_cookie), &[]).await;
5341+ assert!(
5342+ logs.body.contains("\"recipient\":\"ada@izlek.sh\""),
5343+ "the retried send did not rejoin the queue: {}",
5344+ logs.body
5345+ );
5346+}
5347+
5348+/// A member cannot retry a send, and the pages a member can reach never draw
5349+/// a Retry button in the first place.
5350+#[tokio::test]
5351+async fn a_member_may_not_retry_a_send() {
5352+ let app = App::open().await;
5353+ let admin_cookie = admin(&app).await;
5354+ let member = invited(&app, &admin_cookie, "emre@izlek.sh", "Emre", Role::Member).await;
5355+ let (task, send_id) =
5356+ a_task_with_a_notification(&app, &admin_cookie, "Member cannot touch this").await;
5357+ let now = time::OffsetDateTime::now_utc();
5358+ app.store
5359+ .record_send_refused(&send_id, "timeout", Some(now), now)
5360+ .await
5361+ .unwrap();
5362+
5363+ let answer = app
5364+ .post("/api/retry_send", Some(&member), &[("send_id", &send_id)])
5365+ .await;
5366+ assert!(answer.body.contains("Forbidden"), "{}", answer.body);
5367+
5368+ let sends = app.store.sends_for_task(&task, 10).await.unwrap();
5369+ let reread = sends.iter().find(|s| s.id == send_id).unwrap();
5370+ assert_eq!(reread.state, SendState::Failed, "the refused retry moved it anyway");
5371+
5372+ let member_page = app.get(&format!("/?task={task}"), Some(&member)).await;
5373+ let member_html = String::from_utf8_lossy(&member_page.bytes);
5374+ assert!(!member_html.contains("Retry"), "{member_html}");
5375+}
5376+
5377+/// Retrying a send that already went out changes nothing, and does not 500.
5378+#[tokio::test]
5379+async fn retrying_an_already_sent_send_changes_nothing() {
5380+ let app = App::open().await;
5381+ let admin_cookie = admin(&app).await;
5382+ let (task, send_id) =
5383+ a_task_with_a_notification(&app, &admin_cookie, "Already on its way").await;
5384+
5385+ let answer = app
5386+ .post("/api/retry_send", Some(&admin_cookie), &[("send_id", &send_id)])
5387+ .await;
5388+ assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
5389+ assert_eq!(answer.body, "null", "{}", answer.body);
5390+
5391+ let sends = app.store.sends_for_task(&task, 10).await.unwrap();
5392+ let reread = sends.iter().find(|s| s.id == send_id).unwrap();
5393+ assert_eq!(reread.state, SendState::Sent, "a sent send was touched by a retry");
5394+}
style/main.scssmodified+6 -2
@@ -2061,8 +2061,9 @@ img.avatar {
2061 2061
2062 .activity-line {2062 .activity-line {
2063 display: flex;2063 display: flex;
2064+ flex-wrap: wrap;
2064 align-items: baseline;2065 align-items: baseline;
2065- gap: 10px;2066+ gap: 6px 10px;
2066 font-size: 12px;2067 font-size: 12px;
2067 color: var(--muted);2068 color: var(--muted);
2068 }2069 }
@@ -2074,7 +2075,10 @@ img.avatar {
2074 color: var(--muted-soft);2075 color: var(--muted-soft);
2075 }2076 }
2076 2077
2077-.activity-who { color: var(--ink); }2078+.activity-who {
2079+ flex: none;
2080+ color: var(--ink);
2081+}
2078 2082
2079 // -- footer -----------------------------------------------------------------2083 // -- footer -----------------------------------------------------------------
2080 2084