//! Asclepius-tegel: je tickets (zoals «Mijn tickets» op het web, plus aan jou //! toegewezen) links, het gesprek van het gekozen ticket rechts. Antwoorden kan //! hier; behandelen (status, toewijzing) blijft in Asclepius (fase 2). //! //! Ongelezen is lokaal (`kvt.asclepius.seen`): een ticket waarvan `updated_at` //! nieuwer is dan toen je het opende. Elke minuut `ticket_updates`. use std::collections::HashMap; use std::time::Duration; use chrono::{DateTime, Local}; use gpui_kit::component::input::{Textarea, TextareaState}; use gpui_kit::component::scroll::ScrollableElement as _; use gpui_kit::component::{h_flex, v_flex}; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; use kvt_sleutels::format::date_time_nl; use kvt_sleutels::tickets::{ SeenTickets, TextPart, Ticket, TicketAttachment, TicketDetail, TicketFilter, TicketMessage, mention_label, mention_token, split_mentions, ticket_id_from_url, }; use kvt_sleutels::{CardsClient, ClientError}; use super::modal::{primary_button, secondary_button}; use super::tasks::{chip, muted, not_linked}; use super::{ Link, base_url, error_text, forget_token, installed, is_demo, link, notice, token_and_client, update, }; use crate::app_state::AppHandle; use crate::i18n::tr; use crate::runtime; use crate::theme::{self, ElevatedSurface as _}; use crate::views::widgets::symbol; pub const KVT_TICKETS_TAG: &str = "kvt-asclepius-tickets"; const SEEN_META_KEY: &str = "kvt.asclepius.seen"; const POLL_INTERVAL: Duration = Duration::from_secs(60); const HEADER_HEIGHT: f32 = 60.; const PAGE_PADDING: f32 = 20.; const LIST_WIDTH: f32 = 320.; const RADIUS: f32 = 10.; const BUBBLE_RADIUS: f32 = 14.; // Ghost-berichten zoals op het web (`.message.is-ghost`), ongeacht het thema. const GHOST_BG: u32 = 0x5b21b6; const GHOST_BORDER: u32 = 0xf9a8d4; const GHOST_TEXT: u32 = 0xfce7f3; #[derive(Clone)] enum List { NotLinked, Loading, Loaded(Vec), Failed(ClientError), } #[derive(Clone)] enum Detail { Loading, Loaded(TicketDetail), Failed(ClientError), } pub(super) fn ticket_error(error: &ClientError) -> String { match error { ClientError::Forbidden | ClientError::NotFound => tr("kvt.tickets.not_found"), ClientError::BadRequest => tr("kvt.tickets.failed"), // Nog gekoppeld (anders toont de pagina de koppelknop): de Login kent de token wel. ClientError::Unauthorized => tr("kvt.tickets.refused"), other => error_text(other), } } /// `2026-01-15T13:39:00+01:00` → `15 jan 2026 13:39` (lokale tijd). pub(super) fn when(value: &str) -> String { DateTime::parse_from_rfc3339(value.trim()) .map(|moment| date_time_nl(moment.with_timezone(&Local).naive_local())) .unwrap_or_else(|_| value.get(..16).unwrap_or(value).replace('T', " ")) } pub(super) fn status_label(status: &str) -> String { let key = format!("kvt.tickets.status.{}", status.trim().replace(' ', "_")); let label = tr(&key); if label == key || label.is_empty() { status.to_owned() } else { label } } fn me(cx: &App) -> String { match link(cx) { Link::Linked(stored) => stored.email.to_lowercase(), _ => String::new(), } } // --- lokaal ongelezen ---------------------------------------------------------- fn load_seen(cx: &App) -> SeenTickets { cx.try_global::() .and_then(|handle| handle.0.read(cx).store.meta(SEEN_META_KEY).ok().flatten()) .map(|json| SeenTickets::from_json(&json)) .unwrap_or_default() } fn save_seen(seen: &SeenTickets, cx: &App) { if let Some(handle) = cx.try_global::() { let _ = handle .0 .read(cx) .store .set_meta(SEEN_META_KEY, &seen.to_json()); } } // --- gesprek van één ticket (tegel en ticketvenster) ---------------------------- pub struct TicketThread { id: u64, detail: Detail, reply: Entity, sending: bool, error: Option, generation: u64, scroll: ScrollHandle, } impl TicketThread { pub(super) fn new(id: u64, window: &mut Window, cx: &mut Context) -> Self { let mut thread = Self::with_detail(id, None, window, cx); thread.reload(cx); thread } /// Met een al opgehaald ticket (ticketvenster: eerst kijken of je toegang hebt). fn with_detail( id: u64, detail: Option, window: &mut Window, cx: &mut Context, ) -> Self { let reply = cx.new(|cx| { TextareaState::new(window, cx) .auto_grow(2, 8) .placeholder(tr("kvt.tickets.reply_placeholder")) }); let scroll = ScrollHandle::new(); if detail.is_some() { scroll.scroll_to_bottom(); } TicketThread { id, detail: detail.map_or(Detail::Loading, Detail::Loaded), reply, sending: false, error: None, generation: 0, scroll, } } pub(super) fn id(&self) -> u64 { self.id } pub(super) fn reload(&mut self, cx: &mut Context) { self.generation += 1; let generation = self.generation; let id = self.id; if is_demo(cx) { self.detail = match demo_detail(id) { Some(detail) => Detail::Loaded(detail), None => Detail::Failed(ClientError::NotFound), }; self.scroll.scroll_to_bottom(); cx.notify(); return; } let Some((token, client)) = token_and_client(cx) else { return; }; let loading = runtime::spawn(async move { client.asclepius_ticket(&token, id).await }); cx.spawn(async move |this, cx| { let result = loading.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| { if result == Err(ClientError::Unauthorized) { forget_token(cx); } let opened = result.as_ref().ok().map(|detail| detail.ticket.clone()); this.update(cx, |this, cx| { if this.generation != generation { return; } let first = !matches!(this.detail, Detail::Loaded(_)); this.detail = match result { Ok(detail) => Detail::Loaded(detail), Err(error) => Detail::Failed(error), }; if first { this.scroll.scroll_to_bottom(); } cx.notify(); }) .ok(); if let Some(ticket) = opened { ticket_seen(&ticket, cx); } }); }) .detach(); } fn mention(&mut self, email: &str, window: &mut Window, cx: &mut Context) { let Some(token) = mention_token(email) else { return; }; let current = self.reply.read(cx).value().to_string(); let joined = if current.is_empty() || current.ends_with([' ', '\n']) { format!("{current}{token} ") } else { format!("{current} {token} ") }; self.reply.update(cx, |reply, cx| { reply.set_value(joined, window, cx); reply.focus(window, cx); }); } fn send(&mut self, window: &mut Window, cx: &mut Context) { if self.sending { return; } let text = self.reply.read(cx).value().trim().to_owned(); if text.is_empty() { return; } self.sending = true; self.error = None; cx.notify(); if is_demo(cx) { demo_reply(self.id, &text, &me(cx)); self.sending = false; self.reply .update(cx, |reply, cx| reply.set_value("", window, cx)); self.scroll.scroll_to_bottom(); self.reload(cx); refresh_list(cx); return; } let Some((token, client)) = token_and_client(cx) else { self.sending = false; return; }; let id = self.id; let sending = runtime::spawn(async move { client.asclepius_reply(&token, id, &text).await }); let reply = self.reply.clone(); cx.spawn_in(window, async move |this, cx| { let result = sending.await.unwrap_or(Err(ClientError::Unavailable)); this.update_in(cx, |this, window, cx| { this.sending = false; match &result { Ok(()) => { reply.update(cx, |reply, cx| reply.set_value("", window, cx)); this.scroll.scroll_to_bottom(); this.reload(cx); refresh_list(cx); } Err(error) => { if *error == ClientError::Unauthorized { forget_token(cx); } this.error = Some(ticket_error(error)); } } cx.notify(); }) .ok(); }) .detach(); } fn header(&self, detail: &TicketDetail) -> Div { let ticket = &detail.ticket; let mut meta = vec![format!("#{}", ticket.id), status_label(&ticket.status)]; if !ticket.category.is_empty() { meta.push(if ticket.subcategory.is_empty() { ticket.category.clone() } else { format!("{} › {}", ticket.category, ticket.subcategory) }); } if !ticket.created_at.is_empty() { meta.push(when(&ticket.created_at)); } v_flex() .w_full() .flex_none() .px(px(PAGE_PADDING)) .py(px(12.)) .gap(px(2.)) .border_b_1() .border_color(theme::border()) .child( div() .text_size(px(16.)) .font_weight(FontWeight::BOLD) .text_color(theme::text()) .child(ticket.title.clone()), ) .child( div() .text_size(px(12.)) .text_color(theme::text_muted()) .child(meta.join(" · ")), ) } fn message( &self, index: usize, message: &TicketMessage, known: &[String], cx: &mut Context, ) -> AnyElement { let ghost = message.is_ghost; let from_ict = message.sender_role == "admin"; let text_color = if ghost { rgb(GHOST_TEXT).into() } else { theme::text() }; let muted_color = if ghost { rgb(GHOST_TEXT).into() } else { theme::text_muted() }; let mention_color: Hsla = if ghost { rgb(GHOST_BORDER).into() } else { theme::accent_text() }; let mut role = Vec::new(); if from_ict { role.push(tr("kvt.tickets.ict")); } if ghost { role.push(tr("kvt.tickets.ghost")); } let head = h_flex() .w_full() .gap(px(8.)) .items_center() .child( div() .text_size(px(13.)) .font_weight(FontWeight::SEMIBOLD) .text_color(text_color) .child(message.sender_name()), ) .when(!role.is_empty(), |row| { row.child( div() .text_size(px(11.)) .text_color(muted_color) .child(role.join(" · ")), ) }) .child(div().flex_1()) .child( div() .text_size(px(11.)) .text_color(muted_color) .child(when(&message.created_at)), ); let body = message_text(&message.message_text, known, mention_color); let attachments: Vec = message .attachments .iter() .enumerate() .map(|(position, attachment)| { attachment_chip(index, position, attachment, ghost, cx).into_any_element() }) .collect(); v_flex() .id(ElementId::Name( format!("kvt-ticket-message-{index}").into(), )) .w_full() .p(px(12.)) .gap(px(6.)) .rounded(px(BUBBLE_RADIUS)) .map(|bubble| { if ghost { bubble .bg(rgb(GHOST_BG)) .border_2() .border_color(rgb(GHOST_BORDER)) } else if from_ict { bubble.bg(theme::popup_hover()) } else { bubble.bg(theme::surface_raised()) } }) .child(head) .child(div().text_size(px(13.)).text_color(text_color).child(body)) .when(!attachments.is_empty(), |bubble| { bubble.child(h_flex().flex_wrap().gap(px(6.)).children(attachments)) }) .into_any_element() } fn composer(&self, detail: &TicketDetail, cx: &mut Context) -> Div { let me = me(cx); let mut people: Vec = detail .participant_emails .iter() .chain(std::iter::once(&detail.ticket.assigned_email)) .map(|email| email.to_lowercase()) .filter(|email| !email.is_empty() && *email != me) .collect(); people.sort(); people.dedup(); let names = sender_names(detail); v_flex() .w_full() .flex_none() .px(px(PAGE_PADDING)) .py(px(12.)) .gap(px(8.)) .border_t_1() .border_color(theme::border()) .when(!people.is_empty(), |column| { column.child( h_flex() .w_full() .flex_wrap() .gap(px(6.)) .items_center() .child( div() .text_size(px(12.)) .text_color(theme::text_muted()) .child(tr("kvt.tickets.mention")), ) .children(people.into_iter().enumerate().map(|(index, email)| { let label = names .get(&email) .cloned() .unwrap_or_else(|| kvt_sleutels::ponos::name_from_email(&email)); chip( format!("kvt-ticket-mention-{index}").into(), format!("@{label}"), false, ) .on_click(cx.listener( move |this, _, window, cx| this.mention(&email, window, cx), )) })), ) }) .child(Textarea::new(&self.reply)) .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.)) .items_center() .when(detail.ticket.is_closed(), |row| { row.child( div() .text_size(px(12.)) .text_color(theme::text_muted()) .child(tr("kvt.tickets.closed_hint")), ) }) .child(div().flex_1()) .child( primary_button( "kvt-ticket-send", tr(if self.sending { "kvt.tickets.sending" } else { "kvt.tickets.send" }), ) .on_click(cx.listener(|this, _, window, cx| this.send(window, cx))), ), ) } } fn sender_names(detail: &TicketDetail) -> HashMap { detail .messages .iter() .filter(|message| !message.sender_display_name.trim().is_empty()) .map(|message| { ( message.sender_email.to_lowercase(), message.sender_display_name.trim().to_owned(), ) }) .collect() } /// Tekst met Asclepius-vermeldingen als `@Voornaam` (vet, accentkleur), zoals op het web. fn message_text(text: &str, known: &[String], mention: Hsla) -> StyledText { let (shown, ranges) = mention_display(text, known); let style = HighlightStyle { color: Some(mention), font_weight: Some(FontWeight::BOLD), ..HighlightStyle::default() }; StyledText::new(shown).with_highlights(ranges.into_iter().map(|range| (range, style))) } /// Getoonde tekst en de plekken van de vermeldingen daarin. fn mention_display(text: &str, known: &[String]) -> (String, Vec>) { let mut shown = String::new(); let mut ranges = Vec::new(); for part in split_mentions(text.trim_end(), known) { match part { TextPart::Text(text) => shown.push_str(&text), TextPart::Mention { key, email } => { let start = shown.len(); shown.push_str(&mention_label(&key, email.as_deref())); ranges.push(start..shown.len()); } } } (shown, ranges) } fn attachment_chip( message: usize, position: usize, attachment: &TicketAttachment, ghost: bool, cx: &mut Context, ) -> Stateful
{ let attachment = attachment.clone(); let name = attachment.original_name.clone(); h_flex() .id(ElementId::Name( format!("kvt-ticket-attachment-{message}-{position}").into(), )) .h(px(28.)) .px(px(10.)) .gap(px(6.)) .items_center() .rounded(px(6.)) .cursor_pointer() .text_size(px(12.)) .map(|chip| { if ghost { chip.border_1() .border_color(rgb(GHOST_BORDER)) .text_color(rgb(GHOST_TEXT)) } else { chip.bg(theme::popup_hover()) .text_color(theme::text()) .hover(|chip| chip.bg(theme::row_hover())) } }) .on_click(cx.listener(move |_, _, _, cx| open_attachment(attachment.clone(), cx))) .child(symbol( "attach_file", 14., if ghost { rgb(GHOST_TEXT).into() } else { theme::text_muted() }, )) .child(name) } /// Bijlagen gaan alleen met de token: ophalen, in de tijdelijke map zetten en openen. fn open_attachment(attachment: TicketAttachment, cx: &mut App) { if is_demo(cx) { notice(tr("kvt.tickets.demo_attachment"), cx); return; } let Some((token, client)) = token_and_client(cx) else { return; }; let id = attachment.id; let name: String = attachment .original_name .chars() .filter(|c| c.is_alphanumeric() || "-_. ".contains(*c)) .collect(); let name = if name.trim().is_empty() { "bijlage".to_owned() } else { name }; let downloading = runtime::spawn(async move { let bytes = client.asclepius_attachment(&token, id).await?; let directory = std::env::temp_dir().join("rusty-teams-asclepius"); std::fs::create_dir_all(&directory).map_err(|_| ClientError::Unavailable)?; let path = directory.join(format!("{id}-{name}")); std::fs::write(&path, bytes).map_err(|_| ClientError::Unavailable)?; Ok::<_, ClientError>(path) }); cx.spawn(async move |cx| { let result = downloading.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| match result { Ok(path) => cx.open_with_system(&path), Err(error) => { if error == ClientError::Unauthorized { forget_token(cx); } notice(ticket_error(&error), cx); } }); }) .detach(); } impl Render for TicketThread { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { let detail = match &self.detail { Detail::Loading => { return v_flex() .size_full() .child(muted(tr("kvt.card.loading")).px(px(PAGE_PADDING))) .into_any_element(); } Detail::Failed(error) => { return v_flex() .size_full() .child(muted(ticket_error(error)).px(px(PAGE_PADDING))) .into_any_element(); } Detail::Loaded(detail) => detail.clone(), }; let mut known = detail.participant_emails.clone(); known.push(detail.ticket.assigned_email.clone()); known.push(detail.ticket.user_email.clone()); known.extend( detail .messages .iter() .map(|message| message.sender_email.clone()), ); let messages: Vec = detail .messages .iter() .enumerate() .map(|(index, message)| self.message(index, message, &known, cx)) .collect(); v_flex() .debug_selector(|| "kvt-ticket-thread".into()) .size_full() .min_h_0() .child(self.header(&detail)) .child( div() .id("kvt-ticket-messages") .flex_1() .min_h_0() .overflow_y_scroll() .track_scroll(&self.scroll) .child( v_flex() .w_full() .px(px(PAGE_PADDING)) .py(px(12.)) .gap(px(10.)) .children(messages), ), ) .child(self.composer(&detail, cx)) .into_any_element() } } // --- tegelpagina ------------------------------------------------------------- pub struct TicketsPage { filter: TicketFilter, list: List, /// Open tickets, ook als het filter op Afgehandeld staat (badge in de rail). open: Vec, selected: Option>, seen: SeenTickets, generation: u64, since: Option, polling: bool, } /// De pagina (eenmalig aangemaakt; ook voor de badge als de tegel dicht is). fn page(cx: &mut App) -> Option> { if !super::installed(cx) { return None; } if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() { return Some(page); } let page = cx.new(TicketsPage::new); cx.global_mut::().tickets = Some(page.clone()); Some(page) } /// De tegel als element van het hoofdpaneel. pub fn tickets_view(cx: &mut App) -> AnyElement { match page(cx) { Some(page) => div() .flex_1() .min_w_0() .h_full() .child(page) .into_any_element(), None => div().into_any_element(), } } /// De tegel is geopend: vers ophalen. pub fn tickets_opened(cx: &mut App) { if let Some(page) = page(cx) { page.update(cx, |page, cx| page.reload(cx)); } } /// Aantal ongelezen open tickets, voor de badge op de tegel. pub fn tickets_unread(cx: &mut App) -> usize { if !matches!(link(cx), Link::Linked(_)) { return 0; } page(cx).map_or(0, |page| { let page = page.read(cx); page.seen.unread_count(&page.open) }) } fn refresh_list(cx: &mut App) { if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() { page.update(cx, |page, cx| page.reload(cx)); } } /// Net aangemaakt: lijst opnieuw en het nieuwe ticket openen (als de tegel bestaat). pub(super) fn created(id: u64, cx: &mut App) { let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() else { return; }; let Some(window) = cx.active_window() else { page.update(cx, |page, cx| page.reload(cx)); return; }; window .update(cx, |_, window, cx| { page.update(cx, |page, cx| { page.filter = TicketFilter::Open; page.selected = Some(cx.new(|cx| TicketThread::new(id, window, cx))); page.reload(cx); }) }) .ok(); } /// Een ticket is bekeken (tegel of ticketvenster): niet meer ongelezen. pub(super) fn ticket_seen(ticket: &Ticket, cx: &mut App) { if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() { page.update(cx, |page, cx| { if page.seen.mark(ticket) { save_seen(&page.seen, cx); cx.notify(); } }); } } impl TicketsPage { fn new(cx: &mut Context) -> Self { let mut page = TicketsPage { filter: TicketFilter::Open, list: List::Loading, open: Vec::new(), selected: None, seen: load_seen(cx), generation: 0, since: None, polling: false, }; page.reload(cx); page.start_polling(cx); page } fn reload(&mut self, cx: &mut Context) { self.generation += 1; let generation = self.generation; let filter = self.filter; if is_demo(cx) { let all = demo_tickets(); self.open = all.iter().filter(|t| !t.is_closed()).cloned().collect(); if self.seen.initialize(&self.open) { // Demo: één ticket ongelezen, om de stip te tonen. self.seen.seen.insert(DEMO_UNREAD, String::new()); } self.list = List::Loaded( all.into_iter() .filter(|t| t.is_closed() == (filter == TicketFilter::Closed)) .collect(), ); cx.notify(); return; } let Some((token, client)) = token_and_client(cx) else { self.list = List::NotLinked; cx.notify(); return; }; if !matches!(self.list, List::Loaded(_)) { self.list = List::Loading; } let loading = runtime::spawn(async move { let open = client.asclepius_tickets(&token, TicketFilter::Open).await?; let shown = match filter { TicketFilter::Open => open.clone(), TicketFilter::Closed => { client .asclepius_tickets(&token, TicketFilter::Closed) .await? } }; Ok::<_, ClientError>((open, shown)) }); cx.spawn(async move |this, cx| { let result = loading.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| { if matches!(result, Err(ClientError::Unauthorized)) { forget_token(cx); } this.update(cx, |this, cx| { if this.generation != generation { return; } match result { Ok((open, shown)) => { if this.seen.initialize(&open) { save_seen(&this.seen, cx); } this.since = Some(chrono::Utc::now().to_rfc3339()); this.open = open; this.list = List::Loaded(shown); } Err(error) => this.list = List::Failed(error), } cx.notify(); cx.refresh_windows(); }) .ok(); }); }) .detach(); } /// Elke minuut `ticket_updates`; bij wijzigingen de lijst en het open ticket opnieuw. fn start_polling(&mut self, cx: &mut Context) { if self.polling || is_demo(cx) { return; } self.polling = true; cx.spawn(async move |this, cx| { loop { cx.background_executor().timer(POLL_INTERVAL).await; let Ok(Some((since, token))) = this.update(cx, |this, cx| { let since = this.since.clone()?; let (token, client) = token_and_client(cx)?; Some((since, (token, client))) }) else { if this.upgrade().is_none() { return; } continue; }; let (token, client): (String, CardsClient) = token; let polling = runtime::spawn(async move { client.asclepius_updates(&token, &since).await }); let result = polling.await.unwrap_or(Err(ClientError::Unavailable)); let alive = this.update(cx, |this, cx| { if let Ok((changed, server_time)) = result { if !server_time.is_empty() { this.since = Some(server_time); } if !changed.is_empty() { let open_id = this.selected.as_ref().map(|thread| thread.read(cx).id()); if let Some(thread) = this.selected.clone() && changed.iter().any(|t| Some(t.id) == open_id) { thread.update(cx, |thread, cx| thread.reload(cx)); } this.reload(cx); } } }); if alive.is_err() { return; } } }) .detach(); } fn set_filter(&mut self, filter: TicketFilter, cx: &mut Context) { if self.filter == filter { return; } self.filter = filter; self.list = List::Loading; self.reload(cx); } fn select(&mut self, ticket: &Ticket, window: &mut Window, cx: &mut Context) { if self .selected .as_ref() .is_some_and(|thread| thread.read(cx).id() == ticket.id) { return; } let id = ticket.id; self.selected = Some(cx.new(|cx| TicketThread::new(id, window, cx))); if self.seen.mark(ticket) { save_seen(&self.seen, cx); } cx.notify(); cx.refresh_windows(); } fn header(&self, cx: &mut Context) -> Div { h_flex() .h(px(HEADER_HEIGHT)) .flex_none() .px(px(PAGE_PADDING)) .gap(px(8.)) .items_center() .child( div() .flex_1() .min_w_0() .truncate() .text_size(px(16.)) .font_weight(FontWeight::BOLD) .text_color(theme::text()) .child(tr("kvt.tickets.title")), ) .children(super::ticket_form::new_ticket_button(cx)) .child( secondary_button("kvt-tickets-refresh", "refresh", tr("kvt.card.refresh")) .on_click(cx.listener(|this, _, _, cx| this.reload(cx))), ) } fn list(&self, cx: &mut Context) -> AnyElement { let filters = h_flex() .w_full() .flex_none() .px(px(12.)) .pb(px(8.)) .gap(px(6.)) .child( chip( "kvt-tickets-filter-open".into(), tr("kvt.tickets.filter_open"), self.filter == TicketFilter::Open, ) .on_click(cx.listener(|this, _, _, cx| this.set_filter(TicketFilter::Open, cx))), ) .child( chip( "kvt-tickets-filter-closed".into(), tr("kvt.tickets.filter_closed"), self.filter == TicketFilter::Closed, ) .on_click(cx.listener(|this, _, _, cx| this.set_filter(TicketFilter::Closed, cx))), ); let selected = self.selected.as_ref().map(|thread| thread.read(cx).id()); let rows: AnyElement = match &self.list { List::Loading | List::NotLinked => { muted(tr("kvt.card.loading")).px(px(12.)).into_any_element() } List::Failed(error) => muted(ticket_error(error)).px(px(12.)).into_any_element(), List::Loaded(tickets) if tickets.is_empty() => muted(tr(match self.filter { TicketFilter::Open => "kvt.tickets.empty_open", TicketFilter::Closed => "kvt.tickets.empty_closed", })) .px(px(12.)) .into_any_element(), List::Loaded(tickets) => v_flex() .w_full() .px(px(8.)) .gap(px(2.)) .children(tickets.iter().enumerate().map(|(index, ticket)| { let unread = self.seen.is_unread(ticket); let active = selected == Some(ticket.id); let row_ticket = ticket.clone(); v_flex() .id(ElementId::Name(format!("kvt-tickets-row-{index}").into())) .debug_selector(move || format!("kvt-tickets/row/{index}")) .w_full() .px(px(10.)) .py(px(8.)) .gap(px(2.)) .rounded(px(6.)) .cursor_pointer() .map(|row| { if active { row.bg(theme::selection()) } else { row.hover(|row| row.bg(theme::row_hover())) } }) .on_click(cx.listener(move |this, _, window, cx| { this.select(&row_ticket, window, cx) })) .child( h_flex() .w_full() .gap(px(6.)) .items_center() .child( div() .flex_1() .min_w_0() .truncate() .text_size(px(13.)) .text_color(theme::text_strong()) .when(unread, |title| title.font_weight(FontWeight::BOLD)) .child(ticket.title.clone()), ) .when(unread, |row| { row.child( div() .size(px(8.)) .flex_none() .rounded_full() .bg(theme::accent()), ) }), ) .child( div() .truncate() .text_size(px(12.)) .text_color(theme::text_muted()) .child(format!( "#{} · {} · {}", ticket.id, status_label(&ticket.status), when(&ticket.updated_at) )), ) })) .into_any_element(), }; v_flex() .id("kvt-tickets-list") .w(px(LIST_WIDTH)) .h_full() .flex_none() .border_r_1() .border_color(theme::border()) .child(filters) .child( div() .id("kvt-tickets-rows") .flex_1() .min_h_0() .overflow_y_scrollbar() .child(rows), ) .into_any_element() } } impl Render for TicketsPage { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { let linked = matches!(link(cx), Link::Linked(_)); if !linked && !is_demo(cx) { self.list = List::NotLinked; self.selected = None; self.open.clear(); } else if matches!(self.list, List::NotLinked) { self.reload(cx); } let body = if !linked { v_flex() .p(px(PAGE_PADDING)) .max_w(px(560.)) .child(not_linked()) .into_any_element() } else { h_flex() .flex_1() .min_h_0() .w_full() .child(self.list(cx)) .child( div() .flex_1() .min_w_0() .h_full() .child(match &self.selected { Some(thread) => thread.clone().into_any_element(), None => muted(tr("kvt.tickets.pick")) .px(px(PAGE_PADDING)) .into_any_element(), }), ) .into_any_element() }; v_flex() .debug_selector(|| KVT_TICKETS_TAG.into()) .relative() .size_full() .rounded(px(RADIUS)) .bg(theme::surface()) .overflow_hidden() .child(self.header(cx)) .child(body) } } // --- ticketvenster (links naar een ticket) ---------------------------------------- const WINDOW_WIDTH: f32 = 720.; const WINDOW_MARGIN: f32 = 32.; const WINDOW_BACKDROP: f32 = 0.55; pub const KVT_TICKET_WINDOW_TAG: &str = "kvt-asclepius-window"; /// Een link naar een Asclepius-ticket (`…/asclepius/index.php?open=…`): heb je toegang, dan /// opent het ticket in een venster in de app; anders gewoon in de browser. `false` als het /// geen ticketlink is of je niet gekoppeld bent (dan opent de shell de link zelf). pub fn open_ticket_link(url: &str, cx: &mut App) -> bool { if !installed(cx) || !matches!(link(cx), Link::Linked(_)) { return false; } let Some(id) = ticket_id_from_url(&base_url(), url) else { return false; }; let url = url.to_owned(); if is_demo(cx) { match demo_detail(id) { Some(detail) => cx.defer(move |cx| show_window(detail, cx)), None => app_base::open_link::open_url(cx, &url), } return true; } let Some((token, client)) = token_and_client(cx) else { return false; }; let loading = runtime::spawn(async move { client.asclepius_ticket(&token, id).await }); cx.spawn(async move |cx| { let result = loading.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| match result { Ok(detail) => show_window(detail, cx), Err(error) => { if error == ClientError::Unauthorized { forget_token(cx); } // Geen toegang of Asclepius niet bereikbaar: een gewone link. app_base::open_link::open_url(cx, &url); } }); }) .detach(); true } fn show_window(detail: TicketDetail, cx: &mut App) { let Some(window) = cx .active_window() .or_else(|| cx.windows().into_iter().next()) else { return; }; let ticket = detail.ticket.clone(); window .update(cx, |_, window, cx| { let thread = cx.new(|cx| TicketThread::with_detail(ticket.id, Some(detail), window, cx)); update(cx, |kvt| kvt.ticket_window = Some(thread)); cx.refresh_windows(); }) .ok(); ticket_seen(&ticket, cx); } fn close_window(cx: &mut App) { update(cx, |kvt| kvt.ticket_window = None); cx.refresh_windows(); } /// Laag voor `kvt::overlay`. pub(super) fn window_overlay(thread: Entity) -> AnyElement { div() .id("kvt-ticket-window-layer") .absolute() .top_0() .left_0() .size_full() .flex() .items_center() .justify_center() .child( div() .id("kvt-ticket-window-backdrop") .absolute() .top_0() .left_0() .size_full() .bg(black().opacity(WINDOW_BACKDROP)) .occlude() .on_click(|_, _, cx| close_window(cx)), ) .child( div() .id("kvt-ticket-window") .debug_selector(|| KVT_TICKET_WINDOW_TAG.into()) .relative() .w(px(WINDOW_WIDTH)) .max_w(relative(1.)) .h(relative(0.85)) .m(px(WINDOW_MARGIN)) .rounded(px(RADIUS)) .dialog_surface() .overflow_hidden() .occlude() .child(thread) .child( div() .id("kvt-ticket-window-close") .absolute() .top(px(10.)) .right(px(10.)) .size(px(28.)) .flex() .items_center() .justify_center() .rounded_full() .cursor_pointer() .hover(|button| button.bg(theme::popup_hover())) .on_click(|_, _, cx| close_window(cx)) .child(symbol("close", 16., theme::text_muted())), ), ) .into_any_element() } // --- demo ------------------------------------------------------------------------ const DEMO_UNREAD: u64 = 4102; thread_local! { static DEMO_REPLIES: std::cell::RefCell>> = std::cell::RefCell::new(HashMap::new()); } fn demo_ticket(id: u64, title: &str, status: &str, category: &str, updated: &str) -> Ticket { Ticket { id, title: title.to_owned(), category: category.to_owned(), user_email: super::demo::token().email, assigned_email: "ict.medewerker@example.com".to_owned(), status: status.to_owned(), created_at: "2026-01-12T09:15:00+01:00".to_owned(), updated_at: updated.to_owned(), message_count: 3, ..Ticket::default() } } pub(super) fn demo_tickets() -> Vec { vec![ Ticket { subcategory: "Laptop".to_owned(), ..demo_ticket( DEMO_UNREAD, "Laptop start niet meer op", "in behandeling", "Hardware", "2026-01-15T13:39:00+01:00", ) }, demo_ticket( 4098, "Toegang tot gedeelde map Projecten", "afwachtende op gebruiker", "Rechten en toegang", "2026-01-14T16:02:00+01:00", ), demo_ticket( 4090, "Nieuwe headset", "ingediend", "Hardware bestellen", "2026-01-13T10:20:00+01:00", ), demo_ticket( 4012, "Printer op kantoor geeft een fout", "afgehandeld", "Hardware", "2026-01-08T11:00:00+01:00", ), ] } fn demo_message( id: u64, email: &str, name: &str, role: &str, text: &str, at: &str, ) -> TicketMessage { TicketMessage { id, sender_email: email.to_owned(), sender_role: role.to_owned(), sender_display_name: name.to_owned(), message_text: text.to_owned(), created_at: at.to_owned(), ..TicketMessage::default() } } pub(super) fn demo_detail(id: u64) -> Option { let ticket = demo_tickets().into_iter().find(|ticket| ticket.id == id)?; let me = super::demo::token(); let ict = "ict.medewerker@example.com"; let mut messages = vec![ demo_message( 1, &me.email, &me.name, "user", "Mijn laptop gaat niet meer aan sinds vanochtend. Het lampje knippert oranje.", "2026-01-15T09:15:00+01:00", ), demo_message( 2, ict, "Sam Ict", "admin", "Dank je. Kun je de lader een minuut loskoppelen en het opnieuw proberen? @dana.demo:examplecom", "2026-01-15T10:02:00+01:00", ), TicketMessage { is_ghost: true, ..demo_message( 3, ict, "Sam Ict", "admin", "Intern: garantie loopt nog tot maart, eventueel omruilen via de leverancier.", "2026-01-15T10:05:00+01:00", ) }, TicketMessage { attachments: vec![TicketAttachment { id: 77, original_name: "foto-lampje.jpg".to_owned(), mime_type: "image/jpeg".to_owned(), file_size: 120_000, }], ..demo_message( 4, &me.email, &me.name, "user", "Gedaan, hij knippert nog steeds. Foto erbij.", "2026-01-15T13:39:00+01:00", ) }, ]; if id != DEMO_UNREAD { messages.truncate(1); messages[0].message_text = format!("{}.", ticket.title); } DEMO_REPLIES.with(|replies| { messages.extend(replies.borrow().get(&id).cloned().unwrap_or_default()); }); Some(TicketDetail { description: messages[0].message_text.clone(), participant_emails: vec![me.email.clone(), "jonas.ortega@example.com".to_owned()], messages, ticket, }) } fn demo_reply(id: u64, text: &str, email: &str) { let me = super::demo::token(); DEMO_REPLIES.with(|replies| { let mut replies = replies.borrow_mut(); let list = replies.entry(id).or_default(); list.push(demo_message( 100 + list.len() as u64, if email.is_empty() { &me.email } else { email }, &me.name, "user", text, &chrono::Local::now().to_rfc3339(), )); }); } #[cfg(test)] mod tests { use super::{DEMO_UNREAD, demo_detail, demo_tickets, mention_display, when}; use kvt_sleutels::tickets::Ticket; #[test] fn dates_are_dutch_and_local() { let shown = when("2026-01-15T13:39:00+01:00"); assert!(shown.starts_with("15 jan 2026") || shown.starts_with("16 jan 2026")); assert_eq!(when("geen datum"), "geen datum"); } #[test] fn demo_has_a_ghost_and_a_closed_ticket() { let detail = demo_detail(DEMO_UNREAD).unwrap(); assert!(detail.messages.iter().any(|message| message.is_ghost)); assert!(demo_tickets().iter().any(Ticket::is_closed)); } #[test] fn mentions_render_as_first_names() { let (shown, ranges) = mention_display( "Graag @dana.demo:examplecom", &["dana.demo@example.com".to_owned()], ); assert_eq!(shown, "Graag @Dana"); assert_eq!(ranges, [6..11]); } }