BlueGit

ict rusty-teams

Files

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

tickets.rs

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