forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

task.rs1386 lines, 47.5 KiBHistoryRawDownload
1//! The task modal (`docs/architecture.md` section 4, `docs/reference/old-inventory.md` 2.3): the card that
2//! `GET /?task=<key>` opens over the board, and every write the modal makes.
3//!
4//! Reads: the modal loads one task of this board by its key. A key that is unknown, deleted or on another
5//! board answers the board with a "not found" notice and `404`. A viewer sees the same content with no
6//! write control.
7//!
8//! Writes: every write is a form that carries the CSRF token and a `next` path (the modal's own URL). The
9//! gate is the same as the board's (`pages/tasks.rs`): a member with the write level, the token, then the
10//! change. A refused change re-renders the board with the modal open, the message above the fields, and
11//! the typed values kept, at `422`. An accepted change redirects (Post/Redirect/Get) to the modal of its
12//! task, with a notice. Each write bumps the board topic and the task topic (`live.rs`).
13//!
14//! Comments are checked by their own id: the store loads the comment, checks that its task is live and on
15//! this board, and only then asks `authz` whether this member may edit or delete it. A comment of a deleted
16//! task is not found.
17
18use std::collections::{HashMap, HashSet};
19use std::result::Result as StdResult;
20
21use iz_core::authz::{Action, authorize};
22use iz_core::clock::{MeetingInput, resolve_meeting, timestamp_of};
23use iz_core::limits::{COMMENT_MAX, DESCRIPTION_MAX, TITLE_MAX};
24use iz_core::store::board::Tag;
25use iz_core::store::members::Member;
26use iz_core::store::tasks::{NewTask, Task, TaskDetail, TaskEdit};
27use iz_core::zones::{parse_zone, utc_to_local};
28use jiff::civil::Date;
29use jiff::tz::TimeZone;
30use serde::Deserialize;
31use topcoat::Result;
32use topcoat::context::{Cx, app_context};
33use topcoat::router::content::Form;
34use topcoat::router::error::{forbidden, not_found, see_other};
35use topcoat::router::response::Response;
36use topcoat::router::{StatusCode, path_param_segment, route};
37
38use crate::auth::{CurrentMember, percent_encode, safe_next};
39use crate::i18n::board::{K as BK, t as bt};
40use crate::i18n::task::{K, activity_kind, t};
41use crate::i18n::{Lang, lang};
42use crate::live::Topic;
43use crate::pages::board::{BoardPage, board_url, load, pairs, query_of, render, the_board};
44use crate::pages::tasks::{answer_stop, writer};
45use crate::state::AppState;
46
47/// Rows of activity per page in the modal. Reason: the feed is a summary; older rows are one click away.
48const ACTIVITY_PAGE: usize = 20;
49
50/// The filters that the modal keeps in its own links, so the board behind it is the same one.
51const FILTER_KEYS: [&str; 4] = ["tag", "assignee", "sort", "q"];
52
53/// The fields of the edit form as typed, or as stored. A refused edit shows the typed values again.
54#[derive(Clone, Debug, Default)]
55pub struct EditValues {
56 /// The title.
57 pub title: String,
58 /// The description, as plain text.
59 pub description: String,
60 /// The project id.
61 pub tag: String,
62 /// The deadline day, `YYYY-MM-DD`, or empty.
63 pub deadline: String,
64 /// The meeting time in the viewer's zone, `HH:MM`, or empty.
65 pub time: String,
66}
67
68/// One comment as the modal shows it, with the rights of the viewer over it.
69pub struct CommentRow {
70 /// The comment id.
71 pub id: String,
72 /// The author's name.
73 pub author: String,
74 /// The body as stored (plain text).
75 pub body: String,
76 /// When it was written, in the viewer's zone, `YYYY-MM-DD HH:MM`.
77 pub when: String,
78 /// Whether it was edited after it was written.
79 pub edited: bool,
80 /// Whether the viewer may edit it (its author, while a member).
81 pub can_edit: bool,
82 /// Whether the viewer may delete it (its author, or an admin).
83 pub can_delete: bool,
84}
85
86/// One row of the activity feed.
87pub struct ActivityRow {
88 /// The sentence for the kind of event, in the viewer's language.
89 pub sentence: &'static str,
90 /// Who did it, by name (`-` for the system).
91 pub actor: String,
92 /// When, in the viewer's zone, `YYYY-MM-DD HH:MM`.
93 pub when: String,
94}
95
96/// One attachment as the modal lists it, with the links and rights of the viewer over it.
97pub struct FileRow {
98 /// The file name as uploaded.
99 pub name: String,
100 /// The size, as text.
101 pub size: String,
102 /// The uploader's name.
103 pub uploader: String,
104 /// When it was uploaded, in the viewer's zone.
105 pub when: String,
106 /// Whether the viewer can show it (has a preview).
107 pub viewable: bool,
108 /// The modal URL that opens its viewer.
109 pub view_url: String,
110 /// The URL that saves it.
111 pub download_url: String,
112 /// The form action that deletes it.
113 pub delete_action: String,
114 /// Whether the viewer may delete it.
115 pub can_delete: bool,
116}
117
118/// The task modal, as the board page shows it.
119pub struct TaskModal {
120 /// The attachments of the task, oldest first.
121 pub files: Vec<FileRow>,
122 /// The file open in the viewer (`?file=`), when there is one.
123 pub viewer: Option<crate::pages::files::FileView>,
124 /// The task with its tag, assignees, subtasks and links.
125 pub detail: TaskDetail,
126 /// Whether the viewer may change the task.
127 pub can_write: bool,
128 /// This modal's own URL: the board filters and `task=<key>`. Forms return here.
129 pub base: String,
130 /// The board with the same filters and no task: where the modal closes.
131 pub close: String,
132 /// The edit form's values: the stored ones, or the typed ones after a refusal.
133 pub edit: EditValues,
134 /// Enabled members who may be assigned and are not yet assigned here.
135 pub assignable: Vec<Member>,
136 /// Every other live task of the board, for the dependency and parent pickers.
137 pub options: Vec<Task>,
138 /// Whether the viewer watches the task.
139 pub watching: bool,
140 /// The live comments, oldest first.
141 pub comments: Vec<CommentRow>,
142 /// The newest page of the activity feed.
143 pub activity: Vec<ActivityRow>,
144 /// The URL of the next, older page of activity, when there is one.
145 pub older: Option<String>,
146 /// Whether the delete confirmation is open.
147 pub confirm_delete: bool,
148 /// The message of a refused write, shown above the fields.
149 pub error: Option<&'static str>,
150 /// The comment text typed in the composer, kept after a refusal.
151 pub comment_draft: String,
152}
153
154/// What a re-rendered modal starts from: the message of a refusal, the typed values, and the view options.
155#[derive(Default)]
156pub struct Draft {
157 /// The refusal to show.
158 pub error: Option<&'static str>,
159 /// The typed edit values, when the edit was refused.
160 pub edit: Option<EditValues>,
161 /// The typed comment, when the comment was refused.
162 pub comment: Option<String>,
163 /// Whether the delete confirmation is open (`?confirm=delete`).
164 pub confirm: bool,
165 /// The cursor of the activity page to show (`?before=`).
166 pub before: Option<String>,
167}
168
169/// The form of every modal write. Each field is optional on the wire; a missing one is empty.
170#[derive(Deserialize, Default)]
171pub struct ModalForm {
172 #[serde(default)]
173 csrf: String,
174 /// The modal URL the form was on.
175 #[serde(default)]
176 next: String,
177 #[serde(default)]
178 title: String,
179 #[serde(default)]
180 description: String,
181 /// The project id.
182 #[serde(default)]
183 tag: String,
184 #[serde(default)]
185 deadline: String,
186 /// The meeting time, `HH:MM`.
187 #[serde(default)]
188 time: String,
189 /// A comment body.
190 #[serde(default)]
191 body: String,
192 /// A member's id, for assign and unassign.
193 #[serde(default)]
194 sub: String,
195 /// `1` to watch, `0` to stop.
196 #[serde(default)]
197 on: String,
198 /// The parent task's id, or empty for none.
199 #[serde(default)]
200 parent: String,
201 /// The other task of a dependency.
202 #[serde(default)]
203 other: String,
204 /// `blocked_by` (this task waits for `other`) or `blocks` (`other` waits for this task).
205 #[serde(default)]
206 direction: String,
207}
208
209/// The modal's URL for `key`: the board filters of `query` and `task=<key>`, plus `extra`. Filters that are
210/// not in [`FILTER_KEYS`] are dropped, so a stale `confirm` or `before` never comes back.
211pub fn modal_url(query: Option<&str>, key: &str, extra: &[(&str, &str)]) -> String {
212 let mut parts: Vec<String> = pairs(query.unwrap_or(""))
213 .into_iter()
214 .filter(|(name, _)| FILTER_KEYS.contains(&name.as_str()))
215 .map(|(name, value)| format!("{name}={}", percent_encode(&value)))
216 .collect();
217 parts.push(format!("task={}", percent_encode(key)));
218 parts.extend(
219 extra
220 .iter()
221 .map(|(name, value)| format!("{name}={}", percent_encode(value))),
222 );
223 format!("/?{}", parts.join("&"))
224}
225
226/// The link to another task's modal from `close` (the board URL with the filters).
227pub fn task_link(close: &str, key: &str) -> String {
228 let separator = if close.contains('?') { '&' } else { '?' };
229 format!("{close}{separator}task={}", percent_encode(key))
230}
231
232/// The `task` value of a `next` path, when it names one.
233fn task_of(next: &str) -> Option<String> {
234 pairs(query_of(safe_next(Some(next))).unwrap_or(""))
235 .into_iter()
236 .find(|(name, _)| name == "task")
237 .map(|(_, value)| value)
238 .filter(|value| !value.is_empty())
239}
240
241/// Maps a store error to the framework's answer: a missing or hidden thing is `404`, a refused right is
242/// `403`, and anything else is a logged `500`.
243pub fn core_err(error: iz_core::Error) -> topcoat::Error {
244 match error {
245 iz_core::Error::NotFound => not_found().into(),
246 iz_core::Error::Forbidden(_) => forbidden().into(),
247 other => other.into(),
248 }
249}
250
251/// The zone of the signed-in member; UTC when the stored name does not parse.
252fn zone_of(me: &CurrentMember) -> TimeZone {
253 parse_zone(&me.member.zoneinfo).unwrap_or(TimeZone::UTC)
254}
255
256/// A stored UTC stamp in `zone` as `YYYY-MM-DD HH:MM`. Empty when the stamp does not parse.
257pub(crate) fn local_text(stamp: &str, zone: &TimeZone) -> String {
258 match timestamp_of(stamp) {
259 Ok(at) => {
260 let local = utc_to_local(zone, at);
261 format!(
262 "{:04}-{:02}-{:02} {:02}:{:02}",
263 local.year(),
264 local.month(),
265 local.day(),
266 local.hour(),
267 local.minute()
268 )
269 }
270 Err(_) => String::new(),
271 }
272}
273
274/// A stored UTC stamp in `zone` as `HH:MM`, for the time field.
275fn clock_text(stamp: &str, zone: &TimeZone) -> String {
276 match timestamp_of(stamp) {
277 Ok(at) => {
278 let local = utc_to_local(zone, at);
279 format!("{:02}:{:02}", local.hour(), local.minute())
280 }
281 Err(_) => String::new(),
282 }
283}
284
285/// Reads `HH:MM` (one or two digits per part). `None` for anything else, or an hour or minute out of range.
286fn parse_clock(text: &str) -> Option<(u8, u8)> {
287 let (hour, minute) = text.trim().split_once(':')?;
288 if hour.is_empty() || hour.len() > 2 || minute.len() != 2 {
289 return None;
290 }
291 let hour: u8 = hour.parse().ok()?;
292 let minute: u8 = minute.parse().ok()?;
293 (hour < 24 && minute < 60).then_some((hour, minute))
294}
295
296/// Checks the edit form and turns it into the store's input. The first problem found is the message. The
297/// deadline and the meeting time are resolved in the viewer's zone (`clock.rs`).
298fn edit_input(
299 form: &ModalForm,
300 tags: &[Tag],
301 zone: &TimeZone,
302 language: Lang,
303) -> StdResult<TaskEdit, &'static str> {
304 let title = form.title.trim();
305 if title.is_empty() || title.chars().count() > TITLE_MAX {
306 return Err(bt(language, BK::TitleInvalid));
307 }
308 if form.description.chars().count() > DESCRIPTION_MAX {
309 return Err(t(language, K::DescriptionTooLong));
310 }
311 if !tags.iter().any(|tag| tag.id == form.tag) {
312 return Err(t(language, K::ErrProject));
313 }
314 let day = match form.deadline.trim() {
315 "" => None,
316 text => Some(
317 text.parse::<Date>()
318 .map_err(|_| t(language, K::ErrDeadline))?,
319 ),
320 };
321 let clock = match form.time.trim() {
322 "" => None,
323 text => Some(parse_clock(text).ok_or(t(language, K::ErrTime))?),
324 };
325 let (hour, minute) = match clock {
326 Some((hour, minute)) => (Some(hour), Some(minute)),
327 None => (None, None),
328 };
329 let (deadline, meeting_at) = resolve_meeting(MeetingInput { day, hour, minute }, zone)
330 .map_err(|_| t(language, K::ErrMeeting))?;
331 Ok(TaskEdit {
332 title: title.to_owned(),
333 description: form.description.clone(),
334 tag_id: form.tag.clone(),
335 deadline,
336 meeting_at,
337 })
338}
339
340/// The direction of a dependency as the stored pair: `(blocked, blocking)`. `None` for an unknown word.
341fn link_pair<'a>(task: &'a str, other: &'a str, direction: &str) -> Option<(&'a str, &'a str)> {
342 match direction {
343 "blocked_by" => Some((task, other)),
344 "blocks" => Some((other, task)),
345 _ => None,
346 }
347}
348
349/// Loads the modal of `key` into `page`. Returns `false` when the task does not exist on this board (or is
350/// deleted); the page is then left as it was.
351pub async fn open(
352 state: &AppState,
353 me: &CurrentMember,
354 page: &mut BoardPage,
355 key: &str,
356 query: Option<&str>,
357 draft: Draft,
358) -> Result<bool> {
359 let store = &state.store;
360 let board = the_board(store).await?;
361 let detail = match store.task_detail(&board.id, key).await {
362 Ok(detail) => detail,
363 Err(iz_core::Error::NotFound) => return Ok(false),
364 Err(error) => return Err(core_err(error)),
365 };
366 let task_id = detail.task.id.clone();
367 let zone = page.zone.clone();
368 let names: HashMap<String, String> = store
369 .list_members()
370 .await
371 .map_err(core_err)?
372 .into_iter()
373 .map(|member| (member.sub, member.name))
374 .collect();
375 let name_of = |sub: &str| names.get(sub).cloned().unwrap_or_else(|| "-".to_owned());
376 let comments = store
377 .list_comments(&board.id, &task_id)
378 .await
379 .map_err(core_err)?;
380 let before = draft.before.filter(|cursor| cursor.contains('~'));
381 let feed = store
382 .list_task_page(&board.id, &task_id, before.as_deref(), ACTIVITY_PAGE)
383 .await
384 .map_err(core_err)?;
385 let watching = store
386 .is_watching(&task_id, &me.member.sub)
387 .await
388 .map_err(core_err)?;
389 let options: Vec<Task> = store
390 .task_options(&board.id)
391 .await
392 .map_err(core_err)?
393 .into_iter()
394 .filter(|other| other.id != task_id)
395 .collect();
396 let assigned: HashSet<&str> = detail.assignees.iter().map(|a| a.sub.as_str()).collect();
397 let assignable: Vec<Member> = page
398 .members
399 .iter()
400 .filter(|member| !assigned.contains(member.sub.as_str()))
401 .cloned()
402 .collect();
403 let can_write = page.can_write;
404 let comment_rows: Vec<CommentRow> = comments
405 .into_iter()
406 .map(|comment| {
407 let author = comment.author.clone();
408 CommentRow {
409 can_edit: can_write
410 && authorize(
411 &me.actor(),
412 &Action::EditComment {
413 author: author.clone(),
414 },
415 )
416 .is_ok(),
417 can_delete: can_write
418 && authorize(
419 &me.actor(),
420 &Action::DeleteComment {
421 author: author.clone(),
422 },
423 )
424 .is_ok(),
425 author: name_of(&author),
426 when: local_text(&comment.created_at, &zone),
427 edited: comment.edited_at.is_some(),
428 id: comment.id,
429 body: comment.body,
430 }
431 })
432 .collect();
433 let activity: Vec<ActivityRow> = feed
434 .items
435 .iter()
436 .map(|item| ActivityRow {
437 sentence: activity_kind(page.lang, &item.kind),
438 actor: item
439 .actor
440 .as_deref()
441 .map_or_else(|| "-".to_owned(), name_of),
442 when: local_text(&item.at, &zone),
443 })
444 .collect();
445 let base = modal_url(query, key, &[]);
446 let older = feed
447 .next_cursor
448 .map(|cursor| format!("{base}&before={}", percent_encode(&cursor)));
449 let stored = EditValues {
450 title: detail.task.title.clone(),
451 description: detail.task.description.clone(),
452 tag: detail.task.tag_id.clone(),
453 deadline: detail
454 .task
455 .deadline
456 .map(|day| day.to_string())
457 .unwrap_or_default(),
458 time: detail
459 .task
460 .meeting_at
461 .as_deref()
462 .map(|stamp| clock_text(stamp, &zone))
463 .unwrap_or_default(),
464 };
465 let attachments = store
466 .list_attachments(&board.id, &task_id)
467 .await
468 .map_err(core_err)?;
469 let files =
470 crate::pages::files::file_rows(&attachments, key, query, me, can_write, &names, &zone);
471 let modal = TaskModal {
472 files,
473 viewer: None,
474 can_write,
475 close: board_url(&page.filters, &[]),
476 base,
477 edit: draft.edit.unwrap_or(stored),
478 assignable,
479 options,
480 watching,
481 comments: comment_rows,
482 activity,
483 older,
484 confirm_delete: draft.confirm && can_write,
485 error: draft.error,
486 comment_draft: draft.comment.unwrap_or_default(),
487 detail,
488 };
489 page.modal = Some(modal);
490 Ok(true)
491}
492
493/// A write that passed the gate and found its task on this board.
494struct Begun {
495 me: CurrentMember,
496 lang: Lang,
497 board_id: String,
498 detail: TaskDetail,
499}
500
501/// The gate of a write: the member with the write level and the CSRF token, then the board. A refusal of
502/// the gate is answered as the board's writes answer theirs; the inner `Err` carries that answer.
503async fn gate(
504 cx: &Cx,
505 csrf: &str,
506 next: &str,
507) -> Result<StdResult<(CurrentMember, Lang, String), Response>> {
508 let state = app_context::<AppState>(cx);
509 let me = match writer(cx, csrf).await {
510 Ok(me) => me,
511 Err(stop) => {
512 return Ok(Err(
513 answer_stop(cx, stop, false, next, lang(cx, None)).await?
514 ));
515 }
516 };
517 let language = lang(cx, me.member.locale_override.as_deref());
518 let board = the_board(&state.store).await?;
519 Ok(Ok((me, language, board.id)))
520}
521
522/// The gate of a write that names its task in the path.
523async fn gate_task(cx: &Cx, form: &ModalForm, task_id: &str) -> Result<StdResult<Begun, Response>> {
524 let state = app_context::<AppState>(cx);
525 let (me, language, board_id) = match gate(cx, &form.csrf, &form.next).await? {
526 Ok(found) => found,
527 Err(response) => return Ok(Err(response)),
528 };
529 let detail = state
530 .store
531 .task_detail(&board_id, task_id)
532 .await
533 .map_err(core_err)?;
534 Ok(Ok(Begun {
535 me,
536 lang: language,
537 board_id,
538 detail,
539 }))
540}
541
542/// Re-renders the board with the modal of `key` open, the refusal above its fields, and `422`. When the
543/// task is gone the board answers `404` with its "not found" notice.
544pub(crate) async fn refuse(
545 cx: &Cx,
546 me: &CurrentMember,
547 language: Lang,
548 next: &str,
549 key: &str,
550 draft: Draft,
551) -> Result<Response> {
552 let state = app_context::<AppState>(cx);
553 let query = query_of(safe_next(Some(next)));
554 let mut page = load(&state.store, me, language, query).await?;
555 let found = open(state, me, &mut page, key, query, draft).await?;
556 let status = if found {
557 StatusCode::UNPROCESSABLE_ENTITY
558 } else {
559 page.alert = Some(BK::TaskNotFound);
560 StatusCode::NOT_FOUND
561 };
562 render(cx, &page, Some(status)).await
563}
564
565/// A `Draft` that only shows a refusal.
566fn refusal(message: &'static str) -> Draft {
567 Draft {
568 error: Some(message),
569 ..Draft::default()
570 }
571}
572
573/// Tells every open view of the board and of the task that something changed.
574pub(crate) fn bump(state: &AppState, board_id: &str, task_id: &str) {
575 state.live.bump(&Topic::Board(board_id.to_owned()));
576 state.live.bump(&Topic::Task(task_id.to_owned()));
577}
578
579/// Answers a write that went through: the modal of `key` with the saved notice, or the board when there is
580/// no task to return to.
581pub(crate) fn back(next: &str, key: Option<&str>) -> Result<Response> {
582 let target = match key {
583 Some(key) => modal_url(query_of(safe_next(Some(next))), key, &[("notice", "saved")]),
584 None => "/".to_owned(),
585 };
586 Err(see_other(target).into())
587}
588
589/// `POST /tasks/{id}/edit`: the title, description, project, deadline and meeting time.
590#[route(POST "/tasks/{id}/edit")]
591async fn edit_task(cx: &Cx, form: Option<Form<ModalForm>>) -> Result<Response> {
592 let state = app_context::<AppState>(cx);
593 let form = form.map(|Form(form)| form).unwrap_or_default();
594 let task_id = path_param_segment(cx, "id").to_owned();
595 let begun = match gate_task(cx, &form, &task_id).await? {
596 Ok(begun) => begun,
597 Err(response) => return Ok(response),
598 };
599 let key = begun.detail.task.key.clone();
600 let zone = zone_of(&begun.me);
601 let tags = state.store.tags(&begun.board_id).await.map_err(core_err)?;
602 let typed = EditValues {
603 title: form.title.clone(),
604 description: form.description.clone(),
605 tag: form.tag.clone(),
606 deadline: form.deadline.clone(),
607 time: form.time.clone(),
608 };
609 let edit = match edit_input(&form, &tags, &zone, begun.lang) {
610 Ok(edit) => edit,
611 Err(message) => {
612 let draft = Draft {
613 edit: Some(typed),
614 ..refusal(message)
615 };
616 return refuse(cx, &begun.me, begun.lang, &form.next, &key, draft).await;
617 }
618 };
619 match state
620 .store
621 .edit_task(&begun.board_id, &task_id, edit, &begun.me.member.sub)
622 .await
623 {
624 Ok(_) => {
625 bump(state, &begun.board_id, &task_id);
626 back(&form.next, Some(key.as_str()))
627 }
628 Err(iz_core::Error::Invalid(_)) => {
629 let draft = Draft {
630 edit: Some(typed),
631 ..refusal(bt(begun.lang, BK::InvalidForm))
632 };
633 refuse(cx, &begun.me, begun.lang, &form.next, &key, draft).await
634 }
635 Err(error) => Err(core_err(error)),
636 }
637}
638
639/// `POST /tasks/{id}/assign`: adds one member. The store refuses anyone who is not an enabled admin or
640/// member.
641#[route(POST "/tasks/{id}/assign")]
642async fn assign(cx: &Cx, form: Option<Form<ModalForm>>) -> Result<Response> {
643 let state = app_context::<AppState>(cx);
644 let form = form.map(|Form(form)| form).unwrap_or_default();
645 let task_id = path_param_segment(cx, "id").to_owned();
646 let begun = match gate_task(cx, &form, &task_id).await? {
647 Ok(begun) => begun,
648 Err(response) => return Ok(response),
649 };
650 let key = begun.detail.task.key.clone();
651 let sub = form.sub.trim().to_owned();
652 if sub.is_empty() {
653 return refuse(
654 cx,
655 &begun.me,
656 begun.lang,
657 &form.next,
658 &key,
659 refusal(t(begun.lang, K::ErrAssignee)),
660 )
661 .await;
662 }
663 match state
664 .store
665 .assign(
666 &begun.board_id,
667 &task_id,
668 std::slice::from_ref(&sub),
669 &begun.me.member.sub,
670 )
671 .await
672 {
673 Ok(()) => {
674 bump(state, &begun.board_id, &task_id);
675 state.live.bump(&Topic::Person(sub.clone()));
676 back(&form.next, Some(key.as_str()))
677 }
678 Err(iz_core::Error::Invalid(_)) => {
679 refuse(
680 cx,
681 &begun.me,
682 begun.lang,
683 &form.next,
684 &key,
685 refusal(t(begun.lang, K::ErrAssignee)),
686 )
687 .await
688 }
689 Err(error) => Err(core_err(error)),
690 }
691}
692
693/// `POST /tasks/{id}/unassign`: removes one member. Removing someone who is not assigned changes nothing.
694#[route(POST "/tasks/{id}/unassign")]
695async fn unassign(cx: &Cx, form: Option<Form<ModalForm>>) -> Result<Response> {
696 let state = app_context::<AppState>(cx);
697 let form = form.map(|Form(form)| form).unwrap_or_default();
698 let task_id = path_param_segment(cx, "id").to_owned();
699 let begun = match gate_task(cx, &form, &task_id).await? {
700 Ok(begun) => begun,
701 Err(response) => return Ok(response),
702 };
703 let key = begun.detail.task.key.clone();
704 state
705 .store
706 .unassign(
707 &begun.board_id,
708 &task_id,
709 &[form.sub.trim().to_owned()],
710 &begun.me.member.sub,
711 )
712 .await
713 .map_err(core_err)?;
714 bump(state, &begun.board_id, &task_id);
715 state.live.bump(&Topic::Person(form.sub.trim().to_owned()));
716 back(&form.next, Some(key.as_str()))
717}
718
719/// `POST /tasks/{id}/watch`: starts (`on=1`) or stops (`on=0`) watching the task, for the viewer.
720#[route(POST "/tasks/{id}/watch")]
721async fn watch(cx: &Cx, form: Option<Form<ModalForm>>) -> Result<Response> {
722 let state = app_context::<AppState>(cx);
723 let form = form.map(|Form(form)| form).unwrap_or_default();
724 let task_id = path_param_segment(cx, "id").to_owned();
725 let begun = match gate_task(cx, &form, &task_id).await? {
726 Ok(begun) => begun,
727 Err(response) => return Ok(response),
728 };
729 let key = begun.detail.task.key.clone();
730 let on = match form.on.trim() {
731 "1" => true,
732 "0" => false,
733 _ => {
734 return refuse(
735 cx,
736 &begun.me,
737 begun.lang,
738 &form.next,
739 &key,
740 refusal(bt(begun.lang, BK::InvalidForm)),
741 )
742 .await;
743 }
744 };
745 state
746 .store
747 .set_watch(&begun.board_id, &task_id, &begun.me.member.sub, on)
748 .await
749 .map_err(core_err)?;
750 bump(state, &begun.board_id, &task_id);
751 back(&form.next, Some(key.as_str()))
752}
753
754/// `POST /tasks/{id}/subtasks`: creates a subtask under this task, in its column and project.
755#[route(POST "/tasks/{id}/subtasks")]
756async fn add_subtask(cx: &Cx, form: Option<Form<ModalForm>>) -> Result<Response> {
757 let state = app_context::<AppState>(cx);
758 let form = form.map(|Form(form)| form).unwrap_or_default();
759 let task_id = path_param_segment(cx, "id").to_owned();
760 let begun = match gate_task(cx, &form, &task_id).await? {
761 Ok(begun) => begun,
762 Err(response) => return Ok(response),
763 };
764 let key = begun.detail.task.key.clone();
765 let title = form.title.trim().to_owned();
766 if title.is_empty() || title.chars().count() > TITLE_MAX {
767 let message = t(begun.lang, K::ErrSubtaskTitle);
768 return refuse(
769 cx,
770 &begun.me,
771 begun.lang,
772 &form.next,
773 &key,
774 refusal(message),
775 )
776 .await;
777 }
778 if begun.detail.task.parent_id.is_some() {
779 let message = t(begun.lang, K::ErrParent);
780 return refuse(
781 cx,
782 &begun.me,
783 begun.lang,
784 &form.next,
785 &key,
786 refusal(message),
787 )
788 .await;
789 }
790 let input = NewTask {
791 title,
792 description: String::new(),
793 column_id: begun.detail.task.column_id.clone(),
794 tag_id: begun.detail.task.tag_id.clone(),
795 deadline: None,
796 meeting_at: None,
797 assignees: Vec::new(),
798 parent_id: Some(task_id.clone()),
799 link: None,
800 };
801 match state
802 .store
803 .create_task(&begun.board_id, input, &begun.me.member.sub)
804 .await
805 {
806 Ok(_) => {
807 bump(state, &begun.board_id, &task_id);
808 back(&form.next, Some(key.as_str()))
809 }
810 Err(iz_core::Error::Invalid(_)) => {
811 let message = t(begun.lang, K::ErrParent);
812 refuse(
813 cx,
814 &begun.me,
815 begun.lang,
816 &form.next,
817 &key,
818 refusal(message),
819 )
820 .await
821 }
822 Err(error) => Err(core_err(error)),
823 }
824}
825
826/// `POST /tasks/{id}/parent`: makes this task a subtask of `parent`, or a top-level task when `parent` is
827/// empty. One level only; the store refuses the rest.
828#[route(POST "/tasks/{id}/parent")]
829async fn set_parent(cx: &Cx, form: Option<Form<ModalForm>>) -> Result<Response> {
830 let state = app_context::<AppState>(cx);
831 let form = form.map(|Form(form)| form).unwrap_or_default();
832 let task_id = path_param_segment(cx, "id").to_owned();
833 let begun = match gate_task(cx, &form, &task_id).await? {
834 Ok(begun) => begun,
835 Err(response) => return Ok(response),
836 };
837 let key = begun.detail.task.key.clone();
838 let parent = form.parent.trim();
839 let parent = (!parent.is_empty()).then_some(parent);
840 match state
841 .store
842 .set_parent(&begun.board_id, &task_id, parent, &begun.me.member.sub)
843 .await
844 {
845 Ok(()) => {
846 bump(state, &begun.board_id, &task_id);
847 back(&form.next, Some(key.as_str()))
848 }
849 Err(iz_core::Error::Conflict(_)) => {
850 let message = t(begun.lang, K::ErrParentHasChildren);
851 refuse(
852 cx,
853 &begun.me,
854 begun.lang,
855 &form.next,
856 &key,
857 refusal(message),
858 )
859 .await
860 }
861 Err(iz_core::Error::Invalid(_)) => {
862 let message = t(begun.lang, K::ErrParent);
863 refuse(
864 cx,
865 &begun.me,
866 begun.lang,
867 &form.next,
868 &key,
869 refusal(message),
870 )
871 .await
872 }
873 Err(error) => Err(core_err(error)),
874 }
875}
876
877/// `POST /tasks/{id}/links`: adds a dependency with `other`. A cycle is refused with its own message.
878#[route(POST "/tasks/{id}/links")]
879async fn add_link(cx: &Cx, form: Option<Form<ModalForm>>) -> Result<Response> {
880 let state = app_context::<AppState>(cx);
881 let form = form.map(|Form(form)| form).unwrap_or_default();
882 let task_id = path_param_segment(cx, "id").to_owned();
883 let begun = match gate_task(cx, &form, &task_id).await? {
884 Ok(begun) => begun,
885 Err(response) => return Ok(response),
886 };
887 let key = begun.detail.task.key.clone();
888 let other = form.other.trim().to_owned();
889 if other.is_empty() {
890 let message = t(begun.lang, K::ErrOtherTask);
891 return refuse(
892 cx,
893 &begun.me,
894 begun.lang,
895 &form.next,
896 &key,
897 refusal(message),
898 )
899 .await;
900 }
901 let Some((blocked, blocking)) = link_pair(&task_id, &other, form.direction.trim()) else {
902 let message = t(begun.lang, K::ErrDirection);
903 return refuse(
904 cx,
905 &begun.me,
906 begun.lang,
907 &form.next,
908 &key,
909 refusal(message),
910 )
911 .await;
912 };
913 match state
914 .store
915 .add_dependency(&begun.board_id, blocked, blocking, &begun.me.member.sub)
916 .await
917 {
918 Ok(()) => {
919 bump(state, &begun.board_id, &task_id);
920 state.live.bump(&Topic::Task(other.clone()));
921 back(&form.next, Some(key.as_str()))
922 }
923 Err(iz_core::Error::Conflict(_)) => {
924 let message = t(begun.lang, K::ErrCycle);
925 refuse(
926 cx,
927 &begun.me,
928 begun.lang,
929 &form.next,
930 &key,
931 refusal(message),
932 )
933 .await
934 }
935 Err(iz_core::Error::Invalid(_)) => {
936 let message = t(begun.lang, K::ErrSelf);
937 refuse(
938 cx,
939 &begun.me,
940 begun.lang,
941 &form.next,
942 &key,
943 refusal(message),
944 )
945 .await
946 }
947 Err(iz_core::Error::NotFound) => {
948 let message = t(begun.lang, K::ErrOtherTask);
949 refuse(
950 cx,
951 &begun.me,
952 begun.lang,
953 &form.next,
954 &key,
955 refusal(message),
956 )
957 .await
958 }
959 Err(error) => Err(core_err(error)),
960 }
961}
962
963/// `POST /tasks/{id}/links/remove`: clears a dependency (a soft clear: the history stays).
964#[route(POST "/tasks/{id}/links/remove")]
965async fn remove_link(cx: &Cx, form: Option<Form<ModalForm>>) -> Result<Response> {
966 let state = app_context::<AppState>(cx);
967 let form = form.map(|Form(form)| form).unwrap_or_default();
968 let task_id = path_param_segment(cx, "id").to_owned();
969 let begun = match gate_task(cx, &form, &task_id).await? {
970 Ok(begun) => begun,
971 Err(response) => return Ok(response),
972 };
973 let key = begun.detail.task.key.clone();
974 let other = form.other.trim().to_owned();
975 let Some((blocked, blocking)) = link_pair(&task_id, &other, form.direction.trim()) else {
976 let message = t(begun.lang, K::ErrDirection);
977 return refuse(
978 cx,
979 &begun.me,
980 begun.lang,
981 &form.next,
982 &key,
983 refusal(message),
984 )
985 .await;
986 };
987 match state
988 .store
989 .clear_dependency(&begun.board_id, blocked, blocking, &begun.me.member.sub)
990 .await
991 {
992 Ok(()) | Err(iz_core::Error::NotFound) => {
993 bump(state, &begun.board_id, &task_id);
994 state.live.bump(&Topic::Task(other.clone()));
995 back(&form.next, Some(key.as_str()))
996 }
997 Err(error) => Err(core_err(error)),
998 }
999}
1000
1001/// `POST /tasks/{id}/comments`: posts a comment on the task.
1002#[route(POST "/tasks/{id}/comments")]
1003async fn add_comment(cx: &Cx, form: Option<Form<ModalForm>>) -> Result<Response> {
1004 let state = app_context::<AppState>(cx);
1005 let form = form.map(|Form(form)| form).unwrap_or_default();
1006 let task_id = path_param_segment(cx, "id").to_owned();
1007 let begun = match gate_task(cx, &form, &task_id).await? {
1008 Ok(begun) => begun,
1009 Err(response) => return Ok(response),
1010 };
1011 let key = begun.detail.task.key.clone();
1012 let body = form.body.trim().to_owned();
1013 if body.is_empty() || body.chars().count() > COMMENT_MAX {
1014 let draft = Draft {
1015 comment: Some(form.body.clone()),
1016 ..refusal(t(begun.lang, K::ErrComment))
1017 };
1018 return refuse(cx, &begun.me, begun.lang, &form.next, &key, draft).await;
1019 }
1020 match state
1021 .store
1022 .add_comment(&begun.board_id, &task_id, &begun.me.member.sub, &body)
1023 .await
1024 {
1025 Ok(_) => {
1026 bump(state, &begun.board_id, &task_id);
1027 back(&form.next, Some(key.as_str()))
1028 }
1029 Err(error) => Err(core_err(error)),
1030 }
1031}
1032
1033/// `POST /comments/{id}/edit`: edits a comment. Only its author may, and only while a member. The comment
1034/// is checked by its own id (live, on this board, its task live), then by `authz`.
1035#[route(POST "/comments/{id}/edit")]
1036async fn edit_comment(cx: &Cx, form: Option<Form<ModalForm>>) -> Result<Response> {
1037 let state = app_context::<AppState>(cx);
1038 let form = form.map(|Form(form)| form).unwrap_or_default();
1039 let comment_id = path_param_segment(cx, "id").to_owned();
1040 let (me, language, board_id) = match gate(cx, &form.csrf, &form.next).await? {
1041 Ok(found) => found,
1042 Err(response) => return Ok(response),
1043 };
1044 let key = task_of(&form.next);
1045 let body = form.body.trim().to_owned();
1046 if body.is_empty() || body.chars().count() > COMMENT_MAX {
1047 let Some(key) = key else {
1048 return Err(not_found().into());
1049 };
1050 let draft = Draft {
1051 comment: Some(form.body.clone()),
1052 ..refusal(t(language, K::ErrComment))
1053 };
1054 return refuse(cx, &me, language, &form.next, &key, draft).await;
1055 }
1056 match state
1057 .store
1058 .edit_comment(&board_id, &comment_id, &me.actor(), &body)
1059 .await
1060 {
1061 Ok(comment) => {
1062 bump(state, &board_id, &comment.task_id);
1063 back(&form.next, key.as_deref())
1064 }
1065 Err(error) => Err(core_err(error)),
1066 }
1067}
1068
1069/// `POST /comments/{id}/delete`: deletes a comment. Its author (while a member) or an admin may.
1070#[route(POST "/comments/{id}/delete")]
1071async fn delete_comment(cx: &Cx, form: Option<Form<ModalForm>>) -> Result<Response> {
1072 let state = app_context::<AppState>(cx);
1073 let form = form.map(|Form(form)| form).unwrap_or_default();
1074 let comment_id = path_param_segment(cx, "id").to_owned();
1075 let (me, _language, board_id) = match gate(cx, &form.csrf, &form.next).await? {
1076 Ok(found) => found,
1077 Err(response) => return Ok(response),
1078 };
1079 let key = task_of(&form.next);
1080 match state
1081 .store
1082 .delete_comment(&board_id, &comment_id, &me.actor())
1083 .await
1084 {
1085 Ok(task_id) => {
1086 bump(state, &board_id, &task_id);
1087 back(&form.next, key.as_deref())
1088 }
1089 Err(error) => Err(core_err(error)),
1090 }
1091}
1092
1093#[cfg(test)]
1094mod tests {
1095 use super::*;
1096
1097 #[test]
1098 fn modal_url_keeps_filters_and_drops_the_rest() {
1099 assert_eq!(
1100 modal_url(Some("tag=a b&confirm=delete&sort=title&q=x"), "IZ-4", &[]),
1101 "/?tag=a%20b&sort=title&q=x&task=IZ-4"
1102 );
1103 assert_eq!(
1104 modal_url(None, "IZ-4", &[("before", "2026~01")]),
1105 "/?task=IZ-4&before=2026~01"
1106 );
1107 }
1108
1109 #[test]
1110 fn clock_text_is_hours_and_minutes() {
1111 assert_eq!(parse_clock("09:30"), Some((9, 30)));
1112 assert_eq!(parse_clock("9:30"), Some((9, 30)));
1113 assert_eq!(parse_clock("24:00"), None);
1114 assert_eq!(parse_clock("09:60"), None);
1115 assert_eq!(parse_clock("0930"), None);
1116 }
1117
1118 #[test]
1119 fn a_dependency_names_its_blocked_and_blocking_side() {
1120 assert_eq!(link_pair("a", "b", "blocked_by"), Some(("a", "b")));
1121 assert_eq!(link_pair("a", "b", "blocks"), Some(("b", "a")));
1122 assert_eq!(link_pair("a", "b", "other"), None);
1123 }
1124
1125 #[test]
1126 fn a_return_path_names_its_task_only_when_local() {
1127 assert_eq!(task_of("/?task=IZ-4&tag=x").as_deref(), Some("IZ-4"));
1128 assert_eq!(task_of("//evil.example/?task=IZ-4"), None);
1129 }
1130}
1131
1132#[cfg(test)]
1133mod render_tests {
1134 use http::header::{CONTENT_TYPE, COOKIE};
1135 use iz_core::authz::Role;
1136 use iz_core::store::tasks::{NewTask, TaskEdit};
1137 use topcoat::router::{Body, to_bytes};
1138
1139 use super::*;
1140 use crate::boot::{router, test_state};
1141 use crate::pages::board::{cookie_of, one_card, sign_in_as};
1142 use crate::state::AppState;
1143
1144 const AUTHOR: &str = "01ADAAAAAAAAAAAAAAAAAAAAAA";
1145 const OTHER: &str = "01BOAAAAAAAAAAAAAAAAAAAAAA";
1146 const VIEWER: &str = "01VIAAAAAAAAAAAAAAAAAAAAAA";
1147
1148 /// Sends one request and returns its status and body as text.
1149 async fn send(state: &AppState, request: http::Request<Body>) -> (u16, String) {
1150 let response = router(state.clone()).handle(request).await;
1151 let status = response.status().as_u16();
1152 let bytes = to_bytes(response.into_body(), 1024 * 1024)
1153 .await
1154 .expect("body");
1155 (status, String::from_utf8_lossy(&bytes).into_owned())
1156 }
1157
1158 /// A form POST with the session's cookie.
1159 fn post(path: &str, token: &str, body: String) -> http::Request<Body> {
1160 http::Request::post(path)
1161 .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
1162 .header(COOKIE, cookie_of(token))
1163 .body(Body::from(body))
1164 .expect("request")
1165 }
1166
1167 /// A GET with the session's cookie.
1168 fn get(path: &str, token: &str) -> http::Request<Body> {
1169 http::Request::get(path)
1170 .header(COOKIE, cookie_of(token))
1171 .body(Body::empty())
1172 .expect("request")
1173 }
1174
1175 /// The key of a task, read through the store.
1176 async fn key_of(state: &AppState, task_id: &str) -> String {
1177 let board = state.store.board().await.expect("board").expect("some");
1178 state
1179 .store
1180 .task_detail(&board.id, task_id)
1181 .await
1182 .expect("detail")
1183 .task
1184 .key
1185 }
1186
1187 /// The modal URL of a task, as a form carries it.
1188 fn next_of(key: &str) -> String {
1189 percent_encode(&modal_url(None, key, &[]))
1190 }
1191
1192 /// A viewer's comment is refused with `403`, and nothing is stored.
1193 #[tokio::test]
1194 async fn a_viewer_cannot_comment() {
1195 let (_dir, state) = test_state().await;
1196 sign_in_as(&state, AUTHOR, Role::Member).await;
1197 let (task_id, _) = one_card(&state, "Milk", AUTHOR).await;
1198 let (token, csrf) = sign_in_as(&state, VIEWER, Role::Viewer).await;
1199 let key = key_of(&state, &task_id).await;
1200 let body = format!("csrf={csrf}&next={}&body=hello", next_of(&key));
1201 let (status, _) = send(
1202 &state,
1203 post(&format!("/tasks/{task_id}/comments"), &token, body),
1204 )
1205 .await;
1206 assert_eq!(status, 403);
1207 let board = state.store.board().await.expect("board").expect("some");
1208 let comments = state
1209 .store
1210 .list_comments(&board.id, &task_id)
1211 .await
1212 .expect("comments");
1213 assert!(comments.is_empty());
1214 }
1215
1216 /// Another member cannot edit someone else's comment: `403`, and the body stays as it was.
1217 #[tokio::test]
1218 async fn another_member_cannot_edit_a_comment() {
1219 let (_dir, state) = test_state().await;
1220 sign_in_as(&state, AUTHOR, Role::Member).await;
1221 sign_in_as(&state, OTHER, Role::Member).await;
1222 let (task_id, _) = one_card(&state, "Milk", AUTHOR).await;
1223 let board = state.store.board().await.expect("board").expect("some");
1224 let comment = state
1225 .store
1226 .add_comment(&board.id, &task_id, AUTHOR, "mine")
1227 .await
1228 .expect("comment");
1229 let (token, csrf) = sign_in_as(&state, OTHER, Role::Member).await;
1230 let key = key_of(&state, &task_id).await;
1231 let body = format!("csrf={csrf}&next={}&body=changed", next_of(&key));
1232 let (status, _) = send(
1233 &state,
1234 post(&format!("/comments/{}/edit", comment.id), &token, body),
1235 )
1236 .await;
1237 assert_eq!(status, 403);
1238 let comments = state
1239 .store
1240 .list_comments(&board.id, &task_id)
1241 .await
1242 .expect("comments");
1243 assert_eq!(comments[0].body, "mine");
1244 }
1245
1246 /// A comment of a deleted task is not found, for edit and for delete.
1247 #[tokio::test]
1248 async fn a_comment_of_a_deleted_task_is_not_found() {
1249 let (_dir, state) = test_state().await;
1250 sign_in_as(&state, AUTHOR, Role::Member).await;
1251 let (task_id, _) = one_card(&state, "Milk", AUTHOR).await;
1252 let board = state.store.board().await.expect("board").expect("some");
1253 let comment = state
1254 .store
1255 .add_comment(&board.id, &task_id, AUTHOR, "old")
1256 .await
1257 .expect("comment");
1258 state
1259 .store
1260 .delete_task(&board.id, &task_id, AUTHOR)
1261 .await
1262 .expect("delete");
1263 let (token, csrf) = sign_in_as(&state, AUTHOR, Role::Member).await;
1264 let body = format!("csrf={csrf}&next=%2F&body=again");
1265 let (status, _) = send(
1266 &state,
1267 post(&format!("/comments/{}/edit", comment.id), &token, body),
1268 )
1269 .await;
1270 assert_eq!(status, 404);
1271 let body = format!("csrf={csrf}&next=%2F");
1272 let (status, _) = send(
1273 &state,
1274 post(&format!("/comments/{}/delete", comment.id), &token, body),
1275 )
1276 .await;
1277 assert_eq!(status, 404);
1278 }
1279
1280 /// A description with markup and a `javascript:` address reaches the page as text. Only the https
1281 /// address becomes a link.
1282 #[tokio::test]
1283 async fn a_description_is_plain_text_with_safe_links() {
1284 let (_dir, state) = test_state().await;
1285 let (token, _) = sign_in_as(&state, AUTHOR, Role::Member).await;
1286 let (task_id, _) = one_card(&state, "Milk", AUTHOR).await;
1287 let board = state.store.board().await.expect("board").expect("some");
1288 let tags = state.store.tags(&board.id).await.expect("tags");
1289 let description = "<img src=x onerror=alert(1)>\njavascript:alert(1) \
1290 https://ok.example/a?b=1. <b>bold</b>";
1291 state
1292 .store
1293 .edit_task(
1294 &board.id,
1295 &task_id,
1296 TaskEdit {
1297 title: "Milk".into(),
1298 description: description.into(),
1299 tag_id: tags[0].id.clone(),
1300 deadline: None,
1301 meeting_at: None,
1302 },
1303 AUTHOR,
1304 )
1305 .await
1306 .expect("edit");
1307 let key = key_of(&state, &task_id).await;
1308 let (status, html) = send(&state, get(&format!("/?task={key}"), &token)).await;
1309 assert_eq!(status, 200);
1310 assert!(
1311 html.contains("&lt;img src=x onerror=alert(1)&gt;"),
1312 "not escaped"
1313 );
1314 assert!(!html.contains("<img src=x"), "markup reached the page");
1315 assert!(!html.contains("<b>bold</b>"), "markup reached the page");
1316 assert!(!html.contains("href=\"javascript"), "javascript link");
1317 assert!(
1318 html.contains("href=\"https://ok.example/a?b=1\""),
1319 "https address not linked"
1320 );
1321 }
1322
1323 /// A dependency that closes a cycle is refused with `422` and its translated message.
1324 #[tokio::test]
1325 async fn a_dependency_cycle_is_refused_with_a_message() {
1326 let (_dir, state) = test_state().await;
1327 let (token, csrf) = sign_in_as(&state, AUTHOR, Role::Member).await;
1328 let (first, column) = one_card(&state, "First", AUTHOR).await;
1329 let board = state.store.board().await.expect("board").expect("some");
1330 let tags = state.store.tags(&board.id).await.expect("tags");
1331 let second = state
1332 .store
1333 .create_task(
1334 &board.id,
1335 NewTask {
1336 title: "Second".into(),
1337 description: String::new(),
1338 column_id: column,
1339 tag_id: tags[0].id.clone(),
1340 deadline: None,
1341 meeting_at: None,
1342 assignees: Vec::new(),
1343 parent_id: None,
1344 link: None,
1345 },
1346 AUTHOR,
1347 )
1348 .await
1349 .expect("second task")
1350 .id;
1351 state
1352 .store
1353 .add_dependency(&board.id, &first, &second, AUTHOR)
1354 .await
1355 .expect("first link");
1356 let key = key_of(&state, &second).await;
1357 let body = format!(
1358 "csrf={csrf}&next={}&other={first}&direction=blocked_by",
1359 next_of(&key)
1360 );
1361 let (status, html) = send(
1362 &state,
1363 post(&format!("/tasks/{second}/links"), &token, body),
1364 )
1365 .await;
1366 assert_eq!(status, 422);
1367 assert!(
1368 html.contains(t(Lang::En, K::ErrCycle)),
1369 "cycle message missing: {html}"
1370 );
1371 }
1372
1373 /// An unknown task key answers the board with its notice and `404`.
1374 #[tokio::test]
1375 async fn an_unknown_task_key_is_not_found() {
1376 let (_dir, state) = test_state().await;
1377 let (token, _) = sign_in_as(&state, AUTHOR, Role::Member).await;
1378 state.store.ensure_board("IZ").await.expect("board");
1379 let (status, html) = send(&state, get("/?task=IZ-999", &token)).await;
1380 assert_eq!(status, 404);
1381 assert!(html.contains(crate::i18n::board::t(
1382 Lang::En,
1383 crate::i18n::board::K::TaskNotFound
1384 )));
1385 }
1386}