BlueGit

ict rusty-teams

Files

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

tickets.rs

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