| 1 | //! Daedalus-planning als read-only agenda (scope `daedalus`). |
| 2 | //! |
| 3 | //! Zet de bron in `app-state` (`kvt_calendar`) neer zolang de koppeling er is en |
| 4 | //! de planning aan staat; de weekweergave haalt de afspraken dan mee op. |
| 5 | //! Upstream-haak: `app-state/src/call/week.rs`. |
| 6 | |
| 7 | use std::sync::Arc; |
| 8 | |
| 9 | use chatsvc::{CalendarEvent, CalendarSource}; |
| 10 | use chrono::{DateTime, Duration, Utc}; |
| 11 | use gpui_kit::*; |
| 12 | use kvt_sleutels::planning::PlanningEvent; |
| 13 | use kvt_sleutels::{CardsClient, ClientError}; |
| 14 | |
| 15 | use super::{Kvt, Link, read}; |
| 16 | use crate::app_state::AppHandle; |
| 17 | use crate::i18n::tr; |
| 18 | use crate::kvt_calendar::{self, Fetch}; |
| 19 | |
| 20 | /// Uit = `off`; aan is de standaard (alleen eigen werkorders, alleen lezen). |
| 21 | const PLANNING_META_KEY: &str = "kvt.daedalus.planning"; |
| 22 | pub(crate) const CALENDAR_ID: &str = "kvt-daedalus"; |
| 23 | const CALENDAR_NAME: &str = "Daedalus"; |
| 24 | /// Daedalus staat hooguit 62 dagen per verzoek toe. |
| 25 | const MAX_DAYS: i64 = 62; |
| 26 | |
| 27 | pub(super) fn stored_enabled(cx: &App) -> bool { |
| 28 | cx.try_global::<AppHandle>() |
| 29 | .and_then(|handle| { |
| 30 | handle |
| 31 | .0 |
| 32 | .read(cx) |
| 33 | .store |
| 34 | .meta(PLANNING_META_KEY) |
| 35 | .ok() |
| 36 | .flatten() |
| 37 | }) |
| 38 | .is_none_or(|value| value != "off") |
| 39 | } |
| 40 | |
| 41 | pub fn enabled(cx: &App) -> bool { |
| 42 | read(cx, |kvt| kvt.planning).unwrap_or(false) |
| 43 | } |
| 44 | |
| 45 | pub fn set_enabled(on: bool, cx: &mut App) { |
| 46 | if let Some(handle) = cx.try_global::<AppHandle>() { |
| 47 | let _ = handle |
| 48 | .0 |
| 49 | .read(cx) |
| 50 | .store |
| 51 | .set_meta(PLANNING_META_KEY, if on { "on" } else { "off" }); |
| 52 | } |
| 53 | super::update(cx, |kvt| kvt.planning = on); |
| 54 | } |
| 55 | |
| 56 | /// Na elke wijziging van de KVT-staat: bron neerzetten of weghalen, en de |
| 57 | /// agenda herladen als dat iets veranderde. |
| 58 | pub(super) fn sync(cx: &mut App) { |
| 59 | let Some(wanted) = read(cx, wanted_source) else { |
| 60 | return; |
| 61 | }; |
| 62 | let current = read(cx, |kvt| kvt.calendar_source.clone()).flatten(); |
| 63 | if wanted == current { |
| 64 | return; |
| 65 | } |
| 66 | cx.global_mut::<Kvt>().calendar_source = wanted.clone(); |
| 67 | let demo = read(cx, |kvt| kvt.demo).unwrap_or(false); |
| 68 | if demo { |
| 69 | kvt_calendar::set_demo(wanted.map(|_| Arc::new(super::demo::planning) as _)); |
| 70 | } else { |
| 71 | let client = read(cx, |kvt| kvt.client.clone()); |
| 72 | kvt_calendar::set_source( |
| 73 | wanted |
| 74 | .zip(client) |
| 75 | .map(|(token, client)| fetcher(client, token)), |
| 76 | ); |
| 77 | } |
| 78 | if let Some(handle) = cx.try_global::<AppHandle>() { |
| 79 | handle |
| 80 | .0 |
| 81 | .clone() |
| 82 | .update(cx, |state, cx| state.refresh_calendar(cx)); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// Token waarmee de planning opgehaald wordt; `None` = geen planning. |
| 87 | fn wanted_source(kvt: &Kvt) -> Option<String> { |
| 88 | match &kvt.link { |
| 89 | Link::Linked(stored) if kvt.planning => Some(stored.token.clone()), |
| 90 | _ => None, |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | fn fetcher(client: CardsClient, token: String) -> Fetch { |
| 95 | let unavailable = tr("kvt.planning.unavailable"); |
| 96 | let sign_in = tr("kvt.planning.sign_in"); |
| 97 | Arc::new(move |from: DateTime<Utc>, to: DateTime<Utc>| { |
| 98 | let (client, token) = (client.clone(), token.clone()); |
| 99 | let (unavailable, sign_in) = (unavailable.clone(), sign_in.clone()); |
| 100 | Box::pin(async move { |
| 101 | let to = to.min(from + Duration::days(MAX_DAYS)); |
| 102 | // Daedalus rekent in Europe/Amsterdam; de lokale datum volstaat. |
| 103 | let tz = chrono::Local; |
| 104 | let (first, last) = ( |
| 105 | from.with_timezone(&tz).date_naive(), |
| 106 | (to - Duration::seconds(1)).with_timezone(&tz).date_naive(), |
| 107 | ); |
| 108 | match client.daedalus_planning(&token, first, last).await { |
| 109 | Ok(events) => Ok(events.iter().filter_map(calendar_event).collect()), |
| 110 | // Geen scope of geen monteur: gewoon geen planning. |
| 111 | Err(ClientError::Forbidden | ClientError::NotFound) => Ok(Vec::new()), |
| 112 | Err(ClientError::Unauthorized) => Err(sign_in), |
| 113 | Err(_) => Err(unavailable), |
| 114 | } |
| 115 | }) |
| 116 | }) |
| 117 | } |
| 118 | |
| 119 | pub(crate) fn calendar_event(event: &PlanningEvent) -> Option<CalendarEvent> { |
| 120 | let (start, end) = event.span()?; |
| 121 | let mut details = Vec::new(); |
| 122 | if !event.component.is_empty() { |
| 123 | details.push(event.component.clone()); |
| 124 | } |
| 125 | if !event.status.is_empty() { |
| 126 | details.push(event.status.clone()); |
| 127 | } |
| 128 | details.push(event.company.clone()); |
| 129 | Some(CalendarEvent { |
| 130 | object_id: format!("{CALENDAR_ID}#{}", event.id), |
| 131 | subject: event.title.clone(), |
| 132 | start, |
| 133 | end, |
| 134 | all_day: event.all_day, |
| 135 | ical_uid: Some(format!("{}@daedalus.kvt.nl", event.id)), |
| 136 | source: CalendarSource::Ics, |
| 137 | account_id: Some(CALENDAR_ID.to_owned()), |
| 138 | calendar_id: Some(CALENDAR_ID.to_owned()), |
| 139 | sources: vec![CalendarSource::Ics], |
| 140 | location: (!event.object.is_empty()).then(|| event.object.clone()), |
| 141 | body_preview: Some(details.join(" · ")), |
| 142 | web_link: kvt_sleutels::links::is_trusted_link(&event.url).then(|| event.url.clone()), |
| 143 | calendar_name: Some(CALENDAR_NAME.to_owned()), |
| 144 | ..Default::default() |
| 145 | }) |
| 146 | } |
| 147 | |
| 148 | #[cfg(test)] |
| 149 | mod tests { |
| 150 | use kvt_sleutels::planning::PlanningEvent; |
| 151 | |
| 152 | use super::calendar_event; |
| 153 | |
| 154 | fn event(url: &str) -> PlanningEvent { |
| 155 | PlanningEvent { |
| 156 | id: "WO2699001@Testbedrijf".into(), |
| 157 | workorder: "WO2699001".into(), |
| 158 | company: "Testbedrijf".into(), |
| 159 | title: "WO2699001 · Onderhoud".into(), |
| 160 | object: "MS Voorbeeld".into(), |
| 161 | component: "Hoofdmotor".into(), |
| 162 | status: "Gepland".into(), |
| 163 | all_day: true, |
| 164 | start: "2026-01-15".into(), |
| 165 | end: "2026-01-17".into(), |
| 166 | url: url.into(), |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | #[test] |
| 171 | fn work_orders_become_read_only_events() { |
| 172 | let converted = calendar_event(&event( |
| 173 | "https://sleutels.kvt.nl/daedalus/index.php?workorder=WO2699001", |
| 174 | )) |
| 175 | .unwrap(); |
| 176 | assert_eq!(converted.source, chatsvc::CalendarSource::Ics); |
| 177 | assert!(converted.all_day); |
| 178 | assert_eq!(converted.location.as_deref(), Some("MS Voorbeeld")); |
| 179 | assert_eq!(converted.calendar_name.as_deref(), Some("Daedalus")); |
| 180 | assert_eq!( |
| 181 | converted.body_preview.as_deref(), |
| 182 | Some("Hoofdmotor · Gepland · Testbedrijf") |
| 183 | ); |
| 184 | assert!(converted.web_link.is_some()); |
| 185 | } |
| 186 | |
| 187 | #[test] |
| 188 | fn an_untrusted_link_is_dropped() { |
| 189 | assert!( |
| 190 | calendar_event(&event("https://example.com/x")) |
| 191 | .unwrap() |
| 192 | .web_link |
| 193 | .is_none() |
| 194 | ); |
| 195 | } |
| 196 | } |