BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / call / week.rs

week.rs

76d44f37 History
week.rs 26.9 KiB Download Raw
1use std::time::Instant;
2
3use chatsvc::{Calendar, CalendarEvent, CalendarSource, ResponseType, ShowAs};
4use chrono::{Duration, FixedOffset, Local, NaiveDate, Offset, Weekday};
5use gpui_kit::Context;
6
7use super::agenda::demo_events;
8use super::calendar::demo_anchor;
9use super::calendar_prefs::save_calendar_prefs;
10use super::week_grid::{
11 CalendarSpan, WeekLayout, dates_range, local_midnight, visible_dates, week_start,
12};
13use crate::app_state::AppState;
14
15pub const CALENDAR_LOAD_FAILURE: &str = "We couldn't load your calendar.";
16
17/// One calendar source that did not load for the visible range.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct CalendarLoadFailure {
20 pub source: CalendarSource,
21 pub message: String,
22}
23
24#[derive(Debug, Clone, Default)]
25pub struct CalendarWeek {
26 pub start: Option<NaiveDate>,
27 pub span: CalendarSpan,
28 pub events: Vec<CalendarEvent>,
29 pub loading: bool,
30 /// Sources that failed on the last load; cleared by the next load.
31 pub failures: Vec<CalendarLoadFailure>,
32 /// The calendar section is on screen (drives refresh on the poll interval).
33 pub visible: bool,
34 /// A load was asked for before the session existed; run it once it does.
35 pending: bool,
36 request: u64,
37}
38
39impl CalendarWeek {
40 pub fn with_span(span: CalendarSpan) -> Self {
41 CalendarWeek {
42 span,
43 ..CalendarWeek::default()
44 }
45 }
46
47 /// True once when a skipped load should run now.
48 pub(crate) fn take_pending(&mut self) -> bool {
49 std::mem::take(&mut self.pending)
50 }
51}
52
53impl AppState {
54 /// Week layout from the calendar settings and the regional format's first day.
55 pub fn calendar_layout(&self) -> WeekLayout {
56 self.calendar_prefs
57 .layout(app_base::format::regional_first_day())
58 }
59
60 pub fn calendar_start(&self) -> NaiveDate {
61 self.calendar_week
62 .start
63 .unwrap_or_else(|| self.calendar_span_start(Local::now().date_naive()))
64 }
65
66 /// Start of the visible span's range that contains `date`.
67 pub fn calendar_span_start(&self, date: NaiveDate) -> NaiveDate {
68 self.calendar_week
69 .span
70 .start_for(date, &self.calendar_layout())
71 }
72
73 /// The dates the grid draws, in column order.
74 pub fn calendar_dates(&self) -> Vec<NaiveDate> {
75 visible_dates(
76 self.calendar_week.span,
77 self.calendar_start(),
78 &self.calendar_layout(),
79 )
80 }
81
82 pub fn calendar_shows_today(&self) -> bool {
83 self.calendar_dates().contains(&Local::now().date_naive())
84 }
85
86 pub fn open_calendar(&mut self, cx: &mut Context<Self>) {
87 if !self.calendar_available() {
88 return;
89 }
90 self.calendar_week.visible = true;
91 self.calendar_week.start = Some(self.calendar_start());
92 self.request_calendar_scroll_to_now(cx);
93 self.load_calendar_week(cx);
94 }
95
96 /// The user left the calendar section; stop refreshing its range.
97 pub fn close_calendar(&mut self) {
98 self.calendar_week.visible = false;
99 }
100
101 /// Reload the visible range after an agenda poll while the calendar is on screen.
102 pub(crate) fn refresh_visible_calendar(&mut self, cx: &mut Context<Self>) {
103 if self.calendar_week.visible && self.calendar_week.start.is_some() {
104 self.load_calendar_week(cx);
105 }
106 }
107
108 /// Retry from the inline notice after a source failed.
109 pub fn retry_calendar_week(&mut self, cx: &mut Context<Self>) {
110 self.load_calendar_week(cx);
111 }
112
113 /// Run a grid load that was skipped because no session existed yet.
114 pub(crate) fn run_pending_calendar_load(&mut self, cx: &mut Context<Self>) {
115 if self.calendar_week.take_pending() {
116 self.load_calendar_week(cx);
117 }
118 }
119
120 pub fn shift_calendar_week(&mut self, steps: i32, cx: &mut Context<Self>) {
121 let span = self.calendar_week.span;
122 let layout = self.calendar_layout();
123 self.calendar_week.start = Some(span.shifted(self.calendar_start(), steps, &layout));
124 self.request_calendar_scroll_to_now(cx);
125 self.load_calendar_week(cx);
126 }
127
128 pub fn calendar_to_today(&mut self, cx: &mut Context<Self>) {
129 self.calendar_week.start = None;
130 self.open_calendar(cx);
131 }
132
133 /// Month the mini month shows: the user's own choice, else the visible range.
134 pub fn calendar_mini_month_shown(&self) -> NaiveDate {
135 self.calendar_mini_month.unwrap_or_else(|| {
136 let dates = self.calendar_dates();
137 let middle = dates.get(dates.len() / 2).copied();
138 super::week_grid::first_of_month(middle.unwrap_or_else(|| self.calendar_start()))
139 })
140 }
141
142 pub fn move_calendar_mini_month(&mut self, steps: i32, cx: &mut Context<Self>) {
143 let month = self.calendar_mini_month_shown();
144 let moved = if steps >= 0 {
145 month.checked_add_months(chrono::Months::new(steps.unsigned_abs()))
146 } else {
147 month.checked_sub_months(chrono::Months::new(steps.unsigned_abs()))
148 };
149 self.calendar_mini_month = Some(moved.unwrap_or(month));
150 cx.notify();
151 }
152
153 pub fn toggle_calendar_group_expanded(&mut self, group: &str, cx: &mut Context<Self>) {
154 if let Some(index) = self
155 .calendar_expanded_groups
156 .iter()
157 .position(|existing| existing == group)
158 {
159 self.calendar_expanded_groups.remove(index);
160 } else {
161 self.calendar_expanded_groups.push(group.to_owned());
162 }
163 cx.notify();
164 }
165
166 pub fn request_calendar_scroll_to_now(&mut self, cx: &mut Context<Self>) {
167 // Every navigation lands here: the mini month follows the grid again.
168 self.calendar_mini_month = None;
169 if !crate::call::calendar_now::shows_hour_grid(self.calendar_week.span) {
170 return;
171 }
172 self.calendar_scroll_to_now = self.calendar_scroll_to_now.wrapping_add(1);
173 cx.notify();
174 }
175
176 /// Span chosen from the view menu; remembered as the last used span.
177 pub fn set_calendar_span(&mut self, span: CalendarSpan, cx: &mut Context<Self>) {
178 let today = Local::now().date_naive();
179 let start = self.calendar_start();
180 let anchor = if self.calendar_shows_today() {
181 today
182 } else {
183 start
184 };
185 self.calendar_week.span = span;
186 self.calendar_week.start = Some(self.calendar_span_start(anchor));
187 self.calendar_mini_month = None;
188 if self.calendar_prefs.last_span != span {
189 self.calendar_prefs.last_span = span;
190 save_calendar_prefs(&self.store, &self.calendar_prefs);
191 }
192 if crate::call::calendar_now::shows_hour_grid(span) {
193 self.request_calendar_scroll_to_now(cx);
194 }
195 self.load_calendar_week(cx);
196 }
197
198 pub fn show_calendar_date(&mut self, date: NaiveDate, cx: &mut Context<Self>) {
199 self.calendar_week.start = Some(self.calendar_span_start(date));
200 self.request_calendar_scroll_to_now(cx);
201 self.load_calendar_week(cx);
202 }
203
204 pub fn show_calendar_day(&mut self, date: NaiveDate, cx: &mut Context<Self>) {
205 self.calendar_week.span = CalendarSpan::Day;
206 self.show_calendar_date(date, cx);
207 }
208
209 pub(crate) fn load_calendar_week(&mut self, cx: &mut Context<Self>) {
210 if !self.calendar_available() {
211 return;
212 }
213 let start = self.calendar_start();
214 let offset = Local::now().offset().fix();
215 let (from, to) = dates_range(&self.calendar_dates(), offset);
216 if self.mode.demo {
217 let mut events = demo_events(demo_anchor());
218 // Demo meetings sit Monday to Friday of the week the grid shows.
219 // The Monday inside the first shown week, whatever day the week starts on.
220 let dates = self.calendar_dates();
221 let anchor = dates.get(6).or(dates.last()).copied().unwrap_or(start);
222 events.extend(demo_week(week_start(anchor, Weekday::Mon), offset));
223 events.extend(self.demo_meetings.iter().cloned());
224 events.retain(|event| event.end > from && event.start < to);
225 events.sort_by_key(|event| (event.start, event.end));
226 self.calendar_week.events = events;
227 cx.notify();
228 return;
229 }
230 // Grid load needs only the signed-in session, never the calling engine.
231 let Some(engine) = self.engine.clone() else {
232 self.calendar_week.pending = true;
233 return;
234 };
235 self.calendar_week.request += 1;
236 let request = self.calendar_week.request;
237 self.calendar_week.loading = true;
238 cx.notify();
239 let store = self.store.clone();
240 let receiver = crate::runtime::spawn(async move {
241 let started = Instant::now();
242 let accounts = store::load_calendar_accounts(&store);
243 let mut fetched_accounts = accounts.clone();
244 let mut combined = Vec::new();
245 let mut failures = Vec::new();
246 let mut outlook_count = None;
247 if accounts.outlook_selected {
248 match Calendar::new(engine.remote().session())
249 .calendar_view(from, to)
250 .await
251 {
252 Ok(events) => {
253 outlook_count = Some(events.len());
254 combined.extend(events);
255 }
256 Err(error) => failures.push(CalendarLoadFailure {
257 source: CalendarSource::Outlook,
258 message: error.to_string(),
259 }),
260 }
261 }
262 let mut google_count = None;
263 if accounts.has_google() {
264 match crate::google_calendar_sync::fetch_google_events(
265 &mut fetched_accounts,
266 from,
267 to,
268 )
269 .await
270 {
271 Ok(events) => {
272 // Keep only refreshed tokens: a toggle made meanwhile must survive.
273 let _ = store::merge_google_tokens(&store, &fetched_accounts);
274 google_count = Some(events.len());
275 combined.extend(events);
276 }
277 Err(error) => failures.push(CalendarLoadFailure {
278 source: CalendarSource::Google,
279 message: error,
280 }),
281 }
282 }
283 let mut caldav_count = None;
284 if accounts.has_caldav() {
285 match crate::caldav_sync::fetch_caldav_events(&mut fetched_accounts, from, to).await
286 {
287 Ok((events, partial)) => {
288 let _ = store::merge_caldav_metadata(&store, &fetched_accounts);
289 caldav_count = Some(events.len());
290 combined.extend(events);
291 for message in partial {
292 failures.push(CalendarLoadFailure {
293 source: CalendarSource::CalDav,
294 message,
295 });
296 }
297 }
298 Err(error) => failures.push(CalendarLoadFailure {
299 source: CalendarSource::CalDav,
300 message: error,
301 }),
302 }
303 }
304 if accounts.has_ics() {
305 match crate::ics_sync::fetch_ics_events(&accounts, from, to).await {
306 Ok((events, partial)) => {
307 combined.extend(events);
308 for message in partial {
309 failures.push(CalendarLoadFailure {
310 source: CalendarSource::Ics,
311 message,
312 });
313 }
314 }
315 Err(error) => failures.push(CalendarLoadFailure {
316 source: CalendarSource::Ics,
317 message: error,
318 }),
319 }
320 }
321 crate::diagnostics::record(load_summary(
322 from,
323 to,
324 outlook_count,
325 google_count,
326 caldav_count,
327 started.elapsed().as_millis(),
328 &failures,
329 ));
330 let home = home_calendar(&accounts);
331 (chatsvc::merge_calendar_events(combined, home), failures)
332 });
333 cx.spawn(async move |this, cx| {
334 let loaded = receiver.await.unwrap_or_else(|_| {
335 (
336 Vec::new(),
337 vec![CalendarLoadFailure {
338 source: CalendarSource::Outlook,
339 message: CALENDAR_LOAD_FAILURE.to_owned(),
340 }],
341 )
342 });
343 this.update(cx, |state, cx| {
344 if state.calendar_week.request != request {
345 return;
346 }
347 state.calendar_week.loading = false;
348 let (events, failures) = loaded;
349 let previous = std::mem::take(&mut state.calendar_week.events);
350 let mut events = keep_failed_sources(&previous, events, &failures);
351 retain_peek_details(&previous, &mut events);
352 state.calendar_week.events = events;
353 state.calendar_week.failures = failures;
354 cx.notify();
355 })
356 .ok();
357 })
358 .detach();
359 }
360}
361
362/// A source that failed keeps its previous events on screen instead of blanking the week.
363/// When the round already returned some events for that source (partial calendar failure),
364/// previous events are left out so successful calendars are not duplicated.
365pub(crate) fn keep_failed_sources(
366 previous: &[CalendarEvent],
367 mut events: Vec<CalendarEvent>,
368 failures: &[CalendarLoadFailure],
369) -> Vec<CalendarEvent> {
370 for failure in failures {
371 if events.iter().any(|event| event.source == failure.source) {
372 continue;
373 }
374 events.extend(
375 previous
376 .iter()
377 .filter(|event| event.source == failure.source)
378 .cloned(),
379 );
380 }
381 events.sort_by_key(|event| (event.start, event.end));
382 events
383}
384
385/// One diagnostics line per grid load, so an empty week can be traced to its cause.
386pub(crate) fn load_summary(
387 from: chrono::DateTime<chrono::Utc>,
388 to: chrono::DateTime<chrono::Utc>,
389 outlook: Option<usize>,
390 google: Option<usize>,
391 caldav: Option<usize>,
392 elapsed_ms: u128,
393 failures: &[CalendarLoadFailure],
394) -> String {
395 let count = |value: Option<usize>| value.map_or_else(|| "-".to_owned(), |n| n.to_string());
396 let mut line = format!(
397 "calendar grid: {}..{} outlook={} google={} caldav={} in {elapsed_ms} ms",
398 from.format("%Y-%m-%dT%H:%MZ"),
399 to.format("%Y-%m-%dT%H:%MZ"),
400 count(outlook),
401 count(google),
402 count(caldav),
403 );
404 for failure in failures {
405 line.push_str(&format!(
406 "; {} failed: {}",
407 failure.source.label(),
408 failure.message.chars().take(160).collect::<String>()
409 ));
410 }
411 line
412}
413
414fn home_calendar(accounts: &store::CalendarAccounts) -> Option<chatsvc::HomeCalendar<'_>> {
415 use store::CalendarProvider;
416 let source = match accounts.home.provider {
417 CalendarProvider::Outlook => CalendarSource::Outlook,
418 CalendarProvider::Google => CalendarSource::Google,
419 CalendarProvider::CalDav => CalendarSource::CalDav,
420 };
421 Some(chatsvc::HomeCalendar {
422 source,
423 account_id: accounts.home.account_id.as_str(),
424 calendar_id: accounts.home.calendar_id.as_str(),
425 })
426}
427
428fn retain_peek_details(previous: &[CalendarEvent], events: &mut [CalendarEvent]) {
429 for event in events {
430 let Some(old) = previous
431 .iter()
432 .find(|candidate| candidate.object_id == event.object_id)
433 else {
434 continue;
435 };
436 if event.body_preview.is_none() {
437 event.body_preview = old.body_preview.clone();
438 }
439 if event.body_html.is_none() {
440 event.body_html = old.body_html.clone();
441 }
442 if event.attendees.is_empty() {
443 event.attendees = old.attendees.clone();
444 }
445 if event.location.is_none() {
446 event.location = old.location.clone();
447 }
448 if event.response_counts.is_none() {
449 event.response_counts = old.response_counts;
450 }
451 if event.series_master_id.is_none() {
452 event.series_master_id = old.series_master_id.clone();
453 }
454 if event.reminders.is_empty() {
455 event.reminders = old.reminders.clone();
456 }
457 if event.source_link.is_none() {
458 event.source_link = old.source_link.clone();
459 }
460 if event.web_link.is_none() {
461 event.web_link = old.web_link.clone();
462 }
463 if event.calendar_name.is_none() {
464 event.calendar_name = old.calendar_name.clone();
465 }
466 if old.series {
467 event.series = true;
468 }
469 }
470}
471
472fn demo_show_as(subject: &str, response: ResponseType) -> ShowAs {
473 match response {
474 _ if subject.starts_with("Following: ") => ShowAs::Free,
475 ResponseType::Tentative | ResponseType::NotResponded => ShowAs::Tentative,
476 _ => ShowAs::Busy,
477 }
478}
479
480fn demo_week(monday: NaiveDate, offset: FixedOffset) -> Vec<CalendarEvent> {
481 let slots: [(&str, &str, i64, i64, i64, ResponseType); 8] = [
482 (
483 "Team standup",
484 "Mara Lindqvist",
485 0,
486 9 * 60 + 30,
487 15,
488 ResponseType::Accepted,
489 ),
490 (
491 "Release review",
492 "Jonas Ortega",
493 0,
494 11 * 60,
495 60,
496 ResponseType::Organizer,
497 ),
498 (
499 "Customer sync",
500 "Priya Nair",
501 0,
502 11 * 60 + 30,
503 60,
504 ResponseType::NotResponded,
505 ),
506 (
507 "Team standup",
508 "Mara Lindqvist",
509 1,
510 9 * 60 + 30,
511 15,
512 ResponseType::Accepted,
513 ),
514 (
515 "Architecture deep dive",
516 "Lena Brandt",
517 2,
518 14 * 60,
519 90,
520 ResponseType::Tentative,
521 ),
522 (
523 "1:1 Jonas",
524 "Jonas Ortega",
525 3,
526 10 * 60,
527 30,
528 ResponseType::Accepted,
529 ),
530 (
531 "Following: Design office hours",
532 "Lena Brandt",
533 3,
534 13 * 60,
535 60,
536 ResponseType::Tentative,
537 ),
538 (
539 "Sprint retro",
540 "Mara Lindqvist",
541 4,
542 15 * 60,
543 60,
544 ResponseType::Accepted,
545 ),
546 ];
547 slots
548 .iter()
549 .enumerate()
550 .map(|(index, (subject, organizer, day, minute, length, response))| {
551 let start =
552 local_midnight(monday + Duration::days(*day), offset) + Duration::minutes(*minute);
553 CalendarEvent {
554 object_id: format!("demo-week-{index}"),
555 subject: (*subject).to_owned(),
556 start,
557 end: start + Duration::minutes(*length),
558 all_day: false,
559 cancelled: false,
560 online: true,
561 join_url: Some(format!(
562 "https://teams.microsoft.com/l/meetup-join/19%3ameeting_demoweek{index}%40thread.v2/0"
563 )),
564 thread_id: None,
565 organizer_name: Some((*organizer).to_owned()),
566 organizer_address: None,
567 ical_uid: None,
568 show_as: demo_show_as(subject, *response),
569 dial_in: None,
570 response: *response,
571 ..Default::default()
572 }
573 })
574 .collect()
575}
576
577#[cfg(test)]
578mod tests {
579 use std::sync::Arc;
580
581 use chatsvc::{CalendarEvent, CalendarSource};
582 use chrono::{Offset as _, TimeZone, Utc};
583 use gpui_kit::{AppContext as _, TestAppContext};
584 use store::Store;
585
586 use super::{CalendarLoadFailure, keep_failed_sources, load_summary};
587 use crate::app_state::{AppState, Mode};
588
589 fn event(id: &str, source: CalendarSource, hour: u32) -> CalendarEvent {
590 let start = Utc.with_ymd_and_hms(2026, 11, 16, hour, 0, 0).unwrap();
591 CalendarEvent {
592 object_id: id.into(),
593 subject: id.into(),
594 start,
595 end: start + chrono::Duration::minutes(30),
596 source,
597 ..Default::default()
598 }
599 }
600
601 #[gpui_kit::test]
602 fn a_load_before_the_session_runs_once_the_session_is_there(cx: &mut TestAppContext) {
603 cx.update(gpui_kit::init);
604 let store = Arc::new(Store::open_in_memory().unwrap());
605 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
606 cx.update(|cx| {
607 app.update(cx, |state, cx| {
608 state.open_calendar(cx);
609 assert!(state.calendar_week.visible);
610 assert!(state.calendar_week.take_pending());
611 assert!(!state.calendar_week.take_pending());
612 })
613 });
614 }
615
616 #[gpui_kit::test]
617 fn a_guest_org_neither_opens_nor_loads_the_calendar(cx: &mut TestAppContext) {
618 cx.update(gpui_kit::init);
619 let store = Arc::new(Store::open_in_memory().unwrap());
620 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
621 cx.update(|cx| {
622 app.update(cx, |state, cx| {
623 let guest = "11111111-2222-3333-4444-555555555555";
624 state.orgs.active = Some(guest.into());
625 state.orgs.list.push(app_base::orgs::Org {
626 id: guest.into(),
627 name: "Contoso".into(),
628 guest: true,
629 });
630 state.open_calendar(cx);
631 state.retry_calendar_week(cx);
632 assert!(!state.calendar_week.visible);
633 assert!(!state.calendar_week.take_pending());
634 })
635 });
636 }
637
638 #[gpui_kit::test]
639 fn a_poll_reloads_the_grid_only_while_the_calendar_is_shown(cx: &mut TestAppContext) {
640 cx.update(gpui_kit::init);
641 let store = Arc::new(Store::open_in_memory().unwrap());
642 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
643 cx.update(|cx| {
644 app.update(cx, |state, cx| {
645 state.open_calendar(cx);
646 state.calendar_week.take_pending();
647 state.close_calendar();
648 state.refresh_visible_calendar(cx);
649 assert!(!state.calendar_week.take_pending());
650 state.open_calendar(cx);
651 state.calendar_week.take_pending();
652 state.refresh_visible_calendar(cx);
653 assert!(state.calendar_week.take_pending());
654 })
655 });
656 }
657
658 #[gpui_kit::test]
659 fn navigating_asks_the_grid_to_align_again(cx: &mut TestAppContext) {
660 cx.update(gpui_kit::init);
661 let store = Arc::new(Store::open_in_memory().unwrap());
662 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
663 cx.update(|cx| {
664 app.update(cx, |state, cx| {
665 state.open_calendar(cx);
666 let opened = state.calendar_scroll_to_now;
667 state.shift_calendar_week(1, cx);
668 assert_ne!(state.calendar_scroll_to_now, opened);
669 let shifted = state.calendar_scroll_to_now;
670 state.show_calendar_date(chrono::Local::now().date_naive(), cx);
671 assert_ne!(state.calendar_scroll_to_now, shifted);
672 })
673 });
674 }
675
676 #[gpui_kit::test]
677 fn demo_week_fills_the_visible_work_week(cx: &mut TestAppContext) {
678 cx.update(gpui_kit::init);
679 let store = Arc::new(Store::open_in_memory().unwrap());
680 let mode = Mode {
681 demo: true,
682 ..Mode::default()
683 };
684 let app = cx.update(|cx| cx.new(|_| AppState::new(store, mode)));
685 cx.update(|cx| {
686 app.update(cx, |state, cx| {
687 state.open_calendar(cx);
688 let dates = state.calendar_dates();
689 let offset = chrono::Local::now().offset().fix();
690 let days =
691 crate::call::week_grid::week_days(&state.calendar_week.events, &dates, offset);
692 let blocks: usize = days.iter().map(|day| day.blocks.len()).sum();
693 assert!(
694 blocks >= 8,
695 "dates {dates:?}, events {}, blocks {blocks}",
696 state.calendar_week.events.len()
697 );
698 })
699 });
700 }
701
702 #[test]
703 fn a_failed_source_keeps_its_previous_events() {
704 let previous = vec![
705 event("outlook-old", CalendarSource::Outlook, 9),
706 event("google-old", CalendarSource::Google, 10),
707 ];
708 let fresh = vec![event("google-new", CalendarSource::Google, 8)];
709 let failures = [CalendarLoadFailure {
710 source: CalendarSource::Outlook,
711 message: "HTTP 503".into(),
712 }];
713 let ids: Vec<_> = keep_failed_sources(&previous, fresh.clone(), &failures)
714 .into_iter()
715 .map(|event| event.object_id)
716 .collect();
717 assert_eq!(ids, ["google-new", "outlook-old"]);
718 let ids: Vec<_> = keep_failed_sources(&previous, fresh, &[])
719 .into_iter()
720 .map(|event| event.object_id)
721 .collect();
722 assert_eq!(ids, ["google-new"]);
723 }
724
725 #[test]
726 fn a_partial_source_failure_does_not_duplicate_fresh_events() {
727 let previous = vec![
728 event("caldav-old-a", CalendarSource::CalDav, 9),
729 event("caldav-old-b", CalendarSource::CalDav, 10),
730 ];
731 let fresh = vec![event("caldav-new", CalendarSource::CalDav, 8)];
732 let failures = [CalendarLoadFailure {
733 source: CalendarSource::CalDav,
734 message: "CalDAV Work: timeout".into(),
735 }];
736 let ids: Vec<_> = keep_failed_sources(&previous, fresh, &failures)
737 .into_iter()
738 .map(|event| event.object_id)
739 .collect();
740 assert_eq!(ids, ["caldav-new"]);
741 }
742
743 #[test]
744 fn the_load_summary_names_counts_and_failures() {
745 let from = Utc.with_ymd_and_hms(2026, 11, 15, 23, 0, 0).unwrap();
746 let to = Utc.with_ymd_and_hms(2026, 11, 20, 23, 0, 0).unwrap();
747 let failures = [CalendarLoadFailure {
748 source: CalendarSource::Google,
749 message: "client_secret is missing".into(),
750 }];
751 assert_eq!(
752 load_summary(from, to, Some(3), None, None, 412, &failures),
753 "calendar grid: 2026-11-15T23:00Z..2026-11-20T23:00Z outlook=3 google=- caldav=- in 412 ms; \
754 Google failed: client_secret is missing"
755 );
756 }
757}