| 1 | //! Asclepius-tickets via `/asclepius/api.php` met de app-token (scope `asclepius`). |
| 2 | //! |
| 3 | //! Wat de token mag, bepaalt Asclepius (`asclepius_app_token.php`): je eigen tickets |
| 4 | //! (ingediend, deelnemer, gemachtigde of aan jou toegewezen), lezen, aanmaken en een |
| 5 | //! gewoon bericht plaatsen. Geen status, toewijzing of ghost-berichten plaatsen. |
| 6 | //! Ghosts komen alleen mee voor ICT, binnen de regels van de webinterface. |
| 7 | |
| 8 | use std::collections::{HashMap, HashSet}; |
| 9 | |
| 10 | use base64::Engine as _; |
| 11 | use serde::de::{self, Deserializer}; |
| 12 | use serde::{Deserialize, Serialize}; |
| 13 | use url::Url; |
| 14 | |
| 15 | use crate::client::{CardsClient, ClientError, json_or_error}; |
| 16 | |
| 17 | /// Status van een gesloten ticket. |
| 18 | pub const STATUS_CLOSED: &str = "afgehandeld"; |
| 19 | /// Categorieën die op het web alleen ICT kiest; het formulier toont ze niet. |
| 20 | pub const ICT_ONLY_CATEGORIES: [&str; 2] = ["Uitdiensttreding", "Indiensttreding"]; |
| 21 | /// Asclepius: titel max. 150 tekens, beschrijving max. 20 000 in het formulier. |
| 22 | pub const TITLE_MAX: usize = 150; |
| 23 | pub const DESCRIPTION_MAX: usize = 20_000; |
| 24 | /// Zelfde grenzen als `add_ticket_message`. |
| 25 | pub const ATTACHMENTS_MAX: usize = 10; |
| 26 | pub const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024; |
| 27 | |
| 28 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 29 | pub enum TicketFilter { |
| 30 | #[default] |
| 31 | Open, |
| 32 | Closed, |
| 33 | } |
| 34 | |
| 35 | impl TicketFilter { |
| 36 | pub fn as_str(self) -> &'static str { |
| 37 | match self { |
| 38 | TicketFilter::Open => "open", |
| 39 | TicketFilter::Closed => "closed", |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | // --- lenient velden (SQLite via PDO geeft soms "12" in plaats van 12) --------- |
| 45 | |
| 46 | fn de_u64<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> { |
| 47 | match serde_json::Value::deserialize(deserializer)? { |
| 48 | serde_json::Value::Number(number) => number |
| 49 | .as_u64() |
| 50 | .or_else(|| number.as_f64().map(|value| value as u64)) |
| 51 | .ok_or_else(|| de::Error::custom("geen getal")), |
| 52 | serde_json::Value::String(text) => text.trim().parse().map_err(de::Error::custom), |
| 53 | serde_json::Value::Null => Ok(0), |
| 54 | _ => Err(de::Error::custom("geen getal")), |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | fn de_i64<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i64, D::Error> { |
| 59 | match serde_json::Value::deserialize(deserializer)? { |
| 60 | serde_json::Value::Number(number) => Ok(number |
| 61 | .as_i64() |
| 62 | .or_else(|| number.as_f64().map(|value| value as i64)) |
| 63 | .unwrap_or(0)), |
| 64 | serde_json::Value::String(text) => Ok(text.trim().parse().unwrap_or(0)), |
| 65 | serde_json::Value::Bool(value) => Ok(i64::from(value)), |
| 66 | _ => Ok(0), |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | fn de_bool<'de, D: Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> { |
| 71 | Ok(match serde_json::Value::deserialize(deserializer)? { |
| 72 | serde_json::Value::Bool(value) => value, |
| 73 | serde_json::Value::Number(number) => number.as_i64().unwrap_or(0) != 0, |
| 74 | serde_json::Value::String(text) => matches!(text.trim(), "1" | "true"), |
| 75 | _ => false, |
| 76 | }) |
| 77 | } |
| 78 | |
| 79 | fn de_string<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> { |
| 80 | Ok(match serde_json::Value::deserialize(deserializer)? { |
| 81 | serde_json::Value::String(text) => text, |
| 82 | serde_json::Value::Number(number) => number.to_string(), |
| 83 | _ => String::new(), |
| 84 | }) |
| 85 | } |
| 86 | |
| 87 | // --- model ------------------------------------------------------------------ |
| 88 | |
| 89 | #[derive(Debug, Clone, Default, PartialEq, Deserialize)] |
| 90 | pub struct Ticket { |
| 91 | #[serde(deserialize_with = "de_u64")] |
| 92 | pub id: u64, |
| 93 | #[serde(default, deserialize_with = "de_string")] |
| 94 | pub title: String, |
| 95 | #[serde(default, deserialize_with = "de_string")] |
| 96 | pub category: String, |
| 97 | #[serde(default, deserialize_with = "de_string")] |
| 98 | pub subcategory: String, |
| 99 | #[serde(default, deserialize_with = "de_string")] |
| 100 | pub user_email: String, |
| 101 | #[serde(default, deserialize_with = "de_string")] |
| 102 | pub requester_display_name: String, |
| 103 | #[serde(default, deserialize_with = "de_string")] |
| 104 | pub assigned_email: String, |
| 105 | #[serde(default, deserialize_with = "de_string")] |
| 106 | pub status: String, |
| 107 | #[serde(default, deserialize_with = "de_i64")] |
| 108 | pub priority: i64, |
| 109 | #[serde(default, deserialize_with = "de_string")] |
| 110 | pub created_at: String, |
| 111 | #[serde(default, deserialize_with = "de_string")] |
| 112 | pub updated_at: String, |
| 113 | #[serde(default, deserialize_with = "de_i64")] |
| 114 | pub message_count: i64, |
| 115 | } |
| 116 | |
| 117 | impl Ticket { |
| 118 | pub fn is_closed(&self) -> bool { |
| 119 | is_closed(&self.status) |
| 120 | } |
| 121 | |
| 122 | pub fn url(&self, base_url: &str) -> String { |
| 123 | ticket_url(base_url, self.id) |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | #[derive(Debug, Clone, Default, PartialEq, Deserialize)] |
| 128 | pub struct TicketAttachment { |
| 129 | #[serde(deserialize_with = "de_u64")] |
| 130 | pub id: u64, |
| 131 | #[serde(default, deserialize_with = "de_string")] |
| 132 | pub original_name: String, |
| 133 | #[serde(default, deserialize_with = "de_string")] |
| 134 | pub mime_type: String, |
| 135 | #[serde(default, deserialize_with = "de_i64")] |
| 136 | pub file_size: i64, |
| 137 | } |
| 138 | |
| 139 | #[derive(Debug, Clone, Default, PartialEq, Deserialize)] |
| 140 | pub struct TicketMessage { |
| 141 | #[serde(deserialize_with = "de_u64")] |
| 142 | pub id: u64, |
| 143 | #[serde(default, deserialize_with = "de_string")] |
| 144 | pub sender_email: String, |
| 145 | /// `admin` (ICT) of `user`. |
| 146 | #[serde(default, deserialize_with = "de_string")] |
| 147 | pub sender_role: String, |
| 148 | #[serde(default, deserialize_with = "de_string")] |
| 149 | pub sender_display_name: String, |
| 150 | #[serde(default, deserialize_with = "de_string")] |
| 151 | pub message_text: String, |
| 152 | #[serde(default, deserialize_with = "de_string")] |
| 153 | pub created_at: String, |
| 154 | #[serde(default, deserialize_with = "de_bool")] |
| 155 | pub is_ghost: bool, |
| 156 | #[serde(default)] |
| 157 | pub attachments: Vec<TicketAttachment>, |
| 158 | } |
| 159 | |
| 160 | impl TicketMessage { |
| 161 | pub fn sender_name(&self) -> String { |
| 162 | if self.sender_display_name.trim().is_empty() { |
| 163 | crate::ponos::name_from_email(&self.sender_email) |
| 164 | } else { |
| 165 | self.sender_display_name.trim().to_owned() |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | #[derive(Debug, Clone, Default, PartialEq, Deserialize)] |
| 171 | pub struct TicketDetail { |
| 172 | #[serde(flatten)] |
| 173 | pub ticket: Ticket, |
| 174 | #[serde(default, deserialize_with = "de_string")] |
| 175 | pub description: String, |
| 176 | #[serde(default)] |
| 177 | pub participant_emails: Vec<String>, |
| 178 | #[serde(default)] |
| 179 | pub messages: Vec<TicketMessage>, |
| 180 | } |
| 181 | |
| 182 | #[derive(Debug, Clone, Default, PartialEq)] |
| 183 | pub struct Lookups { |
| 184 | pub categories: Vec<String>, |
| 185 | /// Categorie → subcategorieën, in de volgorde van Asclepius. |
| 186 | pub subcategories: HashMap<String, Vec<String>>, |
| 187 | } |
| 188 | |
| 189 | impl Lookups { |
| 190 | /// Categorieën voor het formulier, zonder de ICT-only categorieën (zoals op het web). |
| 191 | pub fn form_categories(&self) -> Vec<String> { |
| 192 | self.categories |
| 193 | .iter() |
| 194 | .filter(|category| !ICT_ONLY_CATEGORIES.contains(&category.as_str())) |
| 195 | .cloned() |
| 196 | .collect() |
| 197 | } |
| 198 | |
| 199 | pub fn subcategories_of(&self, category: &str) -> &[String] { |
| 200 | self.subcategories |
| 201 | .get(category) |
| 202 | .map(Vec::as_slice) |
| 203 | .unwrap_or_default() |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 208 | pub struct NewAttachment { |
| 209 | pub filename: String, |
| 210 | pub mime: String, |
| 211 | pub data: Vec<u8>, |
| 212 | } |
| 213 | |
| 214 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 215 | pub struct NewTicket { |
| 216 | pub title: String, |
| 217 | pub category: String, |
| 218 | pub subcategory: Option<String>, |
| 219 | pub description: String, |
| 220 | /// 0–2, uit de twee vinkjes van het webformulier (`priority_from_flags`). |
| 221 | pub priority: u8, |
| 222 | pub participant_emails: Vec<String>, |
| 223 | pub attachments: Vec<NewAttachment>, |
| 224 | } |
| 225 | |
| 226 | #[derive(Serialize)] |
| 227 | struct AttachmentBody<'a> { |
| 228 | filename: &'a str, |
| 229 | mime: &'a str, |
| 230 | data_base64: String, |
| 231 | } |
| 232 | |
| 233 | #[derive(Serialize)] |
| 234 | struct CreateBody<'a> { |
| 235 | title: &'a str, |
| 236 | category: &'a str, |
| 237 | #[serde(skip_serializing_if = "Option::is_none")] |
| 238 | subcategory: Option<&'a str>, |
| 239 | description: &'a str, |
| 240 | priority: u8, |
| 241 | participant_emails: &'a [String], |
| 242 | #[serde(skip_serializing_if = "Vec::is_empty")] |
| 243 | attachments: Vec<AttachmentBody<'a>>, |
| 244 | } |
| 245 | |
| 246 | impl NewTicket { |
| 247 | fn body(&self) -> CreateBody<'_> { |
| 248 | CreateBody { |
| 249 | title: &self.title, |
| 250 | category: &self.category, |
| 251 | subcategory: self |
| 252 | .subcategory |
| 253 | .as_deref() |
| 254 | .filter(|value| !value.is_empty()), |
| 255 | description: &self.description, |
| 256 | priority: self.priority.min(2), |
| 257 | participant_emails: &self.participant_emails, |
| 258 | attachments: self |
| 259 | .attachments |
| 260 | .iter() |
| 261 | .map(|attachment| AttachmentBody { |
| 262 | filename: &attachment.filename, |
| 263 | mime: &attachment.mime, |
| 264 | data_base64: base64::engine::general_purpose::STANDARD.encode(&attachment.data), |
| 265 | }) |
| 266 | .collect(), |
| 267 | } |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | // --- regels ----------------------------------------------------------------- |
| 272 | |
| 273 | pub fn is_closed(status: &str) -> bool { |
| 274 | status.trim().eq_ignore_ascii_case(STATUS_CLOSED) |
| 275 | } |
| 276 | |
| 277 | /// Zelfde als `getPriorityFromFlags` op het web: het tweede vinkje telt alleen met het eerste. |
| 278 | /// MIME-type uit de extensie (Asclepius controleert de inhoud zelf ook). |
| 279 | pub fn mime_for(filename: &str) -> &'static str { |
| 280 | let extension = filename |
| 281 | .rsplit_once('.') |
| 282 | .map(|(_, extension)| extension.to_ascii_lowercase()) |
| 283 | .unwrap_or_default(); |
| 284 | match extension.as_str() { |
| 285 | "png" => "image/png", |
| 286 | "jpg" | "jpeg" => "image/jpeg", |
| 287 | "gif" => "image/gif", |
| 288 | "webp" => "image/webp", |
| 289 | "pdf" => "application/pdf", |
| 290 | "txt" | "log" => "text/plain", |
| 291 | "csv" => "text/csv", |
| 292 | "doc" => "application/msword", |
| 293 | "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", |
| 294 | "xls" => "application/vnd.ms-excel", |
| 295 | "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", |
| 296 | "ppt" => "application/vnd.ms-powerpoint", |
| 297 | "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation", |
| 298 | "zip" => "application/zip", |
| 299 | "eml" => "message/rfc822", |
| 300 | _ => "application/octet-stream", |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | pub fn priority_from_flags(blocked: bool, fully_blocked: bool) -> u8 { |
| 305 | match (blocked, fully_blocked) { |
| 306 | (true, true) => 2, |
| 307 | (true, false) => 1, |
| 308 | _ => 0, |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | /// `https://sleutels.kvt.nl/asclepius/index.php?open=123`. |
| 313 | pub fn ticket_url(base_url: &str, id: u64) -> String { |
| 314 | format!( |
| 315 | "{}/asclepius/index.php?open={id}", |
| 316 | base_url.trim_end_matches('/') |
| 317 | ) |
| 318 | } |
| 319 | |
| 320 | /// Ticketnummer uit een Asclepius-link op dezelfde host als `base_url` |
| 321 | /// (`/asclepius/`, `index.php` of `admin.php`, met `?open=`). Anders `None`. |
| 322 | pub fn ticket_id_from_url(base_url: &str, url: &str) -> Option<u64> { |
| 323 | let base = Url::parse(base_url).ok()?; |
| 324 | let url = Url::parse(url.trim()).ok()?; |
| 325 | if url.scheme() != "https" || !url.host_str()?.eq_ignore_ascii_case(base.host_str()?) { |
| 326 | return None; |
| 327 | } |
| 328 | let path = url.path().trim_end_matches('/'); |
| 329 | if !matches!( |
| 330 | path, |
| 331 | "/asclepius" | "/asclepius/index.php" | "/asclepius/admin.php" |
| 332 | ) { |
| 333 | return None; |
| 334 | } |
| 335 | url.query_pairs() |
| 336 | .find(|(key, _)| key == "open") |
| 337 | .and_then(|(_, value)| value.trim().parse::<u64>().ok()) |
| 338 | .filter(|id| *id > 0) |
| 339 | } |
| 340 | |
| 341 | /// Komen de opgegeven deelnemers als lijst van geldige adressen, zonder dubbele. |
| 342 | pub fn parse_participants(text: &str) -> Result<Vec<String>, String> { |
| 343 | let mut seen = HashSet::new(); |
| 344 | let mut emails = Vec::new(); |
| 345 | for part in text.split([',', ';', '\n', ' ']) { |
| 346 | let email = part.trim().trim_matches(['<', '>']).to_lowercase(); |
| 347 | if email.is_empty() { |
| 348 | continue; |
| 349 | } |
| 350 | let valid = email.split_once('@').is_some_and(|(local, domain)| { |
| 351 | !local.is_empty() && domain.contains('.') && !domain.starts_with('.') |
| 352 | }); |
| 353 | if !valid { |
| 354 | return Err(email); |
| 355 | } |
| 356 | if seen.insert(email.clone()) { |
| 357 | emails.push(email); |
| 358 | } |
| 359 | } |
| 360 | Ok(emails) |
| 361 | } |
| 362 | |
| 363 | // --- @-vermeldingen ---------------------------------------------------------- |
| 364 | |
| 365 | /// `jan@example.com` → `@jan:examplecom` (zoals Asclepius vermeldingen opslaat). |
| 366 | pub fn mention_token(email: &str) -> Option<String> { |
| 367 | let email = email.trim().to_lowercase(); |
| 368 | let (local, domain) = email.rsplit_once('@')?; |
| 369 | let domain = domain.replace('.', ""); |
| 370 | let domain_ok = !domain.is_empty() |
| 371 | && domain |
| 372 | .chars() |
| 373 | .all(|c| c.is_ascii_alphanumeric() || c == '-'); |
| 374 | (!local.is_empty() && domain_ok).then(|| format!("@{local}:{domain}")) |
| 375 | } |
| 376 | |
| 377 | /// Teams-vermeldingen (`@Naam` in de tekst) naar Asclepius-tokens, als het adres bekend is. |
| 378 | /// Elke naam één keer, de langste eerst (zodat `@Jan de Vries` niet als `@Jan` telt). |
| 379 | pub fn mentions_to_asclepius(text: &str, mentions: &[(String, String)]) -> String { |
| 380 | let mut ordered: Vec<&(String, String)> = mentions.iter().collect(); |
| 381 | ordered.sort_by_key(|(name, _)| std::cmp::Reverse(name.chars().count())); |
| 382 | let mut out = text.to_owned(); |
| 383 | for (name, email) in ordered { |
| 384 | let name = name.trim().trim_start_matches('@'); |
| 385 | let Some(token) = mention_token(email) else { |
| 386 | continue; |
| 387 | }; |
| 388 | if name.is_empty() { |
| 389 | continue; |
| 390 | } |
| 391 | let needle = format!("@{name}"); |
| 392 | let mut result = String::with_capacity(out.len()); |
| 393 | let mut rest = out.as_str(); |
| 394 | while let Some(index) = rest.find(&needle) { |
| 395 | result.push_str(&rest[..index]); |
| 396 | result.push_str(&token); |
| 397 | rest = &rest[index + needle.len()..]; |
| 398 | } |
| 399 | result.push_str(rest); |
| 400 | out = result; |
| 401 | } |
| 402 | out |
| 403 | } |
| 404 | |
| 405 | /// Een stuk berichttekst: gewone tekst of een Asclepius-vermelding. |
| 406 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 407 | pub enum TextPart { |
| 408 | Text(String), |
| 409 | /// `key` zonder `@` (`jan:examplecom`); `email` als die bekend is. |
| 410 | Mention { |
| 411 | key: String, |
| 412 | email: Option<String>, |
| 413 | }, |
| 414 | } |
| 415 | |
| 416 | fn mention_key_char(c: char) -> bool { |
| 417 | c.is_ascii_alphanumeric() || "._%+-".contains(c) |
| 418 | } |
| 419 | |
| 420 | /// Asclepius-tokens (`@jan:examplecom`) in de tekst, met het adres uit `known` als dat erbij hoort. |
| 421 | /// Niet in code (```…``` of `…`), niet midden in een woord of adres. |
| 422 | pub fn split_mentions(text: &str, known: &[String]) -> Vec<TextPart> { |
| 423 | let by_key: HashMap<String, String> = known |
| 424 | .iter() |
| 425 | .filter_map(|email| { |
| 426 | mention_token(email).map(|token| (token[1..].to_owned(), email.to_lowercase())) |
| 427 | }) |
| 428 | .collect(); |
| 429 | let mut parts = Vec::new(); |
| 430 | let mut plain = String::new(); |
| 431 | let chars: Vec<(usize, char)> = text.char_indices().collect(); |
| 432 | let mut index = 0; |
| 433 | let mut in_fence = false; |
| 434 | let mut in_code = false; |
| 435 | while index < chars.len() { |
| 436 | let (byte, c) = chars[index]; |
| 437 | if text[byte..].starts_with("```") { |
| 438 | in_fence = !in_fence; |
| 439 | plain.push_str("```"); |
| 440 | index += 3; |
| 441 | continue; |
| 442 | } |
| 443 | if c == '`' && !in_fence { |
| 444 | in_code = !in_code; |
| 445 | } |
| 446 | let before = index.checked_sub(1).map(|i| chars[i].1); |
| 447 | let opens = before.is_none_or(|b| !(b.is_alphanumeric() || "@./-_".contains(b))); |
| 448 | if c == '@' && opens && !in_fence && !in_code { |
| 449 | // local |
| 450 | let mut end = index + 1; |
| 451 | while end < chars.len() && mention_key_char(chars[end].1) { |
| 452 | end += 1; |
| 453 | } |
| 454 | let local_end = end; |
| 455 | if local_end > index + 1 && end < chars.len() && chars[end].1 == ':' { |
| 456 | let mut domain_end = end + 1; |
| 457 | while domain_end < chars.len() |
| 458 | && (chars[domain_end].1.is_ascii_alphanumeric() || chars[domain_end].1 == '-') |
| 459 | { |
| 460 | domain_end += 1; |
| 461 | } |
| 462 | let next = chars.get(domain_end).map(|(_, c)| *c); |
| 463 | let next_ok = next.is_none_or(|n| n != ':' && !n.is_alphanumeric()); |
| 464 | if domain_end > end + 1 && next_ok { |
| 465 | let start = chars[index + 1].0; |
| 466 | let stop = chars.get(domain_end).map_or(text.len(), |(b, _)| *b); |
| 467 | let key = text[start..stop].to_lowercase(); |
| 468 | let local = &text[start..chars[local_end].0]; |
| 469 | if !local.ends_with('.') { |
| 470 | if !plain.is_empty() { |
| 471 | parts.push(TextPart::Text(std::mem::take(&mut plain))); |
| 472 | } |
| 473 | parts.push(TextPart::Mention { |
| 474 | email: by_key.get(&key).cloned(), |
| 475 | key, |
| 476 | }); |
| 477 | index = domain_end; |
| 478 | continue; |
| 479 | } |
| 480 | } |
| 481 | } |
| 482 | } |
| 483 | plain.push(c); |
| 484 | index += 1; |
| 485 | } |
| 486 | if !plain.is_empty() { |
| 487 | parts.push(TextPart::Text(plain)); |
| 488 | } |
| 489 | parts |
| 490 | } |
| 491 | |
| 492 | /// Naam voor een vermelding: uit het adres als dat bekend is, anders het deel voor de `:`. |
| 493 | pub fn mention_label(key: &str, email: Option<&str>) -> String { |
| 494 | let name = match email { |
| 495 | Some(email) => crate::ponos::name_from_email(email), |
| 496 | None => crate::ponos::name_from_email(key.split(':').next().unwrap_or(key)), |
| 497 | }; |
| 498 | let first = name.split(' ').next().unwrap_or_default(); |
| 499 | format!("@{}", if first.is_empty() { key } else { first }) |
| 500 | } |
| 501 | |
| 502 | // --- lokaal ongelezen ---------------------------------------------------------- |
| 503 | |
| 504 | /// Laatst gezien per ticket (`updated_at`), alleen in de lokale opslag. |
| 505 | #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 506 | pub struct SeenTickets { |
| 507 | /// Na de eerste lijst: oude tickets tellen dan niet als ongelezen. |
| 508 | #[serde(default)] |
| 509 | pub initialized: bool, |
| 510 | #[serde(default)] |
| 511 | pub seen: HashMap<u64, String>, |
| 512 | } |
| 513 | |
| 514 | impl SeenTickets { |
| 515 | pub fn from_json(text: &str) -> Self { |
| 516 | serde_json::from_str(text).unwrap_or_default() |
| 517 | } |
| 518 | |
| 519 | pub fn to_json(&self) -> String { |
| 520 | serde_json::to_string(self).unwrap_or_default() |
| 521 | } |
| 522 | |
| 523 | /// Eerste keer: alles wat er nu is telt als gelezen. |
| 524 | pub fn initialize(&mut self, tickets: &[Ticket]) -> bool { |
| 525 | if self.initialized { |
| 526 | return false; |
| 527 | } |
| 528 | for ticket in tickets { |
| 529 | self.seen.insert(ticket.id, ticket.updated_at.clone()); |
| 530 | } |
| 531 | self.initialized = true; |
| 532 | true |
| 533 | } |
| 534 | |
| 535 | pub fn is_unread(&self, ticket: &Ticket) -> bool { |
| 536 | if !self.initialized { |
| 537 | return false; |
| 538 | } |
| 539 | match self.seen.get(&ticket.id) { |
| 540 | Some(seen) => ticket.updated_at.as_str() > seen.as_str(), |
| 541 | None => true, |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | pub fn mark(&mut self, ticket: &Ticket) -> bool { |
| 546 | let changed = self.seen.get(&ticket.id) != Some(&ticket.updated_at); |
| 547 | self.seen.insert(ticket.id, ticket.updated_at.clone()); |
| 548 | changed |
| 549 | } |
| 550 | |
| 551 | pub fn unread_count(&self, tickets: &[Ticket]) -> usize { |
| 552 | tickets |
| 553 | .iter() |
| 554 | .filter(|ticket| self.is_unread(ticket)) |
| 555 | .count() |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | // --- client ------------------------------------------------------------------- |
| 560 | |
| 561 | #[derive(Deserialize)] |
| 562 | struct ListEnvelope { |
| 563 | #[serde(default)] |
| 564 | tickets: Vec<Ticket>, |
| 565 | } |
| 566 | |
| 567 | #[derive(Deserialize)] |
| 568 | struct UpdatesEnvelope { |
| 569 | #[serde(default)] |
| 570 | tickets: Vec<Ticket>, |
| 571 | #[serde(default)] |
| 572 | server_time: String, |
| 573 | } |
| 574 | |
| 575 | #[derive(Deserialize)] |
| 576 | struct DetailEnvelope { |
| 577 | ticket: TicketDetail, |
| 578 | } |
| 579 | |
| 580 | #[derive(Deserialize)] |
| 581 | struct LookupsEnvelope { |
| 582 | #[serde(default)] |
| 583 | categories: Vec<String>, |
| 584 | #[serde(default)] |
| 585 | subcategories: serde_json::Value, |
| 586 | } |
| 587 | |
| 588 | #[derive(Deserialize)] |
| 589 | struct CreatedEnvelope { |
| 590 | #[serde(deserialize_with = "de_u64")] |
| 591 | ticket_id: u64, |
| 592 | } |
| 593 | |
| 594 | #[derive(Deserialize)] |
| 595 | struct SuccessEnvelope { |
| 596 | #[serde(default, deserialize_with = "de_bool")] |
| 597 | success: bool, |
| 598 | } |
| 599 | |
| 600 | async fn api_json<T: serde::de::DeserializeOwned>( |
| 601 | response: reqwest::Response, |
| 602 | ) -> Result<T, ClientError> { |
| 603 | match response.status().as_u16() { |
| 604 | // Ongeldige invoer of te grote bijlage: de app toont «niet gelukt». |
| 605 | 413 | 422 => Err(ClientError::BadRequest), |
| 606 | _ => json_or_error(response).await, |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | impl CardsClient { |
| 611 | fn asclepius_url(&self) -> String { |
| 612 | format!("{}/asclepius/api.php", self.base_url()) |
| 613 | } |
| 614 | |
| 615 | async fn asclepius_get<T: serde::de::DeserializeOwned>( |
| 616 | &self, |
| 617 | token: &str, |
| 618 | query: &[(&str, &str)], |
| 619 | ) -> Result<T, ClientError> { |
| 620 | let response = self |
| 621 | .http() |
| 622 | .get(self.asclepius_url()) |
| 623 | .query(query) |
| 624 | .bearer_auth(token) |
| 625 | .send() |
| 626 | .await |
| 627 | .map_err(|_| ClientError::Unavailable)?; |
| 628 | api_json(response).await |
| 629 | } |
| 630 | |
| 631 | async fn asclepius_post<T: serde::de::DeserializeOwned>( |
| 632 | &self, |
| 633 | token: &str, |
| 634 | body: &impl Serialize, |
| 635 | ) -> Result<T, ClientError> { |
| 636 | let body = serde_json::to_vec(body).map_err(|_| ClientError::BadRequest)?; |
| 637 | let response = self |
| 638 | .http() |
| 639 | .post(self.asclepius_url()) |
| 640 | .header(reqwest::header::CONTENT_TYPE, "application/json") |
| 641 | .body(body) |
| 642 | .bearer_auth(token) |
| 643 | .send() |
| 644 | .await |
| 645 | .map_err(|_| ClientError::Unavailable)?; |
| 646 | api_json(response).await |
| 647 | } |
| 648 | |
| 649 | /// Je tickets (zoals «Mijn tickets» op het web, plus aan jou toegewezen). |
| 650 | pub async fn asclepius_tickets( |
| 651 | &self, |
| 652 | token: &str, |
| 653 | filter: TicketFilter, |
| 654 | ) -> Result<Vec<Ticket>, ClientError> { |
| 655 | let envelope: ListEnvelope = self |
| 656 | .asclepius_get(token, &[("filter", filter.as_str())]) |
| 657 | .await?; |
| 658 | Ok(envelope.tickets) |
| 659 | } |
| 660 | |
| 661 | /// Eén ticket met berichten; ghosts alleen als Asclepius ze voor jou toont (ICT). |
| 662 | pub async fn asclepius_ticket( |
| 663 | &self, |
| 664 | token: &str, |
| 665 | id: u64, |
| 666 | ) -> Result<TicketDetail, ClientError> { |
| 667 | let id = id.to_string(); |
| 668 | let envelope: DetailEnvelope = self |
| 669 | .asclepius_get(token, &[("id", id.as_str()), ("include_ghosts", "1")]) |
| 670 | .await?; |
| 671 | Ok(envelope.ticket) |
| 672 | } |
| 673 | |
| 674 | /// Tickets die sinds `since` (ISO of `server_time` van de vorige keer) veranderd zijn. |
| 675 | pub async fn asclepius_updates( |
| 676 | &self, |
| 677 | token: &str, |
| 678 | since: &str, |
| 679 | ) -> Result<(Vec<Ticket>, String), ClientError> { |
| 680 | let envelope: UpdatesEnvelope = self |
| 681 | .asclepius_get( |
| 682 | token, |
| 683 | &[("action", "ticket_updates"), ("updated_since", since)], |
| 684 | ) |
| 685 | .await?; |
| 686 | Ok((envelope.tickets, envelope.server_time)) |
| 687 | } |
| 688 | |
| 689 | pub async fn asclepius_lookups(&self, token: &str) -> Result<Lookups, ClientError> { |
| 690 | let envelope: LookupsEnvelope = self |
| 691 | .asclepius_get(token, &[("action", "ticket_lookups")]) |
| 692 | .await?; |
| 693 | let mut subcategories = HashMap::new(); |
| 694 | if let serde_json::Value::Object(map) = envelope.subcategories { |
| 695 | for (category, values) in map { |
| 696 | let list: Vec<String> = values |
| 697 | .as_array() |
| 698 | .map(|values| { |
| 699 | values |
| 700 | .iter() |
| 701 | .filter_map(|value| value.as_str().map(str::to_owned)) |
| 702 | .collect() |
| 703 | }) |
| 704 | .unwrap_or_default(); |
| 705 | if !list.is_empty() { |
| 706 | subcategories.insert(category, list); |
| 707 | } |
| 708 | } |
| 709 | } |
| 710 | Ok(Lookups { |
| 711 | categories: envelope.categories, |
| 712 | subcategories, |
| 713 | }) |
| 714 | } |
| 715 | |
| 716 | /// Maakt het ticket op jouw naam; geeft het ticketnummer. |
| 717 | pub async fn asclepius_create( |
| 718 | &self, |
| 719 | token: &str, |
| 720 | ticket: &NewTicket, |
| 721 | ) -> Result<u64, ClientError> { |
| 722 | let created: CreatedEnvelope = self.asclepius_post(token, &ticket.body()).await?; |
| 723 | Ok(created.ticket_id) |
| 724 | } |
| 725 | |
| 726 | /// Een gewoon bericht (geen ghost, geen status). |
| 727 | pub async fn asclepius_reply( |
| 728 | &self, |
| 729 | token: &str, |
| 730 | id: u64, |
| 731 | text: &str, |
| 732 | ) -> Result<(), ClientError> { |
| 733 | let envelope: SuccessEnvelope = self |
| 734 | .asclepius_post( |
| 735 | token, |
| 736 | &serde_json::json!({ |
| 737 | "action": "add_ticket_message", |
| 738 | "ticket_id": id, |
| 739 | "message": text, |
| 740 | }), |
| 741 | ) |
| 742 | .await?; |
| 743 | if envelope.success { |
| 744 | Ok(()) |
| 745 | } else { |
| 746 | Err(ClientError::BadRequest) |
| 747 | } |
| 748 | } |
| 749 | |
| 750 | /// De inhoud van een bijlage (alleen met de token, dus niet via de browser). |
| 751 | pub async fn asclepius_attachment(&self, token: &str, id: u64) -> Result<Vec<u8>, ClientError> { |
| 752 | let id = id.to_string(); |
| 753 | let response = self |
| 754 | .http() |
| 755 | .get(self.asclepius_url()) |
| 756 | .query(&[("action", "get_attachment"), ("id", id.as_str())]) |
| 757 | .bearer_auth(token) |
| 758 | .send() |
| 759 | .await |
| 760 | .map_err(|_| ClientError::Unavailable)?; |
| 761 | match response.status().as_u16() { |
| 762 | 200 => response |
| 763 | .bytes() |
| 764 | .await |
| 765 | .map(|bytes| bytes.to_vec()) |
| 766 | .map_err(|_| ClientError::Unavailable), |
| 767 | 401 => Err(ClientError::Unauthorized), |
| 768 | 403 => Err(ClientError::Forbidden), |
| 769 | 404 => Err(ClientError::NotFound), |
| 770 | _ => Err(ClientError::Unavailable), |
| 771 | } |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | #[cfg(test)] |
| 776 | mod tests { |
| 777 | use super::*; |
| 778 | |
| 779 | #[test] |
| 780 | fn list_tolerates_string_numbers_and_nulls() { |
| 781 | let json = r#"{"success":true,"filter":"open","tickets":[ |
| 782 | {"id":"12","title":"Printer","category":"Hardware bestellen","subcategory":null, |
| 783 | "user_email":"jan@example.com","assigned_email":null,"status":"ingediend","priority":"1", |
| 784 | "created_at":"2026-01-15T10:00:00+01:00","updated_at":"2026-01-15T11:00:00+01:00", |
| 785 | "message_count":"3","is_private":0}]}"#; |
| 786 | let envelope: ListEnvelope = serde_json::from_str(json).unwrap(); |
| 787 | let ticket = &envelope.tickets[0]; |
| 788 | assert_eq!(ticket.id, 12); |
| 789 | assert_eq!(ticket.priority, 1); |
| 790 | assert_eq!(ticket.subcategory, ""); |
| 791 | assert_eq!(ticket.assigned_email, ""); |
| 792 | assert_eq!(ticket.message_count, 3); |
| 793 | assert!(!ticket.is_closed()); |
| 794 | } |
| 795 | |
| 796 | #[test] |
| 797 | fn detail_reads_messages_ghosts_and_attachments() { |
| 798 | let json = r#"{"success":true,"ticket":{"id":7,"title":"VPN","status":"afgehandeld", |
| 799 | "description":"Werkt niet","participant_emails":["jan@example.com"], |
| 800 | "messages":[ |
| 801 | {"id":1,"sender_email":"jan@example.com","sender_role":"user","message_text":"Hoi","created_at":"x","is_ghost":0,"attachments":[]}, |
| 802 | {"id":"2","sender_email":"ict@example.com","sender_role":"admin","sender_display_name":"ICT Bot","message_text":"Intern","is_ghost":"1", |
| 803 | "attachments":[{"id":"9","original_name":"log.txt","mime_type":"text/plain","file_size":"12","download_url":"https://x"}]} |
| 804 | ]}}"#; |
| 805 | let envelope: DetailEnvelope = serde_json::from_str(json).unwrap(); |
| 806 | let detail = envelope.ticket; |
| 807 | assert_eq!(detail.ticket.id, 7); |
| 808 | assert!(detail.ticket.is_closed()); |
| 809 | assert_eq!(detail.participant_emails, ["jan@example.com"]); |
| 810 | assert!(!detail.messages[0].is_ghost); |
| 811 | assert!(detail.messages[1].is_ghost); |
| 812 | assert_eq!(detail.messages[1].attachments[0].id, 9); |
| 813 | assert_eq!(detail.messages[0].sender_name(), "Jan"); |
| 814 | assert_eq!(detail.messages[1].sender_name(), "ICT Bot"); |
| 815 | } |
| 816 | |
| 817 | #[test] |
| 818 | fn create_body_matches_the_api() { |
| 819 | let ticket = NewTicket { |
| 820 | title: "Scanner".into(), |
| 821 | category: "Hardware bestellen".into(), |
| 822 | subcategory: Some(String::new()), |
| 823 | description: "Graag".into(), |
| 824 | priority: priority_from_flags(true, true), |
| 825 | participant_emails: vec!["piet@example.com".into()], |
| 826 | attachments: vec![NewAttachment { |
| 827 | filename: "a.png".into(), |
| 828 | mime: "image/png".into(), |
| 829 | data: vec![1, 2, 3], |
| 830 | }], |
| 831 | }; |
| 832 | let value = serde_json::to_value(ticket.body()).unwrap(); |
| 833 | assert_eq!(value["priority"], 2); |
| 834 | assert!(value.get("subcategory").is_none()); |
| 835 | assert_eq!(value["participant_emails"][0], "piet@example.com"); |
| 836 | assert_eq!(value["attachments"][0]["data_base64"], "AQID"); |
| 837 | assert!(value.get("action").is_none()); |
| 838 | } |
| 839 | |
| 840 | #[test] |
| 841 | fn priority_follows_the_web_checkboxes() { |
| 842 | assert_eq!(priority_from_flags(false, false), 0); |
| 843 | assert_eq!(priority_from_flags(true, false), 1); |
| 844 | assert_eq!(priority_from_flags(true, true), 2); |
| 845 | assert_eq!(priority_from_flags(false, true), 0); |
| 846 | } |
| 847 | |
| 848 | #[test] |
| 849 | fn form_hides_ict_only_categories() { |
| 850 | let lookups = Lookups { |
| 851 | categories: vec![ |
| 852 | "Hardware bestellen".into(), |
| 853 | "Uitdiensttreding".into(), |
| 854 | "Indiensttreding".into(), |
| 855 | ], |
| 856 | subcategories: HashMap::from([("Hardware bestellen".into(), vec!["Laptop".into()])]), |
| 857 | }; |
| 858 | assert_eq!(lookups.form_categories(), ["Hardware bestellen"]); |
| 859 | assert_eq!(lookups.subcategories_of("Hardware bestellen"), ["Laptop"]); |
| 860 | assert!(lookups.subcategories_of("Anders").is_empty()); |
| 861 | } |
| 862 | |
| 863 | #[test] |
| 864 | fn ticket_links_on_the_same_host_only() { |
| 865 | let base = "https://sleutels.kvt.nl"; |
| 866 | assert_eq!( |
| 867 | ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/index.php?open=776"), |
| 868 | Some(776) |
| 869 | ); |
| 870 | assert_eq!( |
| 871 | ticket_id_from_url(base, "https://Sleutels.kvt.nl/asclepius/?open=5#mention-1"), |
| 872 | Some(5) |
| 873 | ); |
| 874 | assert_eq!( |
| 875 | ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/admin.php?open=9"), |
| 876 | Some(9) |
| 877 | ); |
| 878 | assert_eq!( |
| 879 | ticket_id_from_url(base, "https://evil.example/asclepius/index.php?open=1"), |
| 880 | None |
| 881 | ); |
| 882 | assert_eq!( |
| 883 | ticket_id_from_url(base, "http://sleutels.kvt.nl/asclepius/index.php?open=1"), |
| 884 | None |
| 885 | ); |
| 886 | assert_eq!( |
| 887 | ticket_id_from_url(base, "https://sleutels.kvt.nl/ponos/?open=1"), |
| 888 | None |
| 889 | ); |
| 890 | assert_eq!( |
| 891 | ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/index.php"), |
| 892 | None |
| 893 | ); |
| 894 | assert_eq!( |
| 895 | ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/index.php?open=0"), |
| 896 | None |
| 897 | ); |
| 898 | assert_eq!( |
| 899 | ticket_url(base, 12), |
| 900 | "https://sleutels.kvt.nl/asclepius/index.php?open=12" |
| 901 | ); |
| 902 | } |
| 903 | |
| 904 | #[test] |
| 905 | fn participants_are_validated_and_deduplicated() { |
| 906 | assert_eq!( |
| 907 | parse_participants("Piet@example.com, jan@example.com; piet@example.com").unwrap(), |
| 908 | ["piet@example.com", "jan@example.com"] |
| 909 | ); |
| 910 | assert_eq!(parse_participants(" ").unwrap(), Vec::<String>::new()); |
| 911 | assert_eq!( |
| 912 | parse_participants("jan, piet@example.com"), |
| 913 | Err("jan".into()) |
| 914 | ); |
| 915 | } |
| 916 | |
| 917 | #[test] |
| 918 | fn mention_tokens_match_asclepius() { |
| 919 | assert_eq!( |
| 920 | mention_token("jan@example.com").as_deref(), |
| 921 | Some("@jan:examplecom") |
| 922 | ); |
| 923 | assert_eq!( |
| 924 | mention_token("J.DeVries@example.be").as_deref(), |
| 925 | Some("@j.devries:examplebe") |
| 926 | ); |
| 927 | assert_eq!(mention_token("geen-adres"), None); |
| 928 | } |
| 929 | |
| 930 | #[test] |
| 931 | fn teams_mentions_become_asclepius_tokens() { |
| 932 | let mentions = vec![ |
| 933 | ("Jan".to_owned(), "jan.peters@example.com".to_owned()), |
| 934 | ( |
| 935 | "Jan de Vries".to_owned(), |
| 936 | "j.devries@example.com".to_owned(), |
| 937 | ), |
| 938 | ]; |
| 939 | assert_eq!( |
| 940 | mentions_to_asclepius("@Jan de Vries en @Jan, kijk even", &mentions), |
| 941 | "@j.devries:examplecom en @jan.peters:examplecom, kijk even" |
| 942 | ); |
| 943 | assert_eq!( |
| 944 | mentions_to_asclepius("geen vermelding", &mentions), |
| 945 | "geen vermelding" |
| 946 | ); |
| 947 | } |
| 948 | |
| 949 | #[test] |
| 950 | fn asclepius_tokens_are_split_out_for_display() { |
| 951 | let known = vec!["jan.peters@example.com".to_owned()]; |
| 952 | let parts = split_mentions("Hoi @jan.peters:examplecom en @piet:examplecom!", &known); |
| 953 | assert_eq!( |
| 954 | parts, |
| 955 | vec![ |
| 956 | TextPart::Text("Hoi ".into()), |
| 957 | TextPart::Mention { |
| 958 | key: "jan.peters:examplecom".into(), |
| 959 | email: Some("jan.peters@example.com".into()) |
| 960 | }, |
| 961 | TextPart::Text(" en ".into()), |
| 962 | TextPart::Mention { |
| 963 | key: "piet:examplecom".into(), |
| 964 | email: None |
| 965 | }, |
| 966 | TextPart::Text("!".into()), |
| 967 | ] |
| 968 | ); |
| 969 | assert_eq!( |
| 970 | mention_label("jan.peters:examplecom", Some("jan.peters@example.com")), |
| 971 | "@Jan" |
| 972 | ); |
| 973 | assert_eq!(mention_label("piet:examplecom", None), "@Piet"); |
| 974 | } |
| 975 | |
| 976 | #[test] |
| 977 | fn no_mentions_in_code_addresses_or_times() { |
| 978 | let none = |text: &str| { |
| 979 | split_mentions(text, &[]) |
| 980 | .iter() |
| 981 | .all(|part| matches!(part, TextPart::Text(_))) |
| 982 | }; |
| 983 | assert!(none("mail jan@example.com:examplecom")); |
| 984 | assert!(none("`@jan:examplecom`")); |
| 985 | assert!(none("```\n@jan:examplecom\n```")); |
| 986 | assert!(none("@jan:examplecom:extra")); |
| 987 | assert!(none("om 10:30 @ kantoor")); |
| 988 | } |
| 989 | |
| 990 | #[test] |
| 991 | fn unread_is_local_and_starts_clean() { |
| 992 | let mut seen = SeenTickets::default(); |
| 993 | let ticket = Ticket { |
| 994 | id: 1, |
| 995 | updated_at: "2026-01-15T10:00:00+01:00".into(), |
| 996 | ..Default::default() |
| 997 | }; |
| 998 | assert!(!seen.is_unread(&ticket)); |
| 999 | assert!(seen.initialize(std::slice::from_ref(&ticket))); |
| 1000 | assert!(!seen.initialize(&[])); |
| 1001 | assert!(!seen.is_unread(&ticket)); |
| 1002 | let newer = Ticket { |
| 1003 | updated_at: "2026-01-15T12:00:00+01:00".into(), |
| 1004 | ..ticket.clone() |
| 1005 | }; |
| 1006 | assert!(seen.is_unread(&newer)); |
| 1007 | let fresh = Ticket { |
| 1008 | id: 2, |
| 1009 | ..ticket.clone() |
| 1010 | }; |
| 1011 | assert_eq!(seen.unread_count(&[newer.clone(), fresh]), 2); |
| 1012 | assert!(seen.mark(&newer)); |
| 1013 | assert!(!seen.is_unread(&newer)); |
| 1014 | let restored = SeenTickets::from_json(&seen.to_json()); |
| 1015 | assert_eq!(restored, seen); |
| 1016 | } |
| 1017 | |
| 1018 | #[test] |
| 1019 | fn mime_comes_from_the_extension() { |
| 1020 | assert_eq!(mime_for("Scherm.PNG"), "image/png"); |
| 1021 | assert_eq!(mime_for("rapport.pdf"), "application/pdf"); |
| 1022 | assert_eq!(mime_for("geen-extensie"), "application/octet-stream"); |
| 1023 | } |
| 1024 | } |