BlueGit

ict rusty-teams

Files

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

tickets.rs

tickets.rs 43.7 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/// Net aangemaakt: lijst opnieuw en het nieuwe ticket openen (als de tegel bestaat).
733pub(super) fn created(id: u64, cx: &mut App) {
734 let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() else {
735 return;
736 };
737 let Some(window) = cx.active_window() else {
738 page.update(cx, |page, cx| page.reload(cx));
739 return;
740 };
741 window
742 .update(cx, |_, window, cx| {
743 page.update(cx, |page, cx| {
744 page.filter = TicketFilter::Open;
745 page.selected = Some(cx.new(|cx| TicketThread::new(id, window, cx)));
746 page.reload(cx);
747 })
748 })
749 .ok();
750}
751
752/// Een ticket is bekeken (tegel of ticketvenster): niet meer ongelezen.
753pub(super) fn ticket_seen(ticket: &Ticket, cx: &mut App) {
754 if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() {
755 page.update(cx, |page, cx| {
756 if page.seen.mark(ticket) {
757 save_seen(&page.seen, cx);
758 cx.notify();
759 }
760 });
761 }
762}
763
764impl TicketsPage {
765 fn new(cx: &mut Context<Self>) -> Self {
766 let mut page = TicketsPage {
767 filter: TicketFilter::Open,
768 list: List::Loading,
769 open: Vec::new(),
770 selected: None,
771 seen: load_seen(cx),
772 generation: 0,
773 since: None,
774 polling: false,
775 };
776 page.reload(cx);
777 page.start_polling(cx);
778 page
779 }
780
781 fn reload(&mut self, cx: &mut Context<Self>) {
782 self.generation += 1;
783 let generation = self.generation;
784 let filter = self.filter;
785 if is_demo(cx) {
786 let all = demo_tickets();
787 self.open = all.iter().filter(|t| !t.is_closed()).cloned().collect();
788 if self.seen.initialize(&self.open) {
789 // Demo: één ticket ongelezen, om de stip te tonen.
790 self.seen.seen.insert(DEMO_UNREAD, String::new());
791 }
792 self.list = List::Loaded(
793 all.into_iter()
794 .filter(|t| t.is_closed() == (filter == TicketFilter::Closed))
795 .collect(),
796 );
797 cx.notify();
798 return;
799 }
800 let Some((token, client)) = token_and_client(cx) else {
801 self.list = List::NotLinked;
802 cx.notify();
803 return;
804 };
805 if !matches!(self.list, List::Loaded(_)) {
806 self.list = List::Loading;
807 }
808 let loading = runtime::spawn(async move {
809 let open = client.asclepius_tickets(&token, TicketFilter::Open).await?;
810 let shown = match filter {
811 TicketFilter::Open => open.clone(),
812 TicketFilter::Closed => {
813 client
814 .asclepius_tickets(&token, TicketFilter::Closed)
815 .await?
816 }
817 };
818 Ok::<_, ClientError>((open, shown))
819 });
820 cx.spawn(async move |this, cx| {
821 let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
822 cx.update(|cx| {
823 if matches!(result, Err(ClientError::Unauthorized)) {
824 forget_token(cx);
825 }
826 this.update(cx, |this, cx| {
827 if this.generation != generation {
828 return;
829 }
830 match result {
831 Ok((open, shown)) => {
832 if this.seen.initialize(&open) {
833 save_seen(&this.seen, cx);
834 }
835 this.since = Some(chrono::Utc::now().to_rfc3339());
836 this.open = open;
837 this.list = List::Loaded(shown);
838 }
839 Err(ClientError::Unauthorized) => this.list = List::NotLinked,
840 Err(error) => this.list = List::Failed(error),
841 }
842 cx.notify();
843 cx.refresh_windows();
844 })
845 .ok();
846 });
847 })
848 .detach();
849 }
850
851 /// Elke minuut `ticket_updates`; bij wijzigingen de lijst en het open ticket opnieuw.
852 fn start_polling(&mut self, cx: &mut Context<Self>) {
853 if self.polling || is_demo(cx) {
854 return;
855 }
856 self.polling = true;
857 cx.spawn(async move |this, cx| {
858 loop {
859 cx.background_executor().timer(POLL_INTERVAL).await;
860 let Ok(Some((since, token))) = this.update(cx, |this, cx| {
861 let since = this.since.clone()?;
862 let (token, client) = token_and_client(cx)?;
863 Some((since, (token, client)))
864 }) else {
865 if this.upgrade().is_none() {
866 return;
867 }
868 continue;
869 };
870 let (token, client): (String, CardsClient) = token;
871 let polling =
872 runtime::spawn(async move { client.asclepius_updates(&token, &since).await });
873 let result = polling.await.unwrap_or(Err(ClientError::Unavailable));
874 let alive = this.update(cx, |this, cx| {
875 if let Ok((changed, server_time)) = result {
876 if !server_time.is_empty() {
877 this.since = Some(server_time);
878 }
879 if !changed.is_empty() {
880 let open_id = this.selected.as_ref().map(|thread| thread.read(cx).id());
881 if let Some(thread) = this.selected.clone()
882 && changed.iter().any(|t| Some(t.id) == open_id)
883 {
884 thread.update(cx, |thread, cx| thread.reload(cx));
885 }
886 this.reload(cx);
887 }
888 }
889 });
890 if alive.is_err() {
891 return;
892 }
893 }
894 })
895 .detach();
896 }
897
898 fn set_filter(&mut self, filter: TicketFilter, cx: &mut Context<Self>) {
899 if self.filter == filter {
900 return;
901 }
902 self.filter = filter;
903 self.list = List::Loading;
904 self.reload(cx);
905 }
906
907 fn select(&mut self, ticket: &Ticket, window: &mut Window, cx: &mut Context<Self>) {
908 if self
909 .selected
910 .as_ref()
911 .is_some_and(|thread| thread.read(cx).id() == ticket.id)
912 {
913 return;
914 }
915 let id = ticket.id;
916 self.selected = Some(cx.new(|cx| TicketThread::new(id, window, cx)));
917 if self.seen.mark(ticket) {
918 save_seen(&self.seen, cx);
919 }
920 cx.notify();
921 cx.refresh_windows();
922 }
923
924 fn header(&self, cx: &mut Context<Self>) -> Div {
925 h_flex()
926 .h(px(HEADER_HEIGHT))
927 .flex_none()
928 .px(px(PAGE_PADDING))
929 .gap(px(8.))
930 .items_center()
931 .child(
932 div()
933 .flex_1()
934 .min_w_0()
935 .truncate()
936 .text_size(px(16.))
937 .font_weight(FontWeight::BOLD)
938 .text_color(theme::text())
939 .child(tr("kvt.tickets.title")),
940 )
941 .children(super::ticket_form::new_ticket_button(cx))
942 .child(
943 secondary_button("kvt-tickets-refresh", "refresh", tr("kvt.card.refresh"))
944 .on_click(cx.listener(|this, _, _, cx| this.reload(cx))),
945 )
946 }
947
948 fn list(&self, cx: &mut Context<Self>) -> AnyElement {
949 let filters = h_flex()
950 .w_full()
951 .flex_none()
952 .px(px(12.))
953 .pb(px(8.))
954 .gap(px(6.))
955 .child(
956 chip(
957 "kvt-tickets-filter-open".into(),
958 tr("kvt.tickets.filter_open"),
959 self.filter == TicketFilter::Open,
960 )
961 .on_click(cx.listener(|this, _, _, cx| this.set_filter(TicketFilter::Open, cx))),
962 )
963 .child(
964 chip(
965 "kvt-tickets-filter-closed".into(),
966 tr("kvt.tickets.filter_closed"),
967 self.filter == TicketFilter::Closed,
968 )
969 .on_click(cx.listener(|this, _, _, cx| this.set_filter(TicketFilter::Closed, cx))),
970 );
971 let selected = self.selected.as_ref().map(|thread| thread.read(cx).id());
972 let rows: AnyElement = match &self.list {
973 List::Loading | List::NotLinked => {
974 muted(tr("kvt.card.loading")).px(px(12.)).into_any_element()
975 }
976 List::Failed(error) => muted(ticket_error(error)).px(px(12.)).into_any_element(),
977 List::Loaded(tickets) if tickets.is_empty() => muted(tr(match self.filter {
978 TicketFilter::Open => "kvt.tickets.empty_open",
979 TicketFilter::Closed => "kvt.tickets.empty_closed",
980 }))
981 .px(px(12.))
982 .into_any_element(),
983 List::Loaded(tickets) => v_flex()
984 .w_full()
985 .px(px(8.))
986 .gap(px(2.))
987 .children(tickets.iter().enumerate().map(|(index, ticket)| {
988 let unread = self.seen.is_unread(ticket);
989 let active = selected == Some(ticket.id);
990 let row_ticket = ticket.clone();
991 v_flex()
992 .id(ElementId::Name(format!("kvt-tickets-row-{index}").into()))
993 .debug_selector(move || format!("kvt-tickets/row/{index}"))
994 .w_full()
995 .px(px(10.))
996 .py(px(8.))
997 .gap(px(2.))
998 .rounded(px(6.))
999 .cursor_pointer()
1000 .map(|row| {
1001 if active {
1002 row.bg(theme::selection())
1003 } else {
1004 row.hover(|row| row.bg(theme::row_hover()))
1005 }
1006 })
1007 .on_click(cx.listener(move |this, _, window, cx| {
1008 this.select(&row_ticket, window, cx)
1009 }))
1010 .child(
1011 h_flex()
1012 .w_full()
1013 .gap(px(6.))
1014 .items_center()
1015 .child(
1016 div()
1017 .flex_1()
1018 .min_w_0()
1019 .truncate()
1020 .text_size(px(13.))
1021 .text_color(theme::text_strong())
1022 .when(unread, |title| title.font_weight(FontWeight::BOLD))
1023 .child(ticket.title.clone()),
1024 )
1025 .when(unread, |row| {
1026 row.child(
1027 div()
1028 .size(px(8.))
1029 .flex_none()
1030 .rounded_full()
1031 .bg(theme::accent()),
1032 )
1033 }),
1034 )
1035 .child(
1036 div()
1037 .truncate()
1038 .text_size(px(12.))
1039 .text_color(theme::text_muted())
1040 .child(format!(
1041 "#{} · {} · {}",
1042 ticket.id,
1043 status_label(&ticket.status),
1044 when(&ticket.updated_at)
1045 )),
1046 )
1047 }))
1048 .into_any_element(),
1049 };
1050 v_flex()
1051 .id("kvt-tickets-list")
1052 .w(px(LIST_WIDTH))
1053 .h_full()
1054 .flex_none()
1055 .border_r_1()
1056 .border_color(theme::border())
1057 .child(filters)
1058 .child(
1059 div()
1060 .id("kvt-tickets-rows")
1061 .flex_1()
1062 .min_h_0()
1063 .overflow_y_scrollbar()
1064 .child(rows),
1065 )
1066 .into_any_element()
1067 }
1068}
1069
1070impl Render for TicketsPage {
1071 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1072 let linked = matches!(link(cx), Link::Linked(_));
1073 if !linked && !is_demo(cx) {
1074 self.list = List::NotLinked;
1075 self.selected = None;
1076 self.open.clear();
1077 } else if matches!(self.list, List::NotLinked) {
1078 self.reload(cx);
1079 }
1080 let body = if !linked {
1081 v_flex()
1082 .p(px(PAGE_PADDING))
1083 .max_w(px(560.))
1084 .child(not_linked())
1085 .into_any_element()
1086 } else {
1087 h_flex()
1088 .flex_1()
1089 .min_h_0()
1090 .w_full()
1091 .child(self.list(cx))
1092 .child(
1093 div()
1094 .flex_1()
1095 .min_w_0()
1096 .h_full()
1097 .child(match &self.selected {
1098 Some(thread) => thread.clone().into_any_element(),
1099 None => muted(tr("kvt.tickets.pick"))
1100 .px(px(PAGE_PADDING))
1101 .into_any_element(),
1102 }),
1103 )
1104 .into_any_element()
1105 };
1106 v_flex()
1107 .debug_selector(|| KVT_TICKETS_TAG.into())
1108 .relative()
1109 .size_full()
1110 .rounded(px(RADIUS))
1111 .bg(theme::surface())
1112 .overflow_hidden()
1113 .child(self.header(cx))
1114 .child(body)
1115 }
1116}
1117
1118// --- demo ------------------------------------------------------------------------
1119
1120const DEMO_UNREAD: u64 = 4102;
1121
1122thread_local! {
1123 static DEMO_REPLIES: std::cell::RefCell<HashMap<u64, Vec<TicketMessage>>> =
1124 std::cell::RefCell::new(HashMap::new());
1125}
1126
1127fn demo_ticket(id: u64, title: &str, status: &str, category: &str, updated: &str) -> Ticket {
1128 Ticket {
1129 id,
1130 title: title.to_owned(),
1131 category: category.to_owned(),
1132 user_email: super::demo::token().email,
1133 assigned_email: "ict.medewerker@example.com".to_owned(),
1134 status: status.to_owned(),
1135 created_at: "2026-01-12T09:15:00+01:00".to_owned(),
1136 updated_at: updated.to_owned(),
1137 message_count: 3,
1138 ..Ticket::default()
1139 }
1140}
1141
1142pub(super) fn demo_tickets() -> Vec<Ticket> {
1143 vec![
1144 Ticket {
1145 subcategory: "Laptop".to_owned(),
1146 ..demo_ticket(
1147 DEMO_UNREAD,
1148 "Laptop start niet meer op",
1149 "in behandeling",
1150 "Hardware",
1151 "2026-01-15T13:39:00+01:00",
1152 )
1153 },
1154 demo_ticket(
1155 4098,
1156 "Toegang tot gedeelde map Projecten",
1157 "afwachtende op gebruiker",
1158 "Rechten en toegang",
1159 "2026-01-14T16:02:00+01:00",
1160 ),
1161 demo_ticket(
1162 4090,
1163 "Nieuwe headset",
1164 "ingediend",
1165 "Hardware bestellen",
1166 "2026-01-13T10:20:00+01:00",
1167 ),
1168 demo_ticket(
1169 4012,
1170 "Printer op kantoor geeft een fout",
1171 "afgehandeld",
1172 "Hardware",
1173 "2026-01-08T11:00:00+01:00",
1174 ),
1175 ]
1176}
1177
1178fn demo_message(
1179 id: u64,
1180 email: &str,
1181 name: &str,
1182 role: &str,
1183 text: &str,
1184 at: &str,
1185) -> TicketMessage {
1186 TicketMessage {
1187 id,
1188 sender_email: email.to_owned(),
1189 sender_role: role.to_owned(),
1190 sender_display_name: name.to_owned(),
1191 message_text: text.to_owned(),
1192 created_at: at.to_owned(),
1193 ..TicketMessage::default()
1194 }
1195}
1196
1197pub(super) fn demo_detail(id: u64) -> Option<TicketDetail> {
1198 let ticket = demo_tickets().into_iter().find(|ticket| ticket.id == id)?;
1199 let me = super::demo::token();
1200 let ict = "ict.medewerker@example.com";
1201 let mut messages = vec![
1202 demo_message(
1203 1,
1204 &me.email,
1205 &me.name,
1206 "user",
1207 "Mijn laptop gaat niet meer aan sinds vanochtend. Het lampje knippert oranje.",
1208 "2026-01-15T09:15:00+01:00",
1209 ),
1210 demo_message(
1211 2,
1212 ict,
1213 "Sam Ict",
1214 "admin",
1215 "Dank je. Kun je de lader een minuut loskoppelen en het opnieuw proberen? @dana.demo:examplecom",
1216 "2026-01-15T10:02:00+01:00",
1217 ),
1218 TicketMessage {
1219 is_ghost: true,
1220 ..demo_message(
1221 3,
1222 ict,
1223 "Sam Ict",
1224 "admin",
1225 "Intern: garantie loopt nog tot maart, eventueel omruilen via de leverancier.",
1226 "2026-01-15T10:05:00+01:00",
1227 )
1228 },
1229 TicketMessage {
1230 attachments: vec![TicketAttachment {
1231 id: 77,
1232 original_name: "foto-lampje.jpg".to_owned(),
1233 mime_type: "image/jpeg".to_owned(),
1234 file_size: 120_000,
1235 }],
1236 ..demo_message(
1237 4,
1238 &me.email,
1239 &me.name,
1240 "user",
1241 "Gedaan, hij knippert nog steeds. Foto erbij.",
1242 "2026-01-15T13:39:00+01:00",
1243 )
1244 },
1245 ];
1246 if id != DEMO_UNREAD {
1247 messages.truncate(1);
1248 messages[0].message_text = format!("{}.", ticket.title);
1249 }
1250 DEMO_REPLIES.with(|replies| {
1251 messages.extend(replies.borrow().get(&id).cloned().unwrap_or_default());
1252 });
1253 Some(TicketDetail {
1254 description: messages[0].message_text.clone(),
1255 participant_emails: vec![me.email.clone(), "jonas.ortega@example.com".to_owned()],
1256 messages,
1257 ticket,
1258 })
1259}
1260
1261fn demo_reply(id: u64, text: &str, email: &str) {
1262 let me = super::demo::token();
1263 DEMO_REPLIES.with(|replies| {
1264 let mut replies = replies.borrow_mut();
1265 let list = replies.entry(id).or_default();
1266 list.push(demo_message(
1267 100 + list.len() as u64,
1268 if email.is_empty() { &me.email } else { email },
1269 &me.name,
1270 "user",
1271 text,
1272 &chrono::Local::now().to_rfc3339(),
1273 ));
1274 });
1275}
1276
1277#[cfg(test)]
1278mod tests {
1279 use super::{DEMO_UNREAD, demo_detail, demo_tickets, mention_display, when};
1280 use kvt_sleutels::tickets::Ticket;
1281
1282 #[test]
1283 fn dates_are_dutch_and_local() {
1284 let shown = when("2026-01-15T13:39:00+01:00");
1285 assert!(shown.starts_with("15 jan 2026") || shown.starts_with("16 jan 2026"));
1286 assert_eq!(when("geen datum"), "geen datum");
1287 }
1288
1289 #[test]
1290 fn demo_has_a_ghost_and_a_closed_ticket() {
1291 let detail = demo_detail(DEMO_UNREAD).unwrap();
1292 assert!(detail.messages.iter().any(|message| message.is_ghost));
1293 assert!(demo_tickets().iter().any(Ticket::is_closed));
1294 }
1295
1296 #[test]
1297 fn mentions_render_as_first_names() {
1298 let (shown, ranges) = mention_display(
1299 "Graag @dana.demo:examplecom",
1300 &["dana.demo@example.com".to_owned()],
1301 );
1302 assert_eq!(shown, "Graag @Dana");
1303 assert_eq!(ranges, [6..11]);
1304 }
1305}