BlueGit

ict rusty-teams

Files

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

tickets.rs

tickets.rs 43.0 KiB Download Raw
1//! Asclepius-tegel: je tickets (zoals «Mijn tickets» op het web, plus aan jou
2//! toegewezen) links, het gesprek van het gekozen ticket rechts. Antwoorden kan
3//! hier; behandelen (status, toewijzing) blijft in Asclepius (fase 2).
4//!
5//! Ongelezen is lokaal (`kvt.asclepius.seen`): een ticket waarvan `updated_at`
6//! nieuwer is dan toen je het opende. Elke minuut `ticket_updates`.
7
8use std::collections::HashMap;
9use std::time::Duration;
10
11use chrono::{DateTime, Local};
12use gpui_kit::component::input::{Textarea, TextareaState};
13use gpui_kit::component::scroll::ScrollableElement as _;
14use gpui_kit::component::{h_flex, v_flex};
15use gpui_kit::prelude::FluentBuilder as _;
16use gpui_kit::*;
17use kvt_sleutels::format::date_time_nl;
18use kvt_sleutels::tickets::{
19 SeenTickets, TextPart, Ticket, TicketAttachment, TicketDetail, TicketFilter, TicketMessage,
20 mention_label, mention_token, split_mentions,
21};
22use kvt_sleutels::{CardsClient, ClientError};
23
24use super::modal::{primary_button, secondary_button};
25use super::tasks::{chip, muted, not_linked};
26use super::{Link, error_text, forget_token, is_demo, link, notice, token_and_client};
27use crate::app_state::AppHandle;
28use crate::i18n::tr;
29use crate::runtime;
30use crate::theme;
31use crate::views::widgets::symbol;
32
33pub const KVT_TICKETS_TAG: &str = "kvt-asclepius-tickets";
34const SEEN_META_KEY: &str = "kvt.asclepius.seen";
35const POLL_INTERVAL: Duration = Duration::from_secs(60);
36const HEADER_HEIGHT: f32 = 60.;
37const PAGE_PADDING: f32 = 20.;
38const LIST_WIDTH: f32 = 320.;
39const RADIUS: f32 = 10.;
40const BUBBLE_RADIUS: f32 = 14.;
41
42// Ghost-berichten zoals op het web (`.message.is-ghost`), ongeacht het thema.
43const GHOST_BG: u32 = 0x5b21b6;
44const GHOST_BORDER: u32 = 0xf9a8d4;
45const GHOST_TEXT: u32 = 0xfce7f3;
46
47#[derive(Clone)]
48enum List {
49 NotLinked,
50 Loading,
51 Loaded(Vec<Ticket>),
52 Failed(ClientError),
53}
54
55#[derive(Clone)]
56enum Detail {
57 Loading,
58 Loaded(TicketDetail),
59 Failed(ClientError),
60}
61
62pub(super) fn ticket_error(error: &ClientError) -> String {
63 match error {
64 ClientError::Forbidden | ClientError::NotFound => tr("kvt.tickets.not_found"),
65 ClientError::BadRequest => tr("kvt.tickets.failed"),
66 other => error_text(other),
67 }
68}
69
70/// `2026-01-15T13:39:00+01:00` → `15 jan 2026 13:39` (lokale tijd).
71pub(super) fn when(value: &str) -> String {
72 DateTime::parse_from_rfc3339(value.trim())
73 .map(|moment| date_time_nl(moment.with_timezone(&Local).naive_local()))
74 .unwrap_or_else(|_| value.get(..16).unwrap_or(value).replace('T', " "))
75}
76
77pub(super) fn status_label(status: &str) -> String {
78 let key = format!("kvt.tickets.status.{}", status.trim().replace(' ', "_"));
79 let label = tr(&key);
80 if label == key || label.is_empty() {
81 status.to_owned()
82 } else {
83 label
84 }
85}
86
87fn me(cx: &App) -> String {
88 match link(cx) {
89 Link::Linked(stored) => stored.email.to_lowercase(),
90 _ => String::new(),
91 }
92}
93
94// --- lokaal ongelezen ----------------------------------------------------------
95
96fn load_seen(cx: &App) -> SeenTickets {
97 cx.try_global::<AppHandle>()
98 .and_then(|handle| handle.0.read(cx).store.meta(SEEN_META_KEY).ok().flatten())
99 .map(|json| SeenTickets::from_json(&json))
100 .unwrap_or_default()
101}
102
103fn save_seen(seen: &SeenTickets, cx: &App) {
104 if let Some(handle) = cx.try_global::<AppHandle>() {
105 let _ = handle
106 .0
107 .read(cx)
108 .store
109 .set_meta(SEEN_META_KEY, &seen.to_json());
110 }
111}
112
113// --- gesprek van één ticket (tegel en ticketvenster) ----------------------------
114
115pub struct TicketThread {
116 id: u64,
117 detail: Detail,
118 reply: Entity<TextareaState>,
119 sending: bool,
120 error: Option<String>,
121 generation: u64,
122 scroll: ScrollHandle,
123}
124
125impl TicketThread {
126 pub(super) fn new(id: u64, window: &mut Window, cx: &mut Context<Self>) -> Self {
127 let reply = cx.new(|cx| {
128 TextareaState::new(window, cx)
129 .auto_grow(2, 8)
130 .placeholder(tr("kvt.tickets.reply_placeholder"))
131 });
132 let mut thread = TicketThread {
133 id,
134 detail: Detail::Loading,
135 reply,
136 sending: false,
137 error: None,
138 generation: 0,
139 scroll: ScrollHandle::new(),
140 };
141 thread.reload(cx);
142 thread
143 }
144
145 pub(super) fn id(&self) -> u64 {
146 self.id
147 }
148
149 pub(super) fn reload(&mut self, cx: &mut Context<Self>) {
150 self.generation += 1;
151 let generation = self.generation;
152 let id = self.id;
153 if is_demo(cx) {
154 self.detail = match demo_detail(id) {
155 Some(detail) => Detail::Loaded(detail),
156 None => Detail::Failed(ClientError::NotFound),
157 };
158 self.scroll.scroll_to_bottom();
159 cx.notify();
160 return;
161 }
162 let Some((token, client)) = token_and_client(cx) else {
163 return;
164 };
165 let loading = runtime::spawn(async move { client.asclepius_ticket(&token, id).await });
166 cx.spawn(async move |this, cx| {
167 let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
168 cx.update(|cx| {
169 if result == Err(ClientError::Unauthorized) {
170 forget_token(cx);
171 }
172 let opened = result.as_ref().ok().map(|detail| detail.ticket.clone());
173 this.update(cx, |this, cx| {
174 if this.generation != generation {
175 return;
176 }
177 let first = !matches!(this.detail, Detail::Loaded(_));
178 this.detail = match result {
179 Ok(detail) => Detail::Loaded(detail),
180 Err(error) => Detail::Failed(error),
181 };
182 if first {
183 this.scroll.scroll_to_bottom();
184 }
185 cx.notify();
186 })
187 .ok();
188 if let Some(ticket) = opened {
189 ticket_seen(&ticket, cx);
190 }
191 });
192 })
193 .detach();
194 }
195
196 fn mention(&mut self, email: &str, window: &mut Window, cx: &mut Context<Self>) {
197 let Some(token) = mention_token(email) else {
198 return;
199 };
200 let current = self.reply.read(cx).value().to_string();
201 let joined = if current.is_empty() || current.ends_with([' ', '\n']) {
202 format!("{current}{token} ")
203 } else {
204 format!("{current} {token} ")
205 };
206 self.reply.update(cx, |reply, cx| {
207 reply.set_value(joined, window, cx);
208 reply.focus(window, cx);
209 });
210 }
211
212 fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
213 if self.sending {
214 return;
215 }
216 let text = self.reply.read(cx).value().trim().to_owned();
217 if text.is_empty() {
218 return;
219 }
220 self.sending = true;
221 self.error = None;
222 cx.notify();
223 if is_demo(cx) {
224 demo_reply(self.id, &text, &me(cx));
225 self.sending = false;
226 self.reply
227 .update(cx, |reply, cx| reply.set_value("", window, cx));
228 self.scroll.scroll_to_bottom();
229 self.reload(cx);
230 refresh_list(cx);
231 return;
232 }
233 let Some((token, client)) = token_and_client(cx) else {
234 self.sending = false;
235 return;
236 };
237 let id = self.id;
238 let sending =
239 runtime::spawn(async move { client.asclepius_reply(&token, id, &text).await });
240 let reply = self.reply.clone();
241 cx.spawn_in(window, async move |this, cx| {
242 let result = sending.await.unwrap_or(Err(ClientError::Unavailable));
243 this.update_in(cx, |this, window, cx| {
244 this.sending = false;
245 match &result {
246 Ok(()) => {
247 reply.update(cx, |reply, cx| reply.set_value("", window, cx));
248 this.scroll.scroll_to_bottom();
249 this.reload(cx);
250 refresh_list(cx);
251 }
252 Err(error) => {
253 if *error == ClientError::Unauthorized {
254 forget_token(cx);
255 }
256 this.error = Some(ticket_error(error));
257 }
258 }
259 cx.notify();
260 })
261 .ok();
262 })
263 .detach();
264 }
265
266 fn header(&self, detail: &TicketDetail) -> Div {
267 let ticket = &detail.ticket;
268 let mut meta = vec![format!("#{}", ticket.id), status_label(&ticket.status)];
269 if !ticket.category.is_empty() {
270 meta.push(if ticket.subcategory.is_empty() {
271 ticket.category.clone()
272 } else {
273 format!("{} › {}", ticket.category, ticket.subcategory)
274 });
275 }
276 if !ticket.created_at.is_empty() {
277 meta.push(when(&ticket.created_at));
278 }
279 v_flex()
280 .w_full()
281 .flex_none()
282 .px(px(PAGE_PADDING))
283 .py(px(12.))
284 .gap(px(2.))
285 .border_b_1()
286 .border_color(theme::border())
287 .child(
288 div()
289 .text_size(px(16.))
290 .font_weight(FontWeight::BOLD)
291 .text_color(theme::text())
292 .child(ticket.title.clone()),
293 )
294 .child(
295 div()
296 .text_size(px(12.))
297 .text_color(theme::text_muted())
298 .child(meta.join(" · ")),
299 )
300 }
301
302 fn message(
303 &self,
304 index: usize,
305 message: &TicketMessage,
306 known: &[String],
307 cx: &mut Context<Self>,
308 ) -> AnyElement {
309 let ghost = message.is_ghost;
310 let from_ict = message.sender_role == "admin";
311 let text_color = if ghost {
312 rgb(GHOST_TEXT).into()
313 } else {
314 theme::text()
315 };
316 let muted_color = if ghost {
317 rgb(GHOST_TEXT).into()
318 } else {
319 theme::text_muted()
320 };
321 let mention_color: Hsla = if ghost {
322 rgb(GHOST_BORDER).into()
323 } else {
324 theme::accent_text()
325 };
326 let mut role = Vec::new();
327 if from_ict {
328 role.push(tr("kvt.tickets.ict"));
329 }
330 if ghost {
331 role.push(tr("kvt.tickets.ghost"));
332 }
333 let head = h_flex()
334 .w_full()
335 .gap(px(8.))
336 .items_center()
337 .child(
338 div()
339 .text_size(px(13.))
340 .font_weight(FontWeight::SEMIBOLD)
341 .text_color(text_color)
342 .child(message.sender_name()),
343 )
344 .when(!role.is_empty(), |row| {
345 row.child(
346 div()
347 .text_size(px(11.))
348 .text_color(muted_color)
349 .child(role.join(" · ")),
350 )
351 })
352 .child(div().flex_1())
353 .child(
354 div()
355 .text_size(px(11.))
356 .text_color(muted_color)
357 .child(when(&message.created_at)),
358 );
359 let body = message_text(&message.message_text, known, mention_color);
360 let attachments: Vec<AnyElement> = message
361 .attachments
362 .iter()
363 .enumerate()
364 .map(|(position, attachment)| {
365 attachment_chip(index, position, attachment, ghost, cx).into_any_element()
366 })
367 .collect();
368 v_flex()
369 .id(ElementId::Name(
370 format!("kvt-ticket-message-{index}").into(),
371 ))
372 .w_full()
373 .p(px(12.))
374 .gap(px(6.))
375 .rounded(px(BUBBLE_RADIUS))
376 .map(|bubble| {
377 if ghost {
378 bubble
379 .bg(rgb(GHOST_BG))
380 .border_2()
381 .border_color(rgb(GHOST_BORDER))
382 } else if from_ict {
383 bubble.bg(theme::popup_hover())
384 } else {
385 bubble.bg(theme::surface_raised())
386 }
387 })
388 .child(head)
389 .child(div().text_size(px(13.)).text_color(text_color).child(body))
390 .when(!attachments.is_empty(), |bubble| {
391 bubble.child(h_flex().flex_wrap().gap(px(6.)).children(attachments))
392 })
393 .into_any_element()
394 }
395
396 fn composer(&self, detail: &TicketDetail, cx: &mut Context<Self>) -> Div {
397 let me = me(cx);
398 let mut people: Vec<String> = detail
399 .participant_emails
400 .iter()
401 .chain(std::iter::once(&detail.ticket.assigned_email))
402 .map(|email| email.to_lowercase())
403 .filter(|email| !email.is_empty() && *email != me)
404 .collect();
405 people.sort();
406 people.dedup();
407 let names = sender_names(detail);
408 v_flex()
409 .w_full()
410 .flex_none()
411 .px(px(PAGE_PADDING))
412 .py(px(12.))
413 .gap(px(8.))
414 .border_t_1()
415 .border_color(theme::border())
416 .when(!people.is_empty(), |column| {
417 column.child(
418 h_flex()
419 .w_full()
420 .flex_wrap()
421 .gap(px(6.))
422 .items_center()
423 .child(
424 div()
425 .text_size(px(12.))
426 .text_color(theme::text_muted())
427 .child(tr("kvt.tickets.mention")),
428 )
429 .children(people.into_iter().enumerate().map(|(index, email)| {
430 let label = names
431 .get(&email)
432 .cloned()
433 .unwrap_or_else(|| kvt_sleutels::ponos::name_from_email(&email));
434 chip(
435 format!("kvt-ticket-mention-{index}").into(),
436 format!("@{label}"),
437 false,
438 )
439 .on_click(cx.listener(
440 move |this, _, window, cx| this.mention(&email, window, cx),
441 ))
442 })),
443 )
444 })
445 .child(Textarea::new(&self.reply))
446 .children(self.error.clone().map(|error| {
447 div()
448 .text_size(px(13.))
449 .text_color(theme::red_soft())
450 .child(error)
451 }))
452 .child(
453 h_flex()
454 .w_full()
455 .gap(px(8.))
456 .items_center()
457 .when(detail.ticket.is_closed(), |row| {
458 row.child(
459 div()
460 .text_size(px(12.))
461 .text_color(theme::text_muted())
462 .child(tr("kvt.tickets.closed_hint")),
463 )
464 })
465 .child(div().flex_1())
466 .child(
467 primary_button(
468 "kvt-ticket-send",
469 tr(if self.sending {
470 "kvt.tickets.sending"
471 } else {
472 "kvt.tickets.send"
473 }),
474 )
475 .on_click(cx.listener(|this, _, window, cx| this.send(window, cx))),
476 ),
477 )
478 }
479}
480
481fn sender_names(detail: &TicketDetail) -> HashMap<String, String> {
482 detail
483 .messages
484 .iter()
485 .filter(|message| !message.sender_display_name.trim().is_empty())
486 .map(|message| {
487 (
488 message.sender_email.to_lowercase(),
489 message.sender_display_name.trim().to_owned(),
490 )
491 })
492 .collect()
493}
494
495/// Tekst met Asclepius-vermeldingen als `@Voornaam` (vet, accentkleur), zoals op het web.
496fn message_text(text: &str, known: &[String], mention: Hsla) -> StyledText {
497 let (shown, ranges) = mention_display(text, known);
498 let style = HighlightStyle {
499 color: Some(mention),
500 font_weight: Some(FontWeight::BOLD),
501 ..HighlightStyle::default()
502 };
503 StyledText::new(shown).with_highlights(ranges.into_iter().map(|range| (range, style)))
504}
505
506/// Getoonde tekst en de plekken van de vermeldingen daarin.
507fn mention_display(text: &str, known: &[String]) -> (String, Vec<std::ops::Range<usize>>) {
508 let mut shown = String::new();
509 let mut ranges = Vec::new();
510 for part in split_mentions(text.trim_end(), known) {
511 match part {
512 TextPart::Text(text) => shown.push_str(&text),
513 TextPart::Mention { key, email } => {
514 let start = shown.len();
515 shown.push_str(&mention_label(&key, email.as_deref()));
516 ranges.push(start..shown.len());
517 }
518 }
519 }
520 (shown, ranges)
521}
522
523fn attachment_chip(
524 message: usize,
525 position: usize,
526 attachment: &TicketAttachment,
527 ghost: bool,
528 cx: &mut Context<TicketThread>,
529) -> Stateful<Div> {
530 let attachment = attachment.clone();
531 let name = attachment.original_name.clone();
532 h_flex()
533 .id(ElementId::Name(
534 format!("kvt-ticket-attachment-{message}-{position}").into(),
535 ))
536 .h(px(28.))
537 .px(px(10.))
538 .gap(px(6.))
539 .items_center()
540 .rounded(px(6.))
541 .cursor_pointer()
542 .text_size(px(12.))
543 .map(|chip| {
544 if ghost {
545 chip.border_1()
546 .border_color(rgb(GHOST_BORDER))
547 .text_color(rgb(GHOST_TEXT))
548 } else {
549 chip.bg(theme::popup_hover())
550 .text_color(theme::text())
551 .hover(|chip| chip.bg(theme::row_hover()))
552 }
553 })
554 .on_click(cx.listener(move |_, _, _, cx| open_attachment(attachment.clone(), cx)))
555 .child(symbol(
556 "attach_file",
557 14.,
558 if ghost {
559 rgb(GHOST_TEXT).into()
560 } else {
561 theme::text_muted()
562 },
563 ))
564 .child(name)
565}
566
567/// Bijlagen gaan alleen met de token: ophalen, in de tijdelijke map zetten en openen.
568fn open_attachment(attachment: TicketAttachment, cx: &mut App) {
569 if is_demo(cx) {
570 notice(tr("kvt.tickets.demo_attachment"), cx);
571 return;
572 }
573 let Some((token, client)) = token_and_client(cx) else {
574 return;
575 };
576 let id = attachment.id;
577 let name: String = attachment
578 .original_name
579 .chars()
580 .filter(|c| c.is_alphanumeric() || "-_. ".contains(*c))
581 .collect();
582 let name = if name.trim().is_empty() {
583 "bijlage".to_owned()
584 } else {
585 name
586 };
587 let downloading = runtime::spawn(async move {
588 let bytes = client.asclepius_attachment(&token, id).await?;
589 let directory = std::env::temp_dir().join("rusty-teams-asclepius");
590 std::fs::create_dir_all(&directory).map_err(|_| ClientError::Unavailable)?;
591 let path = directory.join(format!("{id}-{name}"));
592 std::fs::write(&path, bytes).map_err(|_| ClientError::Unavailable)?;
593 Ok::<_, ClientError>(path)
594 });
595 cx.spawn(async move |cx| {
596 let result = downloading.await.unwrap_or(Err(ClientError::Unavailable));
597 cx.update(|cx| match result {
598 Ok(path) => cx.open_with_system(&path),
599 Err(error) => {
600 if error == ClientError::Unauthorized {
601 forget_token(cx);
602 }
603 notice(ticket_error(&error), cx);
604 }
605 });
606 })
607 .detach();
608}
609
610impl Render for TicketThread {
611 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
612 let detail = match &self.detail {
613 Detail::Loading => {
614 return v_flex()
615 .size_full()
616 .child(muted(tr("kvt.card.loading")).px(px(PAGE_PADDING)))
617 .into_any_element();
618 }
619 Detail::Failed(error) => {
620 return v_flex()
621 .size_full()
622 .child(muted(ticket_error(error)).px(px(PAGE_PADDING)))
623 .into_any_element();
624 }
625 Detail::Loaded(detail) => detail.clone(),
626 };
627 let mut known = detail.participant_emails.clone();
628 known.push(detail.ticket.assigned_email.clone());
629 known.push(detail.ticket.user_email.clone());
630 known.extend(
631 detail
632 .messages
633 .iter()
634 .map(|message| message.sender_email.clone()),
635 );
636 let messages: Vec<AnyElement> = detail
637 .messages
638 .iter()
639 .enumerate()
640 .map(|(index, message)| self.message(index, message, &known, cx))
641 .collect();
642 v_flex()
643 .debug_selector(|| "kvt-ticket-thread".into())
644 .size_full()
645 .min_h_0()
646 .child(self.header(&detail))
647 .child(
648 div()
649 .id("kvt-ticket-messages")
650 .flex_1()
651 .min_h_0()
652 .overflow_y_scroll()
653 .track_scroll(&self.scroll)
654 .child(
655 v_flex()
656 .w_full()
657 .px(px(PAGE_PADDING))
658 .py(px(12.))
659 .gap(px(10.))
660 .children(messages),
661 ),
662 )
663 .child(self.composer(&detail, cx))
664 .into_any_element()
665 }
666}
667
668// --- tegelpagina -------------------------------------------------------------
669
670pub struct TicketsPage {
671 filter: TicketFilter,
672 list: List,
673 /// Open tickets, ook als het filter op Afgehandeld staat (badge in de rail).
674 open: Vec<Ticket>,
675 selected: Option<Entity<TicketThread>>,
676 seen: SeenTickets,
677 generation: u64,
678 since: Option<String>,
679 polling: bool,
680}
681
682/// De pagina (eenmalig aangemaakt; ook voor de badge als de tegel dicht is).
683fn page(cx: &mut App) -> Option<Entity<TicketsPage>> {
684 if !super::installed(cx) {
685 return None;
686 }
687 if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() {
688 return Some(page);
689 }
690 let page = cx.new(TicketsPage::new);
691 cx.global_mut::<super::Kvt>().tickets = Some(page.clone());
692 Some(page)
693}
694
695/// De tegel als element van het hoofdpaneel.
696pub fn tickets_view(cx: &mut App) -> AnyElement {
697 match page(cx) {
698 Some(page) => div()
699 .flex_1()
700 .min_w_0()
701 .h_full()
702 .child(page)
703 .into_any_element(),
704 None => div().into_any_element(),
705 }
706}
707
708/// De tegel is geopend: vers ophalen.
709pub fn tickets_opened(cx: &mut App) {
710 if let Some(page) = page(cx) {
711 page.update(cx, |page, cx| page.reload(cx));
712 }
713}
714
715/// Aantal ongelezen open tickets, voor de badge op de tegel.
716pub fn tickets_unread(cx: &mut App) -> usize {
717 if !matches!(link(cx), Link::Linked(_)) {
718 return 0;
719 }
720 page(cx).map_or(0, |page| {
721 let page = page.read(cx);
722 page.seen.unread_count(&page.open)
723 })
724}
725
726fn refresh_list(cx: &mut App) {
727 if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() {
728 page.update(cx, |page, cx| page.reload(cx));
729 }
730}
731
732/// Een ticket is bekeken (tegel of ticketvenster): niet meer ongelezen.
733pub(super) fn ticket_seen(ticket: &Ticket, cx: &mut App) {
734 if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() {
735 page.update(cx, |page, cx| {
736 if page.seen.mark(ticket) {
737 save_seen(&page.seen, cx);
738 cx.notify();
739 }
740 });
741 }
742}
743
744impl TicketsPage {
745 fn new(cx: &mut Context<Self>) -> Self {
746 let mut page = TicketsPage {
747 filter: TicketFilter::Open,
748 list: List::Loading,
749 open: Vec::new(),
750 selected: None,
751 seen: load_seen(cx),
752 generation: 0,
753 since: None,
754 polling: false,
755 };
756 page.reload(cx);
757 page.start_polling(cx);
758 page
759 }
760
761 fn reload(&mut self, cx: &mut Context<Self>) {
762 self.generation += 1;
763 let generation = self.generation;
764 let filter = self.filter;
765 if is_demo(cx) {
766 let all = demo_tickets();
767 self.open = all.iter().filter(|t| !t.is_closed()).cloned().collect();
768 if self.seen.initialize(&self.open) {
769 // Demo: één ticket ongelezen, om de stip te tonen.
770 self.seen.seen.insert(DEMO_UNREAD, String::new());
771 }
772 self.list = List::Loaded(
773 all.into_iter()
774 .filter(|t| t.is_closed() == (filter == TicketFilter::Closed))
775 .collect(),
776 );
777 cx.notify();
778 return;
779 }
780 let Some((token, client)) = token_and_client(cx) else {
781 self.list = List::NotLinked;
782 cx.notify();
783 return;
784 };
785 if !matches!(self.list, List::Loaded(_)) {
786 self.list = List::Loading;
787 }
788 let loading = runtime::spawn(async move {
789 let open = client.asclepius_tickets(&token, TicketFilter::Open).await?;
790 let shown = match filter {
791 TicketFilter::Open => open.clone(),
792 TicketFilter::Closed => {
793 client
794 .asclepius_tickets(&token, TicketFilter::Closed)
795 .await?
796 }
797 };
798 Ok::<_, ClientError>((open, shown))
799 });
800 cx.spawn(async move |this, cx| {
801 let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
802 cx.update(|cx| {
803 if matches!(result, Err(ClientError::Unauthorized)) {
804 forget_token(cx);
805 }
806 this.update(cx, |this, cx| {
807 if this.generation != generation {
808 return;
809 }
810 match result {
811 Ok((open, shown)) => {
812 if this.seen.initialize(&open) {
813 save_seen(&this.seen, cx);
814 }
815 this.since = Some(chrono::Utc::now().to_rfc3339());
816 this.open = open;
817 this.list = List::Loaded(shown);
818 }
819 Err(ClientError::Unauthorized) => this.list = List::NotLinked,
820 Err(error) => this.list = List::Failed(error),
821 }
822 cx.notify();
823 cx.refresh_windows();
824 })
825 .ok();
826 });
827 })
828 .detach();
829 }
830
831 /// Elke minuut `ticket_updates`; bij wijzigingen de lijst en het open ticket opnieuw.
832 fn start_polling(&mut self, cx: &mut Context<Self>) {
833 if self.polling || is_demo(cx) {
834 return;
835 }
836 self.polling = true;
837 cx.spawn(async move |this, cx| {
838 loop {
839 cx.background_executor().timer(POLL_INTERVAL).await;
840 let Ok(Some((since, token))) = this.update(cx, |this, cx| {
841 let since = this.since.clone()?;
842 let (token, client) = token_and_client(cx)?;
843 Some((since, (token, client)))
844 }) else {
845 if this.upgrade().is_none() {
846 return;
847 }
848 continue;
849 };
850 let (token, client): (String, CardsClient) = token;
851 let polling =
852 runtime::spawn(async move { client.asclepius_updates(&token, &since).await });
853 let result = polling.await.unwrap_or(Err(ClientError::Unavailable));
854 let alive = this.update(cx, |this, cx| {
855 if let Ok((changed, server_time)) = result {
856 if !server_time.is_empty() {
857 this.since = Some(server_time);
858 }
859 if !changed.is_empty() {
860 let open_id = this.selected.as_ref().map(|thread| thread.read(cx).id());
861 if let Some(thread) = this.selected.clone()
862 && changed.iter().any(|t| Some(t.id) == open_id)
863 {
864 thread.update(cx, |thread, cx| thread.reload(cx));
865 }
866 this.reload(cx);
867 }
868 }
869 });
870 if alive.is_err() {
871 return;
872 }
873 }
874 })
875 .detach();
876 }
877
878 fn set_filter(&mut self, filter: TicketFilter, cx: &mut Context<Self>) {
879 if self.filter == filter {
880 return;
881 }
882 self.filter = filter;
883 self.list = List::Loading;
884 self.reload(cx);
885 }
886
887 fn select(&mut self, ticket: &Ticket, window: &mut Window, cx: &mut Context<Self>) {
888 if self
889 .selected
890 .as_ref()
891 .is_some_and(|thread| thread.read(cx).id() == ticket.id)
892 {
893 return;
894 }
895 let id = ticket.id;
896 self.selected = Some(cx.new(|cx| TicketThread::new(id, window, cx)));
897 if self.seen.mark(ticket) {
898 save_seen(&self.seen, cx);
899 }
900 cx.notify();
901 cx.refresh_windows();
902 }
903
904 fn header(&self, cx: &mut Context<Self>) -> Div {
905 h_flex()
906 .h(px(HEADER_HEIGHT))
907 .flex_none()
908 .px(px(PAGE_PADDING))
909 .gap(px(8.))
910 .items_center()
911 .child(
912 div()
913 .flex_1()
914 .min_w_0()
915 .truncate()
916 .text_size(px(16.))
917 .font_weight(FontWeight::BOLD)
918 .text_color(theme::text())
919 .child(tr("kvt.tickets.title")),
920 )
921 .child(
922 secondary_button("kvt-tickets-refresh", "refresh", tr("kvt.card.refresh"))
923 .on_click(cx.listener(|this, _, _, cx| this.reload(cx))),
924 )
925 }
926
927 fn list(&self, cx: &mut Context<Self>) -> AnyElement {
928 let filters = h_flex()
929 .w_full()
930 .flex_none()
931 .px(px(12.))
932 .pb(px(8.))
933 .gap(px(6.))
934 .child(
935 chip(
936 "kvt-tickets-filter-open".into(),
937 tr("kvt.tickets.filter_open"),
938 self.filter == TicketFilter::Open,
939 )
940 .on_click(cx.listener(|this, _, _, cx| this.set_filter(TicketFilter::Open, cx))),
941 )
942 .child(
943 chip(
944 "kvt-tickets-filter-closed".into(),
945 tr("kvt.tickets.filter_closed"),
946 self.filter == TicketFilter::Closed,
947 )
948 .on_click(cx.listener(|this, _, _, cx| this.set_filter(TicketFilter::Closed, cx))),
949 );
950 let selected = self.selected.as_ref().map(|thread| thread.read(cx).id());
951 let rows: AnyElement = match &self.list {
952 List::Loading | List::NotLinked => {
953 muted(tr("kvt.card.loading")).px(px(12.)).into_any_element()
954 }
955 List::Failed(error) => muted(ticket_error(error)).px(px(12.)).into_any_element(),
956 List::Loaded(tickets) if tickets.is_empty() => muted(tr(match self.filter {
957 TicketFilter::Open => "kvt.tickets.empty_open",
958 TicketFilter::Closed => "kvt.tickets.empty_closed",
959 }))
960 .px(px(12.))
961 .into_any_element(),
962 List::Loaded(tickets) => v_flex()
963 .w_full()
964 .px(px(8.))
965 .gap(px(2.))
966 .children(tickets.iter().enumerate().map(|(index, ticket)| {
967 let unread = self.seen.is_unread(ticket);
968 let active = selected == Some(ticket.id);
969 let row_ticket = ticket.clone();
970 v_flex()
971 .id(ElementId::Name(format!("kvt-tickets-row-{index}").into()))
972 .debug_selector(move || format!("kvt-tickets/row/{index}"))
973 .w_full()
974 .px(px(10.))
975 .py(px(8.))
976 .gap(px(2.))
977 .rounded(px(6.))
978 .cursor_pointer()
979 .map(|row| {
980 if active {
981 row.bg(theme::selection())
982 } else {
983 row.hover(|row| row.bg(theme::row_hover()))
984 }
985 })
986 .on_click(cx.listener(move |this, _, window, cx| {
987 this.select(&row_ticket, window, cx)
988 }))
989 .child(
990 h_flex()
991 .w_full()
992 .gap(px(6.))
993 .items_center()
994 .child(
995 div()
996 .flex_1()
997 .min_w_0()
998 .truncate()
999 .text_size(px(13.))
1000 .text_color(theme::text_strong())
1001 .when(unread, |title| title.font_weight(FontWeight::BOLD))
1002 .child(ticket.title.clone()),
1003 )
1004 .when(unread, |row| {
1005 row.child(
1006 div()
1007 .size(px(8.))
1008 .flex_none()
1009 .rounded_full()
1010 .bg(theme::accent()),
1011 )
1012 }),
1013 )
1014 .child(
1015 div()
1016 .truncate()
1017 .text_size(px(12.))
1018 .text_color(theme::text_muted())
1019 .child(format!(
1020 "#{} · {} · {}",
1021 ticket.id,
1022 status_label(&ticket.status),
1023 when(&ticket.updated_at)
1024 )),
1025 )
1026 }))
1027 .into_any_element(),
1028 };
1029 v_flex()
1030 .id("kvt-tickets-list")
1031 .w(px(LIST_WIDTH))
1032 .h_full()
1033 .flex_none()
1034 .border_r_1()
1035 .border_color(theme::border())
1036 .child(filters)
1037 .child(
1038 div()
1039 .id("kvt-tickets-rows")
1040 .flex_1()
1041 .min_h_0()
1042 .overflow_y_scrollbar()
1043 .child(rows),
1044 )
1045 .into_any_element()
1046 }
1047}
1048
1049impl Render for TicketsPage {
1050 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1051 let linked = matches!(link(cx), Link::Linked(_));
1052 if !linked && !is_demo(cx) {
1053 self.list = List::NotLinked;
1054 self.selected = None;
1055 self.open.clear();
1056 } else if matches!(self.list, List::NotLinked) {
1057 self.reload(cx);
1058 }
1059 let body = if !linked {
1060 v_flex()
1061 .p(px(PAGE_PADDING))
1062 .max_w(px(560.))
1063 .child(not_linked())
1064 .into_any_element()
1065 } else {
1066 h_flex()
1067 .flex_1()
1068 .min_h_0()
1069 .w_full()
1070 .child(self.list(cx))
1071 .child(
1072 div()
1073 .flex_1()
1074 .min_w_0()
1075 .h_full()
1076 .child(match &self.selected {
1077 Some(thread) => thread.clone().into_any_element(),
1078 None => muted(tr("kvt.tickets.pick"))
1079 .px(px(PAGE_PADDING))
1080 .into_any_element(),
1081 }),
1082 )
1083 .into_any_element()
1084 };
1085 v_flex()
1086 .debug_selector(|| KVT_TICKETS_TAG.into())
1087 .relative()
1088 .size_full()
1089 .rounded(px(RADIUS))
1090 .bg(theme::surface())
1091 .overflow_hidden()
1092 .child(self.header(cx))
1093 .child(body)
1094 }
1095}
1096
1097// --- demo ------------------------------------------------------------------------
1098
1099const DEMO_UNREAD: u64 = 4102;
1100
1101thread_local! {
1102 static DEMO_REPLIES: std::cell::RefCell<HashMap<u64, Vec<TicketMessage>>> =
1103 std::cell::RefCell::new(HashMap::new());
1104}
1105
1106fn demo_ticket(id: u64, title: &str, status: &str, category: &str, updated: &str) -> Ticket {
1107 Ticket {
1108 id,
1109 title: title.to_owned(),
1110 category: category.to_owned(),
1111 user_email: super::demo::token().email,
1112 assigned_email: "ict.medewerker@example.com".to_owned(),
1113 status: status.to_owned(),
1114 created_at: "2026-01-12T09:15:00+01:00".to_owned(),
1115 updated_at: updated.to_owned(),
1116 message_count: 3,
1117 ..Ticket::default()
1118 }
1119}
1120
1121pub(super) fn demo_tickets() -> Vec<Ticket> {
1122 vec![
1123 Ticket {
1124 subcategory: "Laptop".to_owned(),
1125 ..demo_ticket(
1126 DEMO_UNREAD,
1127 "Laptop start niet meer op",
1128 "in behandeling",
1129 "Hardware",
1130 "2026-01-15T13:39:00+01:00",
1131 )
1132 },
1133 demo_ticket(
1134 4098,
1135 "Toegang tot gedeelde map Projecten",
1136 "afwachtende op gebruiker",
1137 "Rechten en toegang",
1138 "2026-01-14T16:02:00+01:00",
1139 ),
1140 demo_ticket(
1141 4090,
1142 "Nieuwe headset",
1143 "ingediend",
1144 "Hardware bestellen",
1145 "2026-01-13T10:20:00+01:00",
1146 ),
1147 demo_ticket(
1148 4012,
1149 "Printer op kantoor geeft een fout",
1150 "afgehandeld",
1151 "Hardware",
1152 "2026-01-08T11:00:00+01:00",
1153 ),
1154 ]
1155}
1156
1157fn demo_message(
1158 id: u64,
1159 email: &str,
1160 name: &str,
1161 role: &str,
1162 text: &str,
1163 at: &str,
1164) -> TicketMessage {
1165 TicketMessage {
1166 id,
1167 sender_email: email.to_owned(),
1168 sender_role: role.to_owned(),
1169 sender_display_name: name.to_owned(),
1170 message_text: text.to_owned(),
1171 created_at: at.to_owned(),
1172 ..TicketMessage::default()
1173 }
1174}
1175
1176pub(super) fn demo_detail(id: u64) -> Option<TicketDetail> {
1177 let ticket = demo_tickets().into_iter().find(|ticket| ticket.id == id)?;
1178 let me = super::demo::token();
1179 let ict = "ict.medewerker@example.com";
1180 let mut messages = vec![
1181 demo_message(
1182 1,
1183 &me.email,
1184 &me.name,
1185 "user",
1186 "Mijn laptop gaat niet meer aan sinds vanochtend. Het lampje knippert oranje.",
1187 "2026-01-15T09:15:00+01:00",
1188 ),
1189 demo_message(
1190 2,
1191 ict,
1192 "Sam Ict",
1193 "admin",
1194 "Dank je. Kun je de lader een minuut loskoppelen en het opnieuw proberen? @dana.demo:examplecom",
1195 "2026-01-15T10:02:00+01:00",
1196 ),
1197 TicketMessage {
1198 is_ghost: true,
1199 ..demo_message(
1200 3,
1201 ict,
1202 "Sam Ict",
1203 "admin",
1204 "Intern: garantie loopt nog tot maart, eventueel omruilen via de leverancier.",
1205 "2026-01-15T10:05:00+01:00",
1206 )
1207 },
1208 TicketMessage {
1209 attachments: vec![TicketAttachment {
1210 id: 77,
1211 original_name: "foto-lampje.jpg".to_owned(),
1212 mime_type: "image/jpeg".to_owned(),
1213 file_size: 120_000,
1214 }],
1215 ..demo_message(
1216 4,
1217 &me.email,
1218 &me.name,
1219 "user",
1220 "Gedaan, hij knippert nog steeds. Foto erbij.",
1221 "2026-01-15T13:39:00+01:00",
1222 )
1223 },
1224 ];
1225 if id != DEMO_UNREAD {
1226 messages.truncate(1);
1227 messages[0].message_text = format!("{}.", ticket.title);
1228 }
1229 DEMO_REPLIES.with(|replies| {
1230 messages.extend(replies.borrow().get(&id).cloned().unwrap_or_default());
1231 });
1232 Some(TicketDetail {
1233 description: messages[0].message_text.clone(),
1234 participant_emails: vec![me.email.clone(), "jonas.ortega@example.com".to_owned()],
1235 messages,
1236 ticket,
1237 })
1238}
1239
1240fn demo_reply(id: u64, text: &str, email: &str) {
1241 let me = super::demo::token();
1242 DEMO_REPLIES.with(|replies| {
1243 let mut replies = replies.borrow_mut();
1244 let list = replies.entry(id).or_default();
1245 list.push(demo_message(
1246 100 + list.len() as u64,
1247 if email.is_empty() { &me.email } else { email },
1248 &me.name,
1249 "user",
1250 text,
1251 &chrono::Local::now().to_rfc3339(),
1252 ));
1253 });
1254}
1255
1256#[cfg(test)]
1257mod tests {
1258 use super::{DEMO_UNREAD, demo_detail, demo_tickets, mention_display, when};
1259 use kvt_sleutels::tickets::Ticket;
1260
1261 #[test]
1262 fn dates_are_dutch_and_local() {
1263 let shown = when("2026-01-15T13:39:00+01:00");
1264 assert!(shown.starts_with("15 jan 2026") || shown.starts_with("16 jan 2026"));
1265 assert_eq!(when("geen datum"), "geen datum");
1266 }
1267
1268 #[test]
1269 fn demo_has_a_ghost_and_a_closed_ticket() {
1270 let detail = demo_detail(DEMO_UNREAD).unwrap();
1271 assert!(detail.messages.iter().any(|message| message.is_ghost));
1272 assert!(demo_tickets().iter().any(Ticket::is_closed));
1273 }
1274
1275 #[test]
1276 fn mentions_render_as_first_names() {
1277 let (shown, ranges) = mention_display(
1278 "Graag @dana.demo:examplecom",
1279 &["dana.demo@example.com".to_owned()],
1280 );
1281 assert_eq!(shown, "Graag @Dana");
1282 assert_eq!(ranges, [6..11]);
1283 }
1284}