BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-call-model / src / calendar_prefs.rs

calendar_prefs.rs

calendar_prefs.rs 7.9 KiB Download Raw
1//! Local calendar preferences: default view, last span, week layout, time scale.
2//!
3//! Work days and hours belong to the Outlook mailbox (Teams and Outlook read them
4//! there); the copy here is only a cache so the grid has them before the mailbox
5//! answers and while offline.
6
7use chrono::{NaiveTime, Weekday};
8use serde::{Deserialize, Serialize};
9use store::Store;
10
11use crate::week_grid::{CalendarSpan, WeekLayout};
12
13pub const CALENDAR_PREFS_KEY: &str = "calendar.prefs";
14
15/// Groups in the calendar list are keyed by this id for Outlook.
16pub const OUTLOOK_GROUP: &str = "outlook";
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
19#[serde(rename_all = "snake_case")]
20pub enum DefaultView {
21 #[default]
22 LastUsed,
23 Day,
24 WorkWeek,
25 Week,
26 Month,
27}
28
29impl DefaultView {
30 pub const ALL: [DefaultView; 5] = [
31 DefaultView::LastUsed,
32 DefaultView::Day,
33 DefaultView::WorkWeek,
34 DefaultView::Week,
35 DefaultView::Month,
36 ];
37
38 pub fn span(self) -> Option<CalendarSpan> {
39 match self {
40 DefaultView::LastUsed => None,
41 DefaultView::Day => Some(CalendarSpan::Day),
42 DefaultView::WorkWeek => Some(CalendarSpan::WorkWeek),
43 DefaultView::Week => Some(CalendarSpan::Week),
44 DefaultView::Month => Some(CalendarSpan::Month),
45 }
46 }
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
50#[serde(rename_all = "snake_case")]
51pub enum TimeScale {
52 Min15,
53 /// Teams default.
54 #[default]
55 Min30,
56 Min60,
57}
58
59impl TimeScale {
60 pub const ALL: [TimeScale; 3] = [TimeScale::Min15, TimeScale::Min30, TimeScale::Min60];
61
62 pub fn minutes(self) -> u32 {
63 match self {
64 TimeScale::Min15 => 15,
65 TimeScale::Min30 => 30,
66 TimeScale::Min60 => 60,
67 }
68 }
69
70 /// Minor grid lines inside one hour.
71 pub fn steps_per_hour(self) -> u32 {
72 60 / self.minutes()
73 }
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
77#[serde(rename_all = "snake_case")]
78pub enum WeekendWorkWeek {
79 /// Outlook and Teams show the coming work week on a weekend.
80 #[default]
81 NextWeek,
82 ThisWeek,
83}
84
85/// Work days and hours as the mailbox stores them, in the mailbox's local time.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub struct WorkHours {
88 pub days: Vec<Weekday>,
89 pub start: NaiveTime,
90 pub end: NaiveTime,
91}
92
93impl Default for WorkHours {
94 fn default() -> Self {
95 WorkHours {
96 days: vec![
97 Weekday::Mon,
98 Weekday::Tue,
99 Weekday::Wed,
100 Weekday::Thu,
101 Weekday::Fri,
102 ],
103 start: NaiveTime::from_hms_opt(8, 0, 0).unwrap_or_default(),
104 end: NaiveTime::from_hms_opt(17, 0, 0).unwrap_or_default(),
105 }
106 }
107}
108
109impl WorkHours {
110 pub fn is_work_day(&self, day: Weekday) -> bool {
111 self.days.contains(&day)
112 }
113
114 /// Minutes after midnight where work time starts and ends.
115 pub fn minute_range(&self) -> (i64, i64) {
116 let minute = |time: NaiveTime| {
117 i64::from(chrono::Timelike::hour(&time)) * 60
118 + i64::from(chrono::Timelike::minute(&time))
119 };
120 (minute(self.start), minute(self.end))
121 }
122}
123
124#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
125#[serde(default)]
126pub struct CalendarPrefs {
127 pub default_view: DefaultView,
128 pub last_span: CalendarSpan,
129 /// `None` follows the regional format.
130 pub first_day: Option<Weekday>,
131 pub time_scale: TimeScale,
132 pub weekend_work_week: WeekendWorkWeek,
133 pub pane_hidden: bool,
134 pub collapsed_groups: Vec<String>,
135 pub work_hours: WorkHours,
136 /// Mailbox language (`en-CH`), cached; Outlook takes the default week start from it.
137 pub mailbox_locale: Option<String>,
138}
139
140impl CalendarPrefs {
141 /// The span the calendar opens in.
142 pub fn initial_span(&self) -> CalendarSpan {
143 self.default_view.span().unwrap_or(self.last_span)
144 }
145
146 pub fn first_day_or(&self, regional: Weekday) -> Weekday {
147 self.first_day.unwrap_or(regional)
148 }
149
150 /// Week layout for the grid; `regional` is the regional format's first day.
151 pub fn layout(&self, regional: Weekday) -> WeekLayout {
152 WeekLayout {
153 first_day: self.first_day_or(regional),
154 work_days: self.work_hours.days.clone(),
155 weekend: self.weekend_work_week,
156 }
157 }
158
159 pub fn group_collapsed(&self, group: &str) -> bool {
160 self.collapsed_groups.iter().any(|id| id == group)
161 }
162
163 pub fn toggle_group(&mut self, group: &str) {
164 if self.group_collapsed(group) {
165 self.collapsed_groups.retain(|id| id != group);
166 } else {
167 self.collapsed_groups.push(group.to_owned());
168 }
169 }
170
171 pub fn from_json(text: &str) -> Self {
172 serde_json::from_str(text).unwrap_or_default()
173 }
174
175 pub fn to_json(&self) -> String {
176 serde_json::to_string(self).unwrap_or_default()
177 }
178}
179
180pub fn load_calendar_prefs(store: &Store) -> CalendarPrefs {
181 store
182 .meta(CALENDAR_PREFS_KEY)
183 .ok()
184 .flatten()
185 .map(|json| CalendarPrefs::from_json(&json))
186 .unwrap_or_default()
187}
188
189pub fn save_calendar_prefs(store: &Store, prefs: &CalendarPrefs) {
190 if let Err(error) = store.set_meta(CALENDAR_PREFS_KEY, &prefs.to_json()) {
191 log::warn!("calendar prefs not saved: {error}");
192 }
193}
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198
199 #[test]
200 fn defaults_keep_todays_behaviour() {
201 let prefs = CalendarPrefs::default();
202 assert_eq!(prefs.default_view, DefaultView::LastUsed);
203 assert_eq!(prefs.initial_span(), CalendarSpan::WorkWeek);
204 assert_eq!(prefs.time_scale.minutes(), 30);
205 assert_eq!(prefs.weekend_work_week, WeekendWorkWeek::NextWeek);
206 assert_eq!(prefs.work_hours.minute_range(), (8 * 60, 17 * 60));
207 assert!(!prefs.work_hours.is_work_day(Weekday::Sat));
208 }
209
210 #[test]
211 fn a_fixed_default_view_wins_over_the_last_span() {
212 let prefs = CalendarPrefs {
213 default_view: DefaultView::Week,
214 last_span: CalendarSpan::Month,
215 ..CalendarPrefs::default()
216 };
217 assert_eq!(prefs.initial_span(), CalendarSpan::Week);
218 let last_used = CalendarPrefs {
219 default_view: DefaultView::LastUsed,
220 ..prefs
221 };
222 assert_eq!(last_used.initial_span(), CalendarSpan::Month);
223 }
224
225 #[test]
226 fn prefs_round_trip_through_the_store() {
227 let store = Store::open_in_memory().unwrap();
228 let mut prefs = CalendarPrefs {
229 default_view: DefaultView::Month,
230 first_day: Some(Weekday::Sun),
231 time_scale: TimeScale::Min15,
232 pane_hidden: true,
233 ..CalendarPrefs::default()
234 };
235 prefs.toggle_group("g1");
236 prefs.work_hours.days = vec![Weekday::Mon, Weekday::Tue, Weekday::Thu];
237 save_calendar_prefs(&store, &prefs);
238 assert_eq!(load_calendar_prefs(&store), prefs);
239 }
240
241 #[test]
242 fn missing_fields_take_defaults_and_broken_json_resets() {
243 let partial = CalendarPrefs::from_json(r#"{"default_view":"month"}"#);
244 assert_eq!(partial.default_view, DefaultView::Month);
245 assert_eq!(partial.time_scale, TimeScale::Min30);
246 assert_eq!(
247 CalendarPrefs::from_json("{not json"),
248 CalendarPrefs::default()
249 );
250 assert_eq!(
251 CalendarPrefs::from_json(r#"{"time_scale":"min7"}"#),
252 CalendarPrefs::default()
253 );
254 }
255
256 #[test]
257 fn a_group_collapses_and_expands() {
258 let mut prefs = CalendarPrefs::default();
259 prefs.toggle_group(OUTLOOK_GROUP);
260 assert!(prefs.group_collapsed(OUTLOOK_GROUP));
261 prefs.toggle_group(OUTLOOK_GROUP);
262 assert!(!prefs.group_collapsed(OUTLOOK_GROUP));
263 }
264}