//! Asclepius: «Nieuw ticket maken» in de app, met de velden van het webformulier. //! Ook voor «Ticket maken in Asclepius» in het berichtmenu, dan vooraf ingevuld //! met het bericht; vermeldingen worden `@naam:domein` zoals Asclepius ze kent. use std::path::PathBuf; use gpui_kit::component::checkbox::Checkbox; use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState}; use gpui_kit::component::{Disableable as _, h_flex, v_flex}; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; use kvt_sleutels::ClientError; use kvt_sleutels::asclepius::MessageSource; use kvt_sleutels::tickets::{ ATTACHMENT_MAX_BYTES, ATTACHMENTS_MAX, DESCRIPTION_MAX, Lookups, NewAttachment, NewTicket, TITLE_MAX, mentions_to_asclepius, mime_for, parse_participants, priority_from_flags, }; use super::modal::{primary_button, secondary_button}; use super::tasks::{chip, field, label, muted, not_linked}; use super::tickets::ticket_error; use super::{Link, forget_token, installed, is_demo, link, notice, token_and_client, update}; use crate::i18n::{tr, tr_args}; use crate::runtime; use crate::theme::{self, ElevatedSurface as _}; use crate::views::widgets::symbol; pub const KVT_TICKET_FORM_TAG: &str = "kvt-asclepius-form"; const BACKDROP_OPACITY: f32 = 0.55; const PANEL_WIDTH: f32 = 560.; const PANEL_MARGIN: f32 = 32.; const PANEL_RADIUS: f32 = 10.; const PANEL_PADDING: f32 = 16.; const SECTION_GAP: f32 = 10.; const CLOSE_SIZE: f32 = 28.; #[derive(Clone)] enum LookupState { Loading, Loaded(Lookups), Failed(ClientError), } struct PickedFile { name: String, size: usize, attachment: NewAttachment, } pub struct TicketForm { source: Option, lookups: LookupState, category: Option, subcategory: Option, title: Entity, description: Entity, participants: Entity, blocked: bool, fully_blocked: bool, files: Vec, saving: bool, error: Option, } /// Opent het formulier; `source` is het bericht bij «Ticket maken in Asclepius». pub(super) fn open_new(source: Option, window: &mut Window, cx: &mut App) { if !installed(cx) { return; } let form = cx.new(|cx| TicketForm::new(source, window, cx)); update(cx, |kvt| kvt.ticket_form = Some(form.clone())); if is_demo(cx) { form.update(cx, |form, cx| form.set_lookups(Ok(demo_lookups()), cx)); return; } let Some((token, client)) = token_and_client(cx) else { return; }; let loading = runtime::spawn(async move { client.asclepius_lookups(&token).await }); let weak = form.downgrade(); cx.spawn(async move |cx| { let result = loading.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| { if result == Err(ClientError::Unauthorized) { forget_token(cx); } weak.update(cx, |form, cx| form.set_lookups(result, cx)) .ok(); }); }) .detach(); } fn tr_with(key: &str, name: &str, value: String) -> String { tr_args( key, &std::collections::HashMap::from([(name.to_owned(), value)]), ) } fn close(cx: &mut App) { update(cx, |kvt| kvt.ticket_form = None); } /// Knop «Nieuw ticket» in de kop van de tegel. pub(super) fn new_ticket_button(cx: &mut Context) -> Option> { matches!(link(cx), Link::Linked(_)).then(|| { primary_button("kvt-tickets-new", tr("kvt.tickets.new")) .on_click(|_, window, cx| open_new(None, window, cx)) }) } /// Beschrijving uit het bericht, met de vermeldingen als Asclepius-token. fn prefilled_description(source: &MessageSource) -> String { mentions_to_asclepius(&source.description(DESCRIPTION_MAX), &source.mentions) } impl TicketForm { fn new(source: Option, window: &mut Window, cx: &mut Context) -> Self { let title_text = source .as_ref() .map(|source| source.title(TITLE_MAX)) .unwrap_or_default(); let description_text = source .as_ref() .map(prefilled_description) .unwrap_or_default(); let title = cx.new(|cx| { InputState::new(window, cx) .placeholder(tr("kvt.tickets.form.title_placeholder")) .default_value(title_text) }); let description = cx.new(|cx| { TextareaState::new(window, cx) .auto_grow(4, 10) .placeholder(tr("kvt.tickets.form.description_placeholder")) .default_value(description_text) }); let participants = cx.new(|cx| { InputState::new(window, cx).placeholder(tr("kvt.tickets.form.participants_placeholder")) }); title.update(cx, |input, cx| input.focus(window, cx)); TicketForm { source, lookups: LookupState::Loading, category: None, subcategory: None, title, description, participants, blocked: false, fully_blocked: false, files: Vec::new(), saving: false, error: None, } } fn set_lookups(&mut self, result: Result, cx: &mut Context) { self.lookups = match result { Ok(lookups) => LookupState::Loaded(lookups), Err(error) => LookupState::Failed(error), }; cx.notify(); } fn pick_files(&mut self, cx: &mut Context) { let receiver = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, multiple: true, prompt: None, }); cx.spawn(async move |this, cx| { let Ok(Ok(Some(paths))) = receiver.await else { return; }; let reading = runtime::spawn(async move { read_files(paths) }); let read = reading.await.unwrap_or_default(); this.update(cx, |this, cx| { for file in read { match file { Ok(file) if this.files.len() < ATTACHMENTS_MAX => this.files.push(file), Ok(_) => { this.error = Some(tr_with( "kvt.tickets.form.too_many_files", "max", ATTACHMENTS_MAX.to_string(), )) } Err(name) => { this.error = Some(tr_with("kvt.tickets.form.file_too_large", "name", name)) } } } cx.notify(); }) .ok(); }) .detach(); } fn save(&mut self, cx: &mut Context) { if self.saving { return; } let title = self.title.read(cx).value().trim().to_owned(); let description = self.description.read(cx).value().trim().to_owned(); let participants_text = self.participants.read(cx).value().to_string(); let Some(category) = self.category.clone() else { self.error = Some(tr("kvt.tickets.form.pick_category")); cx.notify(); return; }; if title.is_empty() || description.is_empty() { self.error = Some(tr("kvt.tickets.form.fill_in")); cx.notify(); return; } let participant_emails = match parse_participants(&participants_text) { Ok(emails) => emails, Err(bad) => { self.error = Some(tr_with("kvt.tickets.form.bad_email", "email", bad)); cx.notify(); return; } }; let ticket = NewTicket { title, category, subcategory: self.subcategory.clone(), description, priority: priority_from_flags(self.blocked, self.fully_blocked), participant_emails, attachments: self .files .iter() .map(|file| file.attachment.clone()) .collect(), }; if is_demo(cx) { close(cx); notice( tr_with("kvt.tickets.form.created", "id", "4103".to_owned()), cx, ); return; } let Some((token, client)) = token_and_client(cx) else { return; }; self.saving = true; self.error = None; cx.notify(); let creating = runtime::spawn(async move { client.asclepius_create(&token, &ticket).await }); cx.spawn(async move |this, cx| { let result = creating.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| match result { Ok(id) => { close(cx); notice( tr_with("kvt.tickets.form.created", "id", id.to_string()), cx, ); super::tickets::created(id, cx); } Err(error) => { if error == ClientError::Unauthorized { forget_token(cx); } this.update(cx, |this, cx| { this.saving = false; this.error = Some(ticket_error(&error)); cx.notify(); }) .ok(); } }); }) .detach(); } fn categories(&self, cx: &mut Context) -> AnyElement { let lookups = match &self.lookups { LookupState::Loading => return muted(tr("kvt.card.loading")).into_any_element(), LookupState::Failed(error) => return muted(ticket_error(error)).into_any_element(), LookupState::Loaded(lookups) => lookups, }; let categories = h_flex().w_full().flex_wrap().gap(px(6.)).children( lookups .form_categories() .into_iter() .enumerate() .map(|(index, category)| { let selected = self.category.as_deref() == Some(category.as_str()); chip( format!("kvt-ticket-category-{index}").into(), category.clone(), selected, ) .on_click(cx.listener(move |this, _, _, cx| { if this.category.as_deref() != Some(category.as_str()) { this.category = Some(category.clone()); this.subcategory = None; } this.error = None; cx.notify(); })) }), ); let subcategories = self .category .as_deref() .map(|category| lookups.subcategories_of(category).to_vec()) .unwrap_or_default(); v_flex() .w_full() .gap(px(SECTION_GAP)) .child(categories) .when(!subcategories.is_empty(), |column| { column .child(label(tr("kvt.tickets.form.subcategory"))) .child( h_flex().w_full().flex_wrap().gap(px(6.)).children( subcategories .into_iter() .enumerate() .map(|(index, subcategory)| { let selected = self.subcategory.as_deref() == Some(subcategory.as_str()); chip( format!("kvt-ticket-subcategory-{index}").into(), subcategory.clone(), selected, ) .on_click(cx.listener( move |this, _, _, cx| { // Nogmaals klikken haalt de keuze weg (subcategorie is optioneel). this.subcategory = (!selected).then(|| subcategory.clone()); cx.notify(); }, )) }), ), ) }) .into_any_element() } fn files(&self, cx: &mut Context) -> Div { h_flex() .w_full() .flex_wrap() .gap(px(6.)) .items_center() .children(self.files.iter().enumerate().map(|(index, file)| { h_flex() .id(ElementId::Name(format!("kvt-ticket-file-{index}").into())) .h(px(28.)) .pl(px(10.)) .pr(px(4.)) .gap(px(6.)) .items_center() .rounded(px(6.)) .bg(theme::popup_hover()) .text_size(px(12.)) .child(symbol("attach_file", 14., theme::text_muted())) .child(format!("{} ({})", file.name, size_label(file.size))) .child( div() .id(ElementId::Name( format!("kvt-ticket-file-remove-{index}").into(), )) .size(px(20.)) .flex() .items_center() .justify_center() .rounded_full() .cursor_pointer() .hover(|button| button.bg(theme::row_hover())) .on_click(cx.listener(move |this, _, _, cx| { if index < this.files.len() { this.files.remove(index); } cx.notify(); })) .child(symbol("close", 12., theme::text_muted())), ) })) .when(self.files.len() < ATTACHMENTS_MAX, |row| { row.child( secondary_button( "kvt-ticket-add-file", "attach_file", tr("kvt.tickets.form.add_files"), ) .on_click(cx.listener(|this, _, _, cx| this.pick_files(cx))), ) }) } } fn read_files(paths: Vec) -> Vec> { paths .into_iter() .filter_map(|path| { let name = path.file_name()?.to_string_lossy().into_owned(); let size = std::fs::metadata(&path).ok()?.len() as usize; if size > ATTACHMENT_MAX_BYTES { return Some(Err(name)); } let data = std::fs::read(&path).ok()?; Some(Ok(PickedFile { size: data.len(), attachment: NewAttachment { mime: mime_for(&name).to_owned(), filename: name.clone(), data, }, name, })) }) .collect() } fn size_label(bytes: usize) -> String { if bytes >= 1024 * 1024 { format!("{:.1} MB", bytes as f64 / (1024. * 1024.)).replace('.', ",") } else { format!("{} kB", bytes.div_ceil(1024).max(1)) } } impl Render for TicketForm { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { let linked = matches!(link(cx), Link::Linked(_)); let ready = linked && matches!(self.lookups, LookupState::Loaded(_)); let detail = self .source .as_ref() .filter(|source| !source.sender.is_empty()) .map(|source| format!("{} · {}", source.sender, source.sent_at)) .unwrap_or_default(); let blocked = self.blocked; let body = if !linked { v_flex().w_full().child(not_linked()) } else { v_flex() .w_full() .gap(px(SECTION_GAP)) .child(label(tr("kvt.tickets.form.title"))) .child( field().child( div() .flex_1() .child(Input::new(&self.title).appearance(false).bordered(false)), ), ) .child(label(tr("kvt.tickets.form.category"))) .child(self.categories(cx)) .child(label(tr("kvt.tickets.form.description"))) .child(Textarea::new(&self.description)) .child( Checkbox::new("kvt-ticket-blocked") .label(tr("kvt.tickets.form.blocked")) .checked(self.blocked) .on_click(cx.listener(|this, checked: &bool, _, cx| { this.blocked = *checked; if !*checked { this.fully_blocked = false; } cx.notify(); })), ) .child( Checkbox::new("kvt-ticket-fully-blocked") .label(tr("kvt.tickets.form.fully_blocked")) .checked(self.fully_blocked) .disabled(!blocked) .on_click(cx.listener(|this, checked: &bool, _, cx| { this.fully_blocked = *checked && this.blocked; cx.notify(); })), ) .child(label(tr("kvt.tickets.form.participants"))) .child( field().child( div().flex_1().child( Input::new(&self.participants) .appearance(false) .bordered(false), ), ), ) .child( div() .text_size(px(12.)) .text_color(theme::text_muted()) .child(tr("kvt.tickets.form.participants_hint")), ) .child(label(tr("kvt.tickets.form.attachments"))) .child(self.files(cx)) }; div() .id("kvt-ticket-form-layer") .absolute() .top_0() .left_0() .size_full() .flex() .items_center() .justify_center() .child( div() .id("kvt-ticket-form-backdrop") .absolute() .top_0() .left_0() .size_full() .bg(black().opacity(BACKDROP_OPACITY)) .occlude() .on_click(|_, _, cx| close(cx)), ) .child( v_flex() .id("kvt-ticket-form-panel") .debug_selector(|| KVT_TICKET_FORM_TAG.into()) .w(px(PANEL_WIDTH)) .max_w(relative(1.)) .max_h(relative(0.92)) .m(px(PANEL_MARGIN)) .p(px(PANEL_PADDING)) .gap(px(SECTION_GAP)) .rounded(px(PANEL_RADIUS)) .dialog_surface() .text_color(theme::text()) .overflow_y_scroll() .occlude() .on_key_down(cx.listener(|_, event: &KeyDownEvent, _, cx| { if event.keystroke.key == "escape" { close(cx); } })) .child( h_flex() .w_full() .items_center() .gap(px(SECTION_GAP)) .child( v_flex() .flex_1() .min_w_0() .child( div() .text_size(px(15.)) .font_weight(FontWeight::SEMIBOLD) .child(tr("kvt.tickets.form.heading")), ) .when(!detail.is_empty(), |column| { column.child( div() .truncate() .text_size(px(12.)) .text_color(theme::text_muted()) .child(detail), ) }), ) .child( div() .id("kvt-ticket-form-close") .size(px(CLOSE_SIZE)) .flex_none() .flex() .items_center() .justify_center() .rounded_full() .cursor_pointer() .hover(|button| button.bg(theme::popup_hover())) .on_click(|_, _, cx| close(cx)) .child(symbol("close", 16., theme::text_muted())), ), ) .child(body) .children(self.error.clone().map(|error| { div() .text_size(px(13.)) .text_color(theme::red_soft()) .child(error) })) .child( h_flex() .w_full() .gap(px(8.)) .justify_end() .child( secondary_button( "kvt-ticket-form-cancel", "close", tr("common.cancel"), ) .on_click(|_, _, cx| close(cx)), ) .when(ready, |row| { row.child( primary_button( "kvt-ticket-form-submit", tr(if self.saving { "kvt.tickets.sending" } else { "kvt.tickets.form.submit" }), ) .on_click(cx.listener(|this, _, _, cx| this.save(cx))), ) }), ), ) } } pub(super) fn demo_lookups() -> Lookups { let mut lookups = Lookups { categories: [ "Hardware", "Hardware bestellen", "Software", "Rechten en toegang", "Indiensttreding", ] .map(str::to_owned) .to_vec(), ..Lookups::default() }; lookups.subcategories.insert( "Hardware".to_owned(), ["Laptop", "Monitor", "Printer"].map(str::to_owned).to_vec(), ); lookups } #[cfg(test)] mod tests { use super::{demo_lookups, prefilled_description, size_label}; use kvt_sleutels::asclepius::MessageSource; #[test] fn message_mentions_become_asclepius_tokens() { let source = MessageSource { text: "@Jonas Ortega kun jij hiernaar kijken?".to_owned(), sender: "Dana Demo".to_owned(), sent_at: "15 jan 2026 13:39".to_owned(), link: None, mentions: vec![( "Jonas Ortega".to_owned(), "jonas.ortega@example.com".to_owned(), )], }; let description = prefilled_description(&source); assert!(description.starts_with("> @jonas.ortega:examplecom kun jij")); } #[test] fn ict_only_categories_are_not_offered() { assert!( !demo_lookups() .form_categories() .contains(&"Indiensttreding".to_owned()) ); } #[test] fn sizes_are_short_and_dutch() { assert_eq!(size_label(500), "1 kB"); assert_eq!(size_label(3 * 1024 * 1024 + 512 * 1024), "3,5 MB"); } }