forge
Explore
Log in

Don't you dare go Hollow

iz_old

Clone
★ 0

0 watching0 forksRustGPL-3.02.2 MiB4c154b4Tahinli2 months ago301 commits

rules.rs919 lines, 33.5 KiBHistoryRawDownload
1//! Mail rules, ported from `iz-web/src/rules.rs` onto topcoat's
2//! server-rendered pages.
3//!
4//! The screen is the admin's, and so is every call behind it: a rule sends mail
5//! on everyone's behalf, from the one workspace sender, so writing one is not
6//! something a Member may do even if they reach the endpoint directly. The
7//! chip in the artboard says "Admin only"; the guard is in the handlers.
8//!
9//! There is no client-side signal here to hold which row is being edited —
10//! every topcoat page is rendered fresh, server-side, on every request. Which
11//! rule (if any) is open for editing rides `?edit=<rule_id>` on `/rules`
12//! itself: the row renders as `RuleForm` server-side instead of the display
13//! row, no script required. The mutating endpoints preserve that query pair
14//! across their redirect (see `crate::server::refusal_of`'s `carrying`), so a
15//! failed edit lands back on the same open row rather than closing it.
16
17use std::sync::Arc;
18
19use serde::{Deserialize, Serialize};
20use topcoat::Result;
21use topcoat::context::Cx;
22use topcoat::router::content::{Form, Json};
23use topcoat::router::{HeaderName, StatusCode, header, page, query_params, route};
24use topcoat::view::{View, ViewExt, view};
25
26use iz_core::board::Column;
27use iz_core::store::{Audience, Store, Trigger, User, Workspace};
28
29use crate::i18n::{Key, Lang, t};
30use crate::server::{Refusal, back_to, refusal_of, require_admin, store};
31
32/// One rule as the screen reads it: a sentence, a switch and a stamp.
33///
34/// The trigger arrives already split into the words the artboard prints —
35/// "When status becomes" / "Done" — because the two halves are chosen from
36/// different vocabularies and only the server knows the column names.
37#[derive(Clone, Debug, Serialize)]
38struct RuleLine {
39 id: String,
40 /// "When status becomes", or "When a task stops being".
41 when: String,
42 /// "Done", or "blocked". `None` when the trigger has no second half —
43 /// which is not the same as an empty one: the sentence prints this in a
44 /// term box, and a box with nothing in it is what "When someone is
45 /// assigned □ send" was.
46 what: Option<String>,
47 subject: String,
48 /// "assignees", "everyone on board", or "its creator".
49 audience: String,
50 /// The trigger's own word — "status", "unblocked", "created" — as the
51 /// edit form's select expects it, not as the sentence prints it.
52 trigger_kind: String,
53 /// The named column, for a status trigger's edit form. `None` for every
54 /// other trigger.
55 column_id: Option<String>,
56 /// The audience's own word — "assignees", "board", "creator" — as the
57 /// edit form's select expects it.
58 audience_kind: String,
59 include_task_details: bool,
60 enabled: bool,
61 /// `Aug 24 14:02`, or nothing when no mail from this rule has ever been
62 /// accepted by the mail server.
63 last_sent: Option<String>,
64 /// `Aug 24 14:02` of the rule's last decision, sent or not, or nothing
65 /// when the rule has never been evaluated.
66 last_fired: Option<String>,
67}
68
69/// A column, for the composer's status list.
70#[derive(Clone, Debug, Serialize)]
71struct ColumnChoice {
72 id: String,
73 name: String,
74}
75
76/// The screen in one answer.
77#[derive(Clone, Debug, Serialize)]
78struct RulesSnapshot {
79 rules: Vec<RuleLine>,
80 columns: Vec<ColumnChoice>,
81 /// Whether a sender is connected. Rules that fire with no sender queue
82 /// rather than fail, and the screen says so instead of leaving somebody to
83 /// wonder why nothing arrived.
84 sender_connected: bool,
85}
86
87/// The word for an audience, as the artboard writes it.
88fn audience_word(audience: Audience, lang: Lang) -> &'static str {
89 match audience {
90 Audience::Assignees => t(lang, Key::AudAssignees),
91 Audience::Board => t(lang, Key::AudEveryoneOnBoard),
92 Audience::Creator => t(lang, Key::AudItsCreator),
93 }
94}
95
96/// The audience's own word, as the edit form's select names it.
97fn audience_kind(audience: Audience) -> &'static str {
98 match audience {
99 Audience::Assignees => "assignees",
100 Audience::Board => "board",
101 Audience::Creator => "creator",
102 }
103}
104
105/// Parses a trigger from the words a form sends: the trigger's own kind, and
106/// a column id only a status trigger carries. A status trigger with no column
107/// is the every-column rule. Every other trigger must arrive with no column —
108/// a column id on, say, "created" is a form gone wrong, not something to
109/// guess past.
110///
111/// Shared by `create_rule` and `update_rule` so the vocabulary is matched
112/// once.
113fn trigger_of(kind: &str, column_id: Option<String>) -> Option<Trigger> {
114 match (kind, column_id) {
115 ("status", column_id) => Some(Trigger::StatusBecomes(column_id)),
116 ("unblocked", None) => Some(Trigger::Unblocked),
117 ("created", None) => Some(Trigger::Created),
118 ("assigned", None) => Some(Trigger::Assigned),
119 ("unassigned", None) => Some(Trigger::Unassigned),
120 ("commented", None) => Some(Trigger::Commented),
121 ("deadline_set", None) => Some(Trigger::DeadlineSet),
122 ("deadline_cleared", None) => Some(Trigger::DeadlineCleared),
123 ("retitled", None) => Some(Trigger::Retitled),
124 ("linked", None) => Some(Trigger::Linked),
125 ("unlinked", None) => Some(Trigger::Unlinked),
126 ("deleted", None) => Some(Trigger::Deleted),
127 _ => None,
128 }
129}
130
131/// The audience a form's own word names, or the refusal for anything else —
132/// shared by `create_rule` and `update_rule`.
133fn audience_of(word: &str) -> std::result::Result<Audience, Refusal> {
134 match word {
135 "assignees" => Ok(Audience::Assignees),
136 "board" => Ok(Audience::Board),
137 "creator" => Ok(Audience::Creator),
138 _ => Err(Refusal::Forbidden),
139 }
140}
141
142/// Whether a sender is connected, read straight off the raw workspace row —
143/// this module does not reach into `crate::settings::Sender` so it stays
144/// independent of that screen's own shape.
145fn sender_connected(workspace: &Workspace) -> bool {
146 !workspace
147 .smtp_host
148 .as_deref()
149 .unwrap_or_default()
150 .trim()
151 .is_empty()
152 && !workspace
153 .smtp_username
154 .as_deref()
155 .unwrap_or_default()
156 .trim()
157 .is_empty()
158 && !workspace
159 .smtp_from_address
160 .as_deref()
161 .unwrap_or_default()
162 .trim()
163 .is_empty()
164 && workspace.smtp_password_set
165}
166
167/// Splits a trigger into the sentence halves the screen prints, ported
168/// verbatim from `current_rules`'s match in `iz-web/src/rules.rs`.
169fn sentence_of(
170 trigger: &Trigger,
171 columns: &[Column],
172 lang: Lang,
173) -> (String, Option<String>, String, Option<String>) {
174 match trigger {
175 // No column is every column, and "becomes <a column>" has nothing to
176 // name then — the sentence changes shape rather than printing a word
177 // for "any".
178 Trigger::StatusBecomes(None) => (
179 t(lang, Key::WhenStatusChanges).to_string(),
180 None,
181 "status".to_string(),
182 None,
183 ),
184 Trigger::StatusBecomes(Some(column_id)) => (
185 t(lang, Key::WhenStatusBecomes).to_string(),
186 Some(
187 columns
188 .iter()
189 .find(|column| &column.id == column_id)
190 // A rule can outlive the column it names. Saying so is
191 // better than printing an id nobody can read.
192 .map(|column| crate::i18n::column_name(lang, &column.name))
193 .unwrap_or_else(|| t(lang, Key::ColumnGone).to_string()),
194 ),
195 "status".to_string(),
196 Some(column_id.clone()),
197 ),
198 Trigger::Unblocked => (
199 t(lang, Key::WhenTaskStopsBeingBlocked).to_string(),
200 Some(t(lang, Key::BlockedWord).to_string()),
201 "unblocked".to_string(),
202 None,
203 ),
204 Trigger::Created => (
205 t(lang, Key::WhenTaskCreated).to_string(),
206 None,
207 "created".to_string(),
208 None,
209 ),
210 Trigger::Assigned => (
211 t(lang, Key::WhenSomeoneAssigned).to_string(),
212 None,
213 "assigned".to_string(),
214 None,
215 ),
216 Trigger::Unassigned => (
217 t(lang, Key::WhenSomeoneUnassigned).to_string(),
218 None,
219 "unassigned".to_string(),
220 None,
221 ),
222 Trigger::Commented => (
223 t(lang, Key::WhenCommentWritten).to_string(),
224 None,
225 "commented".to_string(),
226 None,
227 ),
228 Trigger::DeadlineSet => (
229 t(lang, Key::WhenDeadlineSet).to_string(),
230 None,
231 "deadline_set".to_string(),
232 None,
233 ),
234 Trigger::DeadlineCleared => (
235 t(lang, Key::WhenDeadlineRemoved).to_string(),
236 None,
237 "deadline_cleared".to_string(),
238 None,
239 ),
240 Trigger::Retitled => (
241 t(lang, Key::WhenTaskRenamed).to_string(),
242 None,
243 "retitled".to_string(),
244 None,
245 ),
246 Trigger::Linked => (
247 t(lang, Key::WhenTaskLinked).to_string(),
248 None,
249 "linked".to_string(),
250 None,
251 ),
252 Trigger::Unlinked => (
253 t(lang, Key::WhenTaskUnlinked).to_string(),
254 None,
255 "unlinked".to_string(),
256 None,
257 ),
258 Trigger::Deleted => (
259 t(lang, Key::WhenTaskDeleted).to_string(),
260 None,
261 "deleted".to_string(),
262 None,
263 ),
264 }
265}
266
267/// Every rule on the board, switched-off ones included, with the columns a new
268/// rule may name — shared by the page and `current_rules`, so the two never
269/// drift apart.
270async fn snapshot_of(
271 store: &Arc<dyn Store>,
272 user: &User,
273) -> std::result::Result<RulesSnapshot, Refusal> {
274 let lang = Lang::from_code(&user.language);
275 let zone = iz_core::detail::parse_zone(&user.timezone);
276 let Some(board) = store
277 .board(&user.workspace_id)
278 .await
279 .map_err(|_| Refusal::Unavailable)?
280 else {
281 return Err(Refusal::Unavailable);
282 };
283 let columns = store
284 .columns(&board.id)
285 .await
286 .map_err(|_| Refusal::Unavailable)?;
287 let rules = store
288 .mail_rules(&board.id)
289 .await
290 .map_err(|_| Refusal::Unavailable)?;
291 let last_sent = store
292 .mail_rule_last_sent(&board.id)
293 .await
294 .map_err(|_| Refusal::Unavailable)?;
295 let last_decision = store
296 .mail_rule_last_decision()
297 .await
298 .map_err(|_| Refusal::Unavailable)?;
299 let sender_connected = store
300 .workspace()
301 .await
302 .map_err(|_| Refusal::Unavailable)?
303 .as_ref()
304 .is_some_and(sender_connected);
305
306 let lines = rules
307 .into_iter()
308 .map(|rule| {
309 let (when, what, trigger_kind, column_id) = sentence_of(&rule.trigger, &columns, lang);
310 RuleLine {
311 when,
312 what,
313 subject: rule.subject.clone(),
314 audience: audience_word(rule.audience, lang).to_string(),
315 trigger_kind,
316 column_id,
317 audience_kind: audience_kind(rule.audience).to_string(),
318 include_task_details: rule.include_task_details,
319 enabled: rule.enabled,
320 last_sent: last_sent
321 .iter()
322 .find(|(id, _)| id == &rule.id)
323 .map(|(_, at)| iz_core::detail::moment_label_in(*at, zone)),
324 last_fired: last_decision
325 .iter()
326 .find(|(id, _)| id == &rule.id)
327 .map(|(_, at)| iz_core::detail::moment_label_in(*at, zone)),
328 id: rule.id,
329 }
330 })
331 .collect();
332
333 Ok(RulesSnapshot {
334 rules: lines,
335 columns: columns
336 .into_iter()
337 .map(|column| ColumnChoice {
338 id: column.id,
339 name: crate::i18n::column_name(lang, &column.name),
340 })
341 .collect(),
342 sender_connected,
343 })
344}
345
346/// The admin's store, once the rule id has been shown to name a rule on this
347/// workspace's own board.
348///
349/// A rule id is opaque and arrives from the browser, so "not yours" and "not a
350/// rule" are the same answer: neither tells the caller whether the id exists
351/// somewhere else.
352async fn rule_of_this_workspace(
353 cx: &Cx,
354 rule_id: &str,
355) -> std::result::Result<(Arc<dyn Store>, User, iz_core::store::MailRule), Refusal> {
356 let user = require_admin(cx).await?;
357 let store = store(cx).clone();
358 let board = store
359 .board(&user.workspace_id)
360 .await
361 .map_err(|_| Refusal::Unavailable)?
362 .ok_or(Refusal::Unavailable)?;
363 let rule = store
364 .mail_rule(rule_id)
365 .await
366 .map_err(|_| Refusal::Unavailable)?
367 .ok_or(Refusal::NotFound)?;
368 if rule.board_id != board.id {
369 return Err(Refusal::NotFound);
370 }
371 Ok((store, user, rule))
372}
373
374/// Every rule on the board, as JSON — kept for callers that post rather than
375/// render, such as the http test suite.
376#[route(POST "/api/current_rules")]
377async fn current_rules(cx: &Cx) -> Result<Json<std::result::Result<RulesSnapshot, Refusal>>> {
378 let user = match require_admin(cx).await {
379 Ok(user) => user,
380 Err(refusal) => return Ok(Json(Err(refusal))),
381 };
382 let store = store(cx).clone();
383 Ok(Json(snapshot_of(&store, &user).await))
384}
385
386/// A 303 to [`back_to`], carrying `refusal` as the body for
387/// `crate::server::carry_refusal_on_redirect` to read and copy onto the query.
388type Redirect = Result<(StatusCode, [(HeaderName, String); 1], Json<Option<Refusal>>)>;
389
390fn redirect(cx: &Cx, refusal: Option<Refusal>) -> Redirect {
391 Ok((
392 StatusCode::SEE_OTHER,
393 [(header::LOCATION, back_to(cx, "/"))],
394 Json(refusal),
395 ))
396}
397
398#[derive(Deserialize)]
399struct CreateRuleForm {
400 trigger: String,
401 column_id: String,
402 subject: String,
403 audience: String,
404 #[serde(default)]
405 include_task_details: String,
406}
407
408/// Writes one rule.
409///
410/// `column_id` is only read for the status trigger, and is checked against
411/// this workspace's own board rather than trusted — a column id from
412/// somewhere else would otherwise be a way to hang a rule off another
413/// workspace's board.
414#[route(POST "/api/create_rule")]
415async fn create_rule(cx: &Cx, Form(input): Form<CreateRuleForm>) -> Redirect {
416 let user = match require_admin(cx).await {
417 Ok(user) => user,
418 Err(refusal) => return redirect(cx, Some(refusal)),
419 };
420 let subject = input.subject.trim().to_string();
421 if subject.is_empty() {
422 return redirect(cx, Some(Refusal::EmptySubject));
423 }
424 let audience = match audience_of(&input.audience) {
425 Ok(audience) => audience,
426 Err(refusal) => return redirect(cx, Some(refusal)),
427 };
428
429 let store = store(cx).clone();
430 let board = match store.board(&user.workspace_id).await {
431 Ok(Some(board)) => board,
432 _ => return redirect(cx, Some(Refusal::Unavailable)),
433 };
434 let column_id = if input.column_id.trim().is_empty() {
435 None
436 } else {
437 Some(input.column_id)
438 };
439 // A status rule may name no column at all — that one watches every
440 // column. A named one still has to be this board's own.
441 if input.trigger == "status"
442 && let Some(column_id) = &column_id
443 {
444 let columns = match store.columns(&board.id).await {
445 Ok(columns) => columns,
446 Err(_) => return redirect(cx, Some(Refusal::Unavailable)),
447 };
448 if !columns.iter().any(|column| &column.id == column_id) {
449 return redirect(cx, Some(Refusal::Forbidden));
450 }
451 }
452 let Some(trigger) = trigger_of(&input.trigger, column_id) else {
453 return redirect(cx, Some(Refusal::Forbidden));
454 };
455
456 if store
457 .create_mail_rule(
458 &board.id,
459 &trigger,
460 &subject,
461 audience,
462 time::OffsetDateTime::now_utc(),
463 input.include_task_details == "true",
464 )
465 .await
466 .is_err()
467 {
468 return redirect(cx, Some(Refusal::Unavailable));
469 }
470 let _ = store
471 .record_event(
472 Some(&user.id),
473 &iz_core::detail::ActivityKind::RuleCreated,
474 &subject,
475 time::OffsetDateTime::now_utc(),
476 )
477 .await;
478 redirect(cx, None)
479}
480
481#[derive(Deserialize)]
482struct UpdateRuleForm {
483 rule_id: String,
484 trigger: String,
485 column_id: String,
486 subject: String,
487 audience: String,
488 #[serde(default)]
489 include_task_details: String,
490}
491
492/// Rewrites a rule's sentence in place. Guarded exactly like `create_rule` —
493/// same subject rule, same column-belongs-to-this-board check — plus the
494/// rule itself has to be this workspace's, or an id from elsewhere could be
495/// rewritten by an admin who never owned it.
496#[route(POST "/api/update_rule")]
497async fn update_rule(cx: &Cx, Form(input): Form<UpdateRuleForm>) -> Redirect {
498 let user = match require_admin(cx).await {
499 Ok(user) => user,
500 Err(refusal) => return redirect(cx, Some(refusal)),
501 };
502 let subject = input.subject.trim().to_string();
503 if subject.is_empty() {
504 return redirect(cx, Some(Refusal::EmptySubject));
505 }
506 let audience = match audience_of(&input.audience) {
507 Ok(audience) => audience,
508 Err(refusal) => return redirect(cx, Some(refusal)),
509 };
510
511 let store = store(cx).clone();
512 let board = match store.board(&user.workspace_id).await {
513 Ok(Some(board)) => board,
514 _ => return redirect(cx, Some(Refusal::Unavailable)),
515 };
516 match store.mail_rule(&input.rule_id).await {
517 Ok(Some(rule)) if rule.board_id == board.id => {}
518 Ok(_) => return redirect(cx, Some(Refusal::NotFound)),
519 Err(_) => return redirect(cx, Some(Refusal::Unavailable)),
520 }
521
522 let column_id = if input.column_id.trim().is_empty() {
523 None
524 } else {
525 Some(input.column_id)
526 };
527 // A status rule may name no column at all — that one watches every
528 // column. A named one still has to be this board's own.
529 if input.trigger == "status"
530 && let Some(column_id) = &column_id
531 {
532 let columns = match store.columns(&board.id).await {
533 Ok(columns) => columns,
534 Err(_) => return redirect(cx, Some(Refusal::Unavailable)),
535 };
536 if !columns.iter().any(|column| &column.id == column_id) {
537 return redirect(cx, Some(Refusal::Forbidden));
538 }
539 }
540 let Some(trigger) = trigger_of(&input.trigger, column_id) else {
541 return redirect(cx, Some(Refusal::Forbidden));
542 };
543
544 if store
545 .update_mail_rule(
546 &input.rule_id,
547 &trigger,
548 &subject,
549 audience,
550 input.include_task_details == "true",
551 )
552 .await
553 .is_err()
554 {
555 return redirect(cx, Some(Refusal::Unavailable));
556 }
557 let _ = store
558 .record_event(
559 Some(&user.id),
560 &iz_core::detail::ActivityKind::RuleEdited,
561 &subject,
562 time::OffsetDateTime::now_utc(),
563 )
564 .await;
565 redirect(cx, None)
566}
567
568#[derive(Deserialize)]
569struct SetRuleEnabledForm {
570 rule_id: String,
571 enabled: String,
572}
573
574/// Turns one rule on or off. Switching off stops it firing from here on; mail
575/// it already owes has been written to the ledger and is still owed.
576#[route(POST "/api/set_rule_enabled")]
577async fn set_rule_enabled(cx: &Cx, Form(input): Form<SetRuleEnabledForm>) -> Redirect {
578 let (store, user, rule) = match rule_of_this_workspace(cx, &input.rule_id).await {
579 Ok(triple) => triple,
580 Err(refusal) => return redirect(cx, Some(refusal)),
581 };
582 if store
583 .set_mail_rule_enabled(&input.rule_id, input.enabled == "true")
584 .await
585 .is_err()
586 {
587 return redirect(cx, Some(Refusal::Unavailable));
588 }
589 let _ = store
590 .record_event(
591 Some(&user.id),
592 &iz_core::detail::ActivityKind::RuleToggled,
593 &rule.subject,
594 time::OffsetDateTime::now_utc(),
595 )
596 .await;
597 redirect(cx, None)
598}
599
600#[derive(Deserialize)]
601struct DeleteRuleForm {
602 rule_id: String,
603}
604
605/// Removes a rule. What it has already sent stays in the ledger: the rule is
606/// gone, the record of what went out is not.
607#[route(POST "/api/delete_rule")]
608async fn delete_rule(cx: &Cx, Form(input): Form<DeleteRuleForm>) -> Redirect {
609 let (store, user, rule) = match rule_of_this_workspace(cx, &input.rule_id).await {
610 Ok(triple) => triple,
611 Err(refusal) => return redirect(cx, Some(refusal)),
612 };
613 if store.delete_mail_rule(&input.rule_id).await.is_err() {
614 return redirect(cx, Some(Refusal::Unavailable));
615 }
616 let _ = store
617 .record_event(
618 Some(&user.id),
619 &iz_core::detail::ActivityKind::RuleDeleted,
620 &rule.subject,
621 time::OffsetDateTime::now_utc(),
622 )
623 .await;
624 redirect(cx, None)
625}
626
627/// Which rule (if any) `/rules` renders open for editing.
628#[query_params(error = redirect("/rules"))]
629struct RulesQuery {
630 edit: Option<String>,
631}
632
633/// The trigger/column/subject/audience form: one view for both writing a new
634/// rule and rewriting an existing one, so the two never drift apart.
635///
636/// `existing` is `None` for a fresh rule and `Some` to edit one in place. The
637/// column select only shows for the status trigger; every other trigger
638/// carries `column_id` as a hidden field instead, the same trick
639/// `iz-web/src/rules.rs` used to hide it live — here it is decided once,
640/// server-side, from whichever trigger the form starts on (the existing
641/// rule's, or "status" for a fresh one), since there is no script to flip it
642/// as the admin changes the select.
643async fn rule_form<'a>(
644 cx: &'a Cx,
645 columns: &'a [ColumnChoice],
646 existing: Option<&'a RuleLine>,
647 refusal: Option<&'a Refusal>,
648 lang: Lang,
649) -> Result<impl View + 'a> {
650 let is_edit = existing.is_some();
651 let action = if is_edit {
652 "/api/update_rule"
653 } else {
654 "/api/create_rule"
655 };
656 let trigger_kind = existing
657 .map(|rule| rule.trigger_kind.as_str())
658 .unwrap_or("status");
659 let column_id = existing
660 .and_then(|rule| rule.column_id.as_deref())
661 .or_else(|| columns.first().map(|column| column.id.as_str()))
662 .unwrap_or_default();
663 let subject = existing
664 .map(|rule| rule.subject.as_str())
665 .unwrap_or_default();
666 let audience_kind = existing
667 .map(|rule| rule.audience_kind.as_str())
668 .unwrap_or("assignees");
669 let include_task_details = existing.is_some_and(|rule| rule.include_task_details);
670
671 Ok(view! {
672 cx =>
673 <form method="post" action=(action) class="rule-new-body">
674 if let Some(rule) = existing {
675 <input type="hidden" name="rule_id" value=(rule.id.clone())>
676 }
677 <label class="rule-field">
678 <span class="field-label">(t(lang, Key::WhenLabel))</span>
679 <select class="field-input" name="trigger">
680 <option value="status" selected=(trigger_kind == "status")>(t(lang, Key::TriggerStatusBecomes))</option>
681 <option value="unblocked" selected=(trigger_kind == "unblocked")>(t(lang, Key::TriggerUnblocked))</option>
682 <option value="created" selected=(trigger_kind == "created")>(t(lang, Key::TriggerCreated))</option>
683 <option value="assigned" selected=(trigger_kind == "assigned")>(t(lang, Key::TriggerAssigned))</option>
684 <option value="unassigned" selected=(trigger_kind == "unassigned")>(t(lang, Key::TriggerUnassigned))</option>
685 <option value="commented" selected=(trigger_kind == "commented")>(t(lang, Key::TriggerCommented))</option>
686 <option value="deadline_set" selected=(trigger_kind == "deadline_set")>(t(lang, Key::TriggerDeadlineSet))</option>
687 <option value="deadline_cleared" selected=(trigger_kind == "deadline_cleared")>(t(lang, Key::TriggerDeadlineCleared))</option>
688 <option value="retitled" selected=(trigger_kind == "retitled")>(t(lang, Key::TriggerRetitled))</option>
689 <option value="linked" selected=(trigger_kind == "linked")>(t(lang, Key::TriggerLinked))</option>
690 <option value="unlinked" selected=(trigger_kind == "unlinked")>(t(lang, Key::TriggerUnlinked))</option>
691 <option value="deleted" selected=(trigger_kind == "deleted")>(t(lang, Key::TriggerDeleted))</option>
692 </select>
693 </label>
694 if trigger_kind == "status" {
695 <label class="rule-field">
696 <span class="field-label">(t(lang, Key::ColumnLabel))</span>
697 <select class="field-input" name="column_id">
698 <option value="" selected=(column_id.is_empty())>(t(lang, Key::AnyColumn))</option>
699 for column in columns {
700 <option value=(column.id.clone()) selected=(column.id == column_id)>(column.name.clone())</option>
701 }
702 </select>
703 </label>
704 } else {
705 <input type="hidden" name="column_id" value=(column_id)>
706 }
707 <label class="rule-field">
708 <span class="field-label">(t(lang, Key::SendLabel))</span>
709 <input
710 class="field-input"
711 type="text"
712 name="subject"
713 placeholder=(t(lang, Key::SubjectPlaceholder))
714 maxlength="120"
715 required=""
716 value=(subject)
717 >
718 </label>
719 <label class="rule-field">
720 <span class="field-label">(t(lang, Key::ToLabel))</span>
721 <select class="field-input" name="audience">
722 <option value="assignees" selected=(audience_kind == "assignees")>(t(lang, Key::AudienceAssignees))</option>
723 <option value="board" selected=(audience_kind == "board")>(t(lang, Key::AudienceBoard))</option>
724 <option value="creator" selected=(audience_kind == "creator")>(t(lang, Key::AudienceCreator))</option>
725 </select>
726 </label>
727 <div class="rule-field">
728 <span class="field-label">(t(lang, Key::BodyLabel))</span>
729 <label class="field-box">
730 <input type="checkbox" name="include_task_details" value="true" checked=(include_task_details)>
731 <span class="field-text">(t(lang, Key::TaskDetails))</span>
732 </label>
733 </div>
734 <div class="panel-foot">
735 if let Some(refusal) = refusal {
736 <span class="field-error">(refusal.message_in(lang))</span>
737 }
738 if is_edit {
739 <a class="quiet" href="/rules">(t(lang, Key::Cancel))</a>
740 }
741 <button class="primary" type="submit">(if is_edit { t(lang, Key::SaveRule) } else { t(lang, Key::AddRule) })</button>
742 </div>
743 </form>
744 }.boxed())
745}
746
747/// The "New rule" control and the form inside it. A `<details>` rather than
748/// anything script-driven, so a browser with no script can still open it and
749/// post the form.
750async fn composer<'a>(
751 cx: &'a Cx,
752 columns: &'a [ColumnChoice],
753 refusal: Option<&'a Refusal>,
754 lang: Lang,
755) -> Result<impl View + 'a> {
756 Ok(view! {
757 cx =>
758 <details class="rule-new">
759 <summary class="rule-new-open">(t(lang, Key::NewRule))</summary>
760 (topcoat::view::Child::new(rule_form(cx, columns, None, refusal, lang).await?))
761 </details>
762 }
763 .boxed())
764}
765
766/// One rule's row: the form in place of it when `editing`, its display
767/// otherwise.
768async fn rule_row<'a>(
769 cx: &'a Cx,
770 rule: &'a RuleLine,
771 columns: &'a [ColumnChoice],
772 editing: bool,
773 refusal: Option<&'a Refusal>,
774 lang: Lang,
775) -> Result<impl View + 'a> {
776 if editing {
777 return Ok(view! {
778 cx =>
779 <div class="rule-row">
780 (topcoat::view::Child::new(rule_form(cx, columns, Some(rule), refusal, lang).await?))
781 </div>
782 }.boxed());
783 }
784
785 let row_class = if rule.enabled {
786 "rule-row"
787 } else {
788 "rule-row rule-row-off"
789 };
790 let switch_class = if rule.enabled {
791 "rule-switch rule-switch-on"
792 } else {
793 "rule-switch"
794 };
795 let switch_label = if rule.enabled {
796 t(lang, Key::SwitchRuleOff)
797 } else {
798 t(lang, Key::SwitchRuleOn)
799 };
800 let stamp = rule
801 .last_sent
802 .as_ref()
803 .map(|moment| crate::i18n::last_sent_label(lang, moment))
804 .or_else(|| {
805 rule.last_fired
806 .as_ref()
807 .map(|moment| crate::i18n::last_fired_label(lang, moment))
808 })
809 .unwrap_or_else(|| t(lang, Key::NeverFired).to_string());
810
811 Ok(view! {
812 cx =>
813 <div class=(row_class)>
814 <form method="post" action="/api/set_rule_enabled" class="rule-switch-form">
815 <input type="hidden" name="rule_id" value=(rule.id.clone())>
816 <input type="hidden" name="enabled" value=((!rule.enabled).to_string())>
817 <button class=(switch_class) type="submit" title=(switch_label)>
818 <span class="rule-switch-knob"></span>
819 <span class="visually-hidden">(switch_label)</span>
820 </button>
821 </form>
822
823 <div class="rule-sentence">
824 <span>(rule.when.clone())</span>
825 // A trigger with no second half prints no term box. The box
826 // only exists to hold a word.
827 if let Some(what) = &rule.what {
828 <span class="rule-term">(what.clone())</span>
829 }
830 <span>(t(lang, Key::SendConnector))</span>
831 <span class="rule-term">(rule.subject.clone())</span>
832 <span>(t(lang, Key::ToConnector))</span>
833 <span class="rule-term">(rule.audience.clone())</span>
834 </div>
835
836 <span class="rule-stamp">(stamp)</span>
837
838 <a class="quiet" href=(format!("/rules?edit={}", rule.id)) title=(t(lang, Key::EditThisRule))>(t(lang, Key::EditLabel))</a>
839
840 <form method="post" action="/api/delete_rule">
841 <input type="hidden" name="rule_id" value=(rule.id.clone())>
842 <button class="quiet quiet-danger" type="submit" title=(t(lang, Key::DeleteThisRule))>(t(lang, Key::Delete))</button>
843 </form>
844 </div>
845 }.boxed())
846}
847
848#[page("/rules")]
849async fn rules_page(cx: &Cx) -> Result<impl View> {
850 let user = match require_admin(cx).await {
851 Ok(user) => user,
852 Err(refusal) => {
853 return Ok(view! {
854 <main class="scaffold-note">
855 <p>(refusal.message())</p>
856 <p><a href="/">(t(Lang::En, Key::BackToBoard))</a></p>
857 </main>
858 }
859 .boxed());
860 }
861 };
862 let lang = Lang::from_code(&user.language);
863 let store = store(cx).clone();
864 let snapshot = match snapshot_of(&store, &user).await {
865 Ok(snapshot) => snapshot,
866 Err(refusal) => {
867 return Ok(view! {
868 <main class="scaffold-note">
869 <p>(refusal.message_in(lang))</p>
870 <p><a href="/">(t(lang, Key::BackToBoard))</a></p>
871 </main>
872 }
873 .boxed());
874 }
875 };
876 let edit_id = query_params::<RulesQuery>(cx)?.edit.clone();
877 let create_refusal = refusal_of(cx, "create_rule");
878 let update_refusal = refusal_of(cx, "update_rule");
879
880 let me = crate::detail::Me::from(&user);
881 Ok(view! {
882 <header class="topbar">
883 (topcoat::view::Child::new(crate::layout::family_mark(cx).await?))
884 (topcoat::view::Child::new(crate::layout::topbar_nav(cx, crate::layout::NavPage::Rules, user.role, lang).await?))
885 <div class="spacer"></div>
886 (topcoat::view::Child::new(crate::layout::user_menu(cx, &me, lang).await?))
887 </header>
888
889 <div class="settings-shell">
890 <main class="settings-stage">
891 <div class="settings-head">
892 <h1 class="settings-title">(t(lang, Key::MailRules))</h1>
893 <span class="chip chip-admin">(t(lang, Key::AdminOnly))</span>
894 </div>
895
896 if !snapshot.sender_connected {
897 <p class="rules-quiet">
898 (t(lang, Key::NoSenderConnectedPrefix))
899 (" ")
900 <a href="/settings">(t(lang, Key::NavSettings))</a>
901 </p>
902 }
903
904 (topcoat::view::Child::new(composer(cx, &snapshot.columns, create_refusal.as_ref(), lang).await?))
905
906 <div class="rule-list">
907 for rule in &snapshot.rules {
908 (topcoat::view::Child::new(rule_row(cx, rule, &snapshot.columns, edit_id.as_deref() == Some(rule.id.as_str()), update_refusal.as_ref(), lang).await?))
909 }
910 if snapshot.rules.is_empty() {
911 <p class="rules-quiet">(t(lang, Key::NoRulesYet))</p>
912 }
913 </div>
914 </main>
915 (topcoat::view::Child::new(crate::dropdown::dropdown_script(cx).await?))
916 (topcoat::view::Child::new(crate::layout::escape_script(cx).await?))
917 </div>
918 }.boxed())
919}