BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / kvt / ticket_form.rs

ticket_form.rs

ticket_form.rs 25.3 KiB Download Raw
1//! Asclepius: «Nieuw ticket maken» in de app, met de velden van het webformulier.
2//! Ook voor «Ticket maken in Asclepius» in het berichtmenu, dan vooraf ingevuld
3//! met het bericht; vermeldingen worden `@naam:domein` zoals Asclepius ze kent.
4
5use std::path::PathBuf;
6
7use gpui_kit::component::checkbox::Checkbox;
8use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
9use gpui_kit::component::{Disableable as _, h_flex, v_flex};
10use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::*;
12use kvt_sleutels::ClientError;
13use kvt_sleutels::asclepius::MessageSource;
14use kvt_sleutels::tickets::{
15 ATTACHMENT_MAX_BYTES, ATTACHMENTS_MAX, DESCRIPTION_MAX, Lookups, NewAttachment, NewTicket,
16 TITLE_MAX, mentions_to_asclepius, mime_for, parse_participants, priority_from_flags,
17};
18
19use super::modal::{primary_button, secondary_button};
20use super::tasks::{chip, field, label, muted, not_linked};
21use super::tickets::ticket_error;
22use super::{Link, forget_token, installed, is_demo, link, notice, token_and_client, update};
23use crate::i18n::{tr, tr_args};
24use crate::runtime;
25use crate::theme::{self, ElevatedSurface as _};
26use crate::views::widgets::symbol;
27
28pub const KVT_TICKET_FORM_TAG: &str = "kvt-asclepius-form";
29const BACKDROP_OPACITY: f32 = 0.55;
30const PANEL_WIDTH: f32 = 560.;
31const PANEL_MARGIN: f32 = 32.;
32const PANEL_RADIUS: f32 = 10.;
33const PANEL_PADDING: f32 = 16.;
34const SECTION_GAP: f32 = 10.;
35const CLOSE_SIZE: f32 = 28.;
36
37#[derive(Clone)]
38enum LookupState {
39 Loading,
40 Loaded(Lookups),
41 Failed(ClientError),
42}
43
44struct PickedFile {
45 name: String,
46 size: usize,
47 attachment: NewAttachment,
48}
49
50pub struct TicketForm {
51 source: Option<MessageSource>,
52 lookups: LookupState,
53 category: Option<String>,
54 subcategory: Option<String>,
55 title: Entity<InputState>,
56 description: Entity<TextareaState>,
57 participants: Entity<InputState>,
58 blocked: bool,
59 fully_blocked: bool,
60 files: Vec<PickedFile>,
61 saving: bool,
62 error: Option<String>,
63}
64
65/// Opent het formulier; `source` is het bericht bij «Ticket maken in Asclepius».
66pub(super) fn open_new(source: Option<MessageSource>, window: &mut Window, cx: &mut App) {
67 if !installed(cx) {
68 return;
69 }
70 let form = cx.new(|cx| TicketForm::new(source, window, cx));
71 update(cx, |kvt| kvt.ticket_form = Some(form.clone()));
72 if is_demo(cx) {
73 form.update(cx, |form, cx| form.set_lookups(Ok(demo_lookups()), cx));
74 return;
75 }
76 let Some((token, client)) = token_and_client(cx) else {
77 return;
78 };
79 let loading = runtime::spawn(async move { client.asclepius_lookups(&token).await });
80 let weak = form.downgrade();
81 cx.spawn(async move |cx| {
82 let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
83 cx.update(|cx| {
84 if result == Err(ClientError::Unauthorized) {
85 forget_token(cx);
86 }
87 weak.update(cx, |form, cx| form.set_lookups(result, cx))
88 .ok();
89 });
90 })
91 .detach();
92}
93
94fn tr_with(key: &str, name: &str, value: String) -> String {
95 tr_args(
96 key,
97 &std::collections::HashMap::from([(name.to_owned(), value)]),
98 )
99}
100
101fn close(cx: &mut App) {
102 update(cx, |kvt| kvt.ticket_form = None);
103}
104
105/// Knop «Nieuw ticket» in de kop van de tegel.
106pub(super) fn new_ticket_button<T: 'static>(cx: &mut Context<T>) -> Option<Stateful<Div>> {
107 matches!(link(cx), Link::Linked(_)).then(|| {
108 primary_button("kvt-tickets-new", tr("kvt.tickets.new"))
109 .on_click(|_, window, cx| open_new(None, window, cx))
110 })
111}
112
113/// Beschrijving uit het bericht, met de vermeldingen als Asclepius-token.
114fn prefilled_description(source: &MessageSource) -> String {
115 mentions_to_asclepius(&source.description(DESCRIPTION_MAX), &source.mentions)
116}
117
118impl TicketForm {
119 fn new(source: Option<MessageSource>, window: &mut Window, cx: &mut Context<Self>) -> Self {
120 let title_text = source
121 .as_ref()
122 .map(|source| source.title(TITLE_MAX))
123 .unwrap_or_default();
124 let description_text = source
125 .as_ref()
126 .map(prefilled_description)
127 .unwrap_or_default();
128 let title = cx.new(|cx| {
129 InputState::new(window, cx)
130 .placeholder(tr("kvt.tickets.form.title_placeholder"))
131 .default_value(title_text)
132 });
133 let description = cx.new(|cx| {
134 TextareaState::new(window, cx)
135 .auto_grow(4, 10)
136 .placeholder(tr("kvt.tickets.form.description_placeholder"))
137 .default_value(description_text)
138 });
139 let participants = cx.new(|cx| {
140 InputState::new(window, cx).placeholder(tr("kvt.tickets.form.participants_placeholder"))
141 });
142 title.update(cx, |input, cx| input.focus(window, cx));
143 TicketForm {
144 source,
145 lookups: LookupState::Loading,
146 category: None,
147 subcategory: None,
148 title,
149 description,
150 participants,
151 blocked: false,
152 fully_blocked: false,
153 files: Vec::new(),
154 saving: false,
155 error: None,
156 }
157 }
158
159 fn set_lookups(&mut self, result: Result<Lookups, ClientError>, cx: &mut Context<Self>) {
160 self.lookups = match result {
161 Ok(lookups) => LookupState::Loaded(lookups),
162 Err(error) => LookupState::Failed(error),
163 };
164 cx.notify();
165 }
166
167 fn pick_files(&mut self, cx: &mut Context<Self>) {
168 let receiver = cx.prompt_for_paths(PathPromptOptions {
169 files: true,
170 directories: false,
171 multiple: true,
172 prompt: None,
173 });
174 cx.spawn(async move |this, cx| {
175 let Ok(Ok(Some(paths))) = receiver.await else {
176 return;
177 };
178 let reading = runtime::spawn(async move { read_files(paths) });
179 let read = reading.await.unwrap_or_default();
180 this.update(cx, |this, cx| {
181 for file in read {
182 match file {
183 Ok(file) if this.files.len() < ATTACHMENTS_MAX => this.files.push(file),
184 Ok(_) => {
185 this.error = Some(tr_with(
186 "kvt.tickets.form.too_many_files",
187 "max",
188 ATTACHMENTS_MAX.to_string(),
189 ))
190 }
191 Err(name) => {
192 this.error =
193 Some(tr_with("kvt.tickets.form.file_too_large", "name", name))
194 }
195 }
196 }
197 cx.notify();
198 })
199 .ok();
200 })
201 .detach();
202 }
203
204 fn save(&mut self, cx: &mut Context<Self>) {
205 if self.saving {
206 return;
207 }
208 let title = self.title.read(cx).value().trim().to_owned();
209 let description = self.description.read(cx).value().trim().to_owned();
210 let participants_text = self.participants.read(cx).value().to_string();
211 let Some(category) = self.category.clone() else {
212 self.error = Some(tr("kvt.tickets.form.pick_category"));
213 cx.notify();
214 return;
215 };
216 if title.is_empty() || description.is_empty() {
217 self.error = Some(tr("kvt.tickets.form.fill_in"));
218 cx.notify();
219 return;
220 }
221 let participant_emails = match parse_participants(&participants_text) {
222 Ok(emails) => emails,
223 Err(bad) => {
224 self.error = Some(tr_with("kvt.tickets.form.bad_email", "email", bad));
225 cx.notify();
226 return;
227 }
228 };
229 let ticket = NewTicket {
230 title,
231 category,
232 subcategory: self.subcategory.clone(),
233 description,
234 priority: priority_from_flags(self.blocked, self.fully_blocked),
235 participant_emails,
236 attachments: self
237 .files
238 .iter()
239 .map(|file| file.attachment.clone())
240 .collect(),
241 };
242 if is_demo(cx) {
243 close(cx);
244 notice(
245 tr_with("kvt.tickets.form.created", "id", "4103".to_owned()),
246 cx,
247 );
248 return;
249 }
250 let Some((token, client)) = token_and_client(cx) else {
251 return;
252 };
253 self.saving = true;
254 self.error = None;
255 cx.notify();
256 let creating =
257 runtime::spawn(async move { client.asclepius_create(&token, &ticket).await });
258 cx.spawn(async move |this, cx| {
259 let result = creating.await.unwrap_or(Err(ClientError::Unavailable));
260 cx.update(|cx| match result {
261 Ok(id) => {
262 close(cx);
263 notice(
264 tr_with("kvt.tickets.form.created", "id", id.to_string()),
265 cx,
266 );
267 super::tickets::created(id, cx);
268 }
269 Err(error) => {
270 if error == ClientError::Unauthorized {
271 forget_token(cx);
272 }
273 this.update(cx, |this, cx| {
274 this.saving = false;
275 this.error = Some(ticket_error(&error));
276 cx.notify();
277 })
278 .ok();
279 }
280 });
281 })
282 .detach();
283 }
284
285 fn categories(&self, cx: &mut Context<Self>) -> AnyElement {
286 let lookups = match &self.lookups {
287 LookupState::Loading => return muted(tr("kvt.card.loading")).into_any_element(),
288 LookupState::Failed(error) => return muted(ticket_error(error)).into_any_element(),
289 LookupState::Loaded(lookups) => lookups,
290 };
291 let categories = h_flex().w_full().flex_wrap().gap(px(6.)).children(
292 lookups
293 .form_categories()
294 .into_iter()
295 .enumerate()
296 .map(|(index, category)| {
297 let selected = self.category.as_deref() == Some(category.as_str());
298 chip(
299 format!("kvt-ticket-category-{index}").into(),
300 category.clone(),
301 selected,
302 )
303 .on_click(cx.listener(move |this, _, _, cx| {
304 if this.category.as_deref() != Some(category.as_str()) {
305 this.category = Some(category.clone());
306 this.subcategory = None;
307 }
308 this.error = None;
309 cx.notify();
310 }))
311 }),
312 );
313 let subcategories = self
314 .category
315 .as_deref()
316 .map(|category| lookups.subcategories_of(category).to_vec())
317 .unwrap_or_default();
318 v_flex()
319 .w_full()
320 .gap(px(SECTION_GAP))
321 .child(categories)
322 .when(!subcategories.is_empty(), |column| {
323 column
324 .child(label(tr("kvt.tickets.form.subcategory")))
325 .child(
326 h_flex().w_full().flex_wrap().gap(px(6.)).children(
327 subcategories
328 .into_iter()
329 .enumerate()
330 .map(|(index, subcategory)| {
331 let selected =
332 self.subcategory.as_deref() == Some(subcategory.as_str());
333 chip(
334 format!("kvt-ticket-subcategory-{index}").into(),
335 subcategory.clone(),
336 selected,
337 )
338 .on_click(cx.listener(
339 move |this, _, _, cx| {
340 // Nogmaals klikken haalt de keuze weg (subcategorie is optioneel).
341 this.subcategory =
342 (!selected).then(|| subcategory.clone());
343 cx.notify();
344 },
345 ))
346 }),
347 ),
348 )
349 })
350 .into_any_element()
351 }
352
353 fn files(&self, cx: &mut Context<Self>) -> Div {
354 h_flex()
355 .w_full()
356 .flex_wrap()
357 .gap(px(6.))
358 .items_center()
359 .children(self.files.iter().enumerate().map(|(index, file)| {
360 h_flex()
361 .id(ElementId::Name(format!("kvt-ticket-file-{index}").into()))
362 .h(px(28.))
363 .pl(px(10.))
364 .pr(px(4.))
365 .gap(px(6.))
366 .items_center()
367 .rounded(px(6.))
368 .bg(theme::popup_hover())
369 .text_size(px(12.))
370 .child(symbol("attach_file", 14., theme::text_muted()))
371 .child(format!("{} ({})", file.name, size_label(file.size)))
372 .child(
373 div()
374 .id(ElementId::Name(
375 format!("kvt-ticket-file-remove-{index}").into(),
376 ))
377 .size(px(20.))
378 .flex()
379 .items_center()
380 .justify_center()
381 .rounded_full()
382 .cursor_pointer()
383 .hover(|button| button.bg(theme::row_hover()))
384 .on_click(cx.listener(move |this, _, _, cx| {
385 if index < this.files.len() {
386 this.files.remove(index);
387 }
388 cx.notify();
389 }))
390 .child(symbol("close", 12., theme::text_muted())),
391 )
392 }))
393 .when(self.files.len() < ATTACHMENTS_MAX, |row| {
394 row.child(
395 secondary_button(
396 "kvt-ticket-add-file",
397 "attach_file",
398 tr("kvt.tickets.form.add_files"),
399 )
400 .on_click(cx.listener(|this, _, _, cx| this.pick_files(cx))),
401 )
402 })
403 }
404}
405
406fn read_files(paths: Vec<PathBuf>) -> Vec<Result<PickedFile, String>> {
407 paths
408 .into_iter()
409 .filter_map(|path| {
410 let name = path.file_name()?.to_string_lossy().into_owned();
411 let size = std::fs::metadata(&path).ok()?.len() as usize;
412 if size > ATTACHMENT_MAX_BYTES {
413 return Some(Err(name));
414 }
415 let data = std::fs::read(&path).ok()?;
416 Some(Ok(PickedFile {
417 size: data.len(),
418 attachment: NewAttachment {
419 mime: mime_for(&name).to_owned(),
420 filename: name.clone(),
421 data,
422 },
423 name,
424 }))
425 })
426 .collect()
427}
428
429fn size_label(bytes: usize) -> String {
430 if bytes >= 1024 * 1024 {
431 format!("{:.1} MB", bytes as f64 / (1024. * 1024.)).replace('.', ",")
432 } else {
433 format!("{} kB", bytes.div_ceil(1024).max(1))
434 }
435}
436
437impl Render for TicketForm {
438 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
439 let linked = matches!(link(cx), Link::Linked(_));
440 let ready = linked && matches!(self.lookups, LookupState::Loaded(_));
441 let detail = self
442 .source
443 .as_ref()
444 .filter(|source| !source.sender.is_empty())
445 .map(|source| format!("{} · {}", source.sender, source.sent_at))
446 .unwrap_or_default();
447 let blocked = self.blocked;
448 let body = if !linked {
449 v_flex().w_full().child(not_linked())
450 } else {
451 v_flex()
452 .w_full()
453 .gap(px(SECTION_GAP))
454 .child(label(tr("kvt.tickets.form.title")))
455 .child(
456 field().child(
457 div()
458 .flex_1()
459 .child(Input::new(&self.title).appearance(false).bordered(false)),
460 ),
461 )
462 .child(label(tr("kvt.tickets.form.category")))
463 .child(self.categories(cx))
464 .child(label(tr("kvt.tickets.form.description")))
465 .child(Textarea::new(&self.description))
466 .child(
467 Checkbox::new("kvt-ticket-blocked")
468 .label(tr("kvt.tickets.form.blocked"))
469 .checked(self.blocked)
470 .on_click(cx.listener(|this, checked: &bool, _, cx| {
471 this.blocked = *checked;
472 if !*checked {
473 this.fully_blocked = false;
474 }
475 cx.notify();
476 })),
477 )
478 .child(
479 Checkbox::new("kvt-ticket-fully-blocked")
480 .label(tr("kvt.tickets.form.fully_blocked"))
481 .checked(self.fully_blocked)
482 .disabled(!blocked)
483 .on_click(cx.listener(|this, checked: &bool, _, cx| {
484 this.fully_blocked = *checked && this.blocked;
485 cx.notify();
486 })),
487 )
488 .child(label(tr("kvt.tickets.form.participants")))
489 .child(
490 field().child(
491 div().flex_1().child(
492 Input::new(&self.participants)
493 .appearance(false)
494 .bordered(false),
495 ),
496 ),
497 )
498 .child(
499 div()
500 .text_size(px(12.))
501 .text_color(theme::text_muted())
502 .child(tr("kvt.tickets.form.participants_hint")),
503 )
504 .child(label(tr("kvt.tickets.form.attachments")))
505 .child(self.files(cx))
506 };
507 div()
508 .id("kvt-ticket-form-layer")
509 .absolute()
510 .top_0()
511 .left_0()
512 .size_full()
513 .flex()
514 .items_center()
515 .justify_center()
516 .child(
517 div()
518 .id("kvt-ticket-form-backdrop")
519 .absolute()
520 .top_0()
521 .left_0()
522 .size_full()
523 .bg(black().opacity(BACKDROP_OPACITY))
524 .occlude()
525 .on_click(|_, _, cx| close(cx)),
526 )
527 .child(
528 v_flex()
529 .id("kvt-ticket-form-panel")
530 .debug_selector(|| KVT_TICKET_FORM_TAG.into())
531 .w(px(PANEL_WIDTH))
532 .max_w(relative(1.))
533 .max_h(relative(0.92))
534 .m(px(PANEL_MARGIN))
535 .p(px(PANEL_PADDING))
536 .gap(px(SECTION_GAP))
537 .rounded(px(PANEL_RADIUS))
538 .dialog_surface()
539 .text_color(theme::text())
540 .overflow_y_scroll()
541 .occlude()
542 .on_key_down(cx.listener(|_, event: &KeyDownEvent, _, cx| {
543 if event.keystroke.key == "escape" {
544 close(cx);
545 }
546 }))
547 .child(
548 h_flex()
549 .w_full()
550 .items_center()
551 .gap(px(SECTION_GAP))
552 .child(
553 v_flex()
554 .flex_1()
555 .min_w_0()
556 .child(
557 div()
558 .text_size(px(15.))
559 .font_weight(FontWeight::SEMIBOLD)
560 .child(tr("kvt.tickets.form.heading")),
561 )
562 .when(!detail.is_empty(), |column| {
563 column.child(
564 div()
565 .truncate()
566 .text_size(px(12.))
567 .text_color(theme::text_muted())
568 .child(detail),
569 )
570 }),
571 )
572 .child(
573 div()
574 .id("kvt-ticket-form-close")
575 .size(px(CLOSE_SIZE))
576 .flex_none()
577 .flex()
578 .items_center()
579 .justify_center()
580 .rounded_full()
581 .cursor_pointer()
582 .hover(|button| button.bg(theme::popup_hover()))
583 .on_click(|_, _, cx| close(cx))
584 .child(symbol("close", 16., theme::text_muted())),
585 ),
586 )
587 .child(body)
588 .children(self.error.clone().map(|error| {
589 div()
590 .text_size(px(13.))
591 .text_color(theme::red_soft())
592 .child(error)
593 }))
594 .child(
595 h_flex()
596 .w_full()
597 .gap(px(8.))
598 .justify_end()
599 .child(
600 secondary_button(
601 "kvt-ticket-form-cancel",
602 "close",
603 tr("common.cancel"),
604 )
605 .on_click(|_, _, cx| close(cx)),
606 )
607 .when(ready, |row| {
608 row.child(
609 primary_button(
610 "kvt-ticket-form-submit",
611 tr(if self.saving {
612 "kvt.tickets.sending"
613 } else {
614 "kvt.tickets.form.submit"
615 }),
616 )
617 .on_click(cx.listener(|this, _, _, cx| this.save(cx))),
618 )
619 }),
620 ),
621 )
622 }
623}
624
625pub(super) fn demo_lookups() -> Lookups {
626 let mut lookups = Lookups {
627 categories: [
628 "Hardware",
629 "Hardware bestellen",
630 "Software",
631 "Rechten en toegang",
632 "Indiensttreding",
633 ]
634 .map(str::to_owned)
635 .to_vec(),
636 ..Lookups::default()
637 };
638 lookups.subcategories.insert(
639 "Hardware".to_owned(),
640 ["Laptop", "Monitor", "Printer"].map(str::to_owned).to_vec(),
641 );
642 lookups
643}
644
645#[cfg(test)]
646mod tests {
647 use super::{demo_lookups, prefilled_description, size_label};
648 use kvt_sleutels::asclepius::MessageSource;
649
650 #[test]
651 fn message_mentions_become_asclepius_tokens() {
652 let source = MessageSource {
653 text: "@Jonas Ortega kun jij hiernaar kijken?".to_owned(),
654 sender: "Dana Demo".to_owned(),
655 sent_at: "15 jan 2026 13:39".to_owned(),
656 link: None,
657 mentions: vec![(
658 "Jonas Ortega".to_owned(),
659 "jonas.ortega@example.com".to_owned(),
660 )],
661 };
662 let description = prefilled_description(&source);
663 assert!(description.starts_with("> @jonas.ortega:examplecom kun jij"));
664 }
665
666 #[test]
667 fn ict_only_categories_are_not_offered() {
668 assert!(
669 !demo_lookups()
670 .form_categories()
671 .contains(&"Indiensttreding".to_owned())
672 );
673 }
674
675 #[test]
676 fn sizes_are_short_and_dutch() {
677 assert_eq!(size_label(500), "1 kB");
678 assert_eq!(size_label(3 * 1024 * 1024 + 512 * 1024), "3,5 MB");
679 }
680}