BlueGit

ict rusty-teams

Files

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

calendar_prefs.rs

calendar_prefs.rs 8.3 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 pub time_scale: TimeScale,
130 pub weekend_work_week: WeekendWorkWeek,
131 pub pane_hidden: bool,
132 pub collapsed_groups: Vec<String>,
133 pub work_hours: WorkHours,
134 /// Mailbox language (`en-CH`), cached; Outlook takes the default week start from it.
135 pub mailbox_locale: Option<String>,
136}
137
138impl CalendarPrefs {
139 /// The span the calendar opens in.
140 pub fn initial_span(&self) -> CalendarSpan {
141 self.default_view.span().unwrap_or(self.last_span)
142 }
143
144 /// Week layout for the grid; the first day comes from the regional format.
145 pub fn layout(&self, first_day: Weekday) -> WeekLayout {
146 WeekLayout {
147 first_day,
148 work_days: self.work_hours.days.clone(),
149 weekend: self.weekend_work_week,
150 }
151 }
152
153 pub fn group_collapsed(&self, group: &str) -> bool {
154 self.collapsed_groups.iter().any(|id| id == group)
155 }
156
157 pub fn toggle_group(&mut self, group: &str) {
158 if self.group_collapsed(group) {
159 self.collapsed_groups.retain(|id| id != group);
160 } else {
161 self.collapsed_groups.push(group.to_owned());
162 }
163 }
164
165 pub fn from_json(text: &str) -> Self {
166 serde_json::from_str(text).unwrap_or_default()
167 }
168
169 /// The first day of week this record kept before it moved to the regional format.
170 pub fn legacy_first_day(json: &str) -> Option<Weekday> {
171 let value: serde_json::Value = serde_json::from_str(json).ok()?;
172 serde_json::from_value(value.get("first_day")?.clone()).ok()
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 time_scale: TimeScale::Min15,
231 pane_hidden: true,
232 ..CalendarPrefs::default()
233 };
234 prefs.toggle_group("g1");
235 prefs.work_hours.days = vec![Weekday::Mon, Weekday::Tue, Weekday::Thu];
236 save_calendar_prefs(&store, &prefs);
237 assert_eq!(load_calendar_prefs(&store), prefs);
238 }
239
240 #[test]
241 fn the_old_first_day_is_read_once_it_left_the_struct() {
242 let json = r#"{"default_view":"month","first_day":"Sun"}"#;
243 assert_eq!(CalendarPrefs::legacy_first_day(json), Some(Weekday::Sun));
244 assert_eq!(
245 CalendarPrefs::legacy_first_day(r#"{"first_day":null}"#),
246 None
247 );
248 assert_eq!(
249 CalendarPrefs::from_json(json).default_view,
250 DefaultView::Month
251 );
252 }
253
254 #[test]
255 fn missing_fields_take_defaults_and_broken_json_resets() {
256 let partial = CalendarPrefs::from_json(r#"{"default_view":"month"}"#);
257 assert_eq!(partial.default_view, DefaultView::Month);
258 assert_eq!(partial.time_scale, TimeScale::Min30);
259 assert_eq!(
260 CalendarPrefs::from_json("{not json"),
261 CalendarPrefs::default()
262 );
263 assert_eq!(
264 CalendarPrefs::from_json(r#"{"time_scale":"min7"}"#),
265 CalendarPrefs::default()
266 );
267 }
268
269 #[test]
270 fn a_group_collapses_and_expands() {
271 let mut prefs = CalendarPrefs::default();
272 prefs.toggle_group(OUTLOOK_GROUP);
273 assert!(prefs.group_collapsed(OUTLOOK_GROUP));
274 prefs.toggle_group(OUTLOOK_GROUP);
275 assert!(!prefs.group_collapsed(OUTLOOK_GROUP));
276 }
277}