| 1 | use chrono::{ |
| 2 | DateTime, Datelike, Duration, Local, NaiveDate, NaiveTime, TimeZone, Timelike, Weekday, |
| 3 | }; |
| 4 | |
| 5 | const LATER_TODAY_HOURS: i64 = 3; |
| 6 | const LATER_TODAY_CUTOFF_HOUR: u32 = 20; |
| 7 | const MORNING_HOUR: u32 = 8; |
| 8 | const SLOT_MINUTES: u32 = 30; |
| 9 | const TIME_STEP_MINUTES: i32 = 15; |
| 10 | const MAX_DAYS_AHEAD: i64 = 7; |
| 11 | pub const DAY_CHOICES: usize = 7; |
| 12 | |
| 13 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 14 | pub enum PresetKind { |
| 15 | LaterToday, |
| 16 | TomorrowMorning, |
| 17 | MondayMorning, |
| 18 | } |
| 19 | |
| 20 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 21 | pub struct Preset { |
| 22 | pub kind: PresetKind, |
| 23 | pub label: &'static str, |
| 24 | pub time_label: String, |
| 25 | pub at: DateTime<Local>, |
| 26 | } |
| 27 | |
| 28 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 29 | pub enum ScheduleError { |
| 30 | Past, |
| 31 | TooFar, |
| 32 | } |
| 33 | |
| 34 | impl ScheduleError { |
| 35 | pub fn message(self) -> &'static str { |
| 36 | match self { |
| 37 | ScheduleError::Past => "That time has passed.", |
| 38 | ScheduleError::TooFar => "Teams schedules up to 7 days ahead.", |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | pub fn validate(at: DateTime<Local>, now: DateTime<Local>) -> Result<(), ScheduleError> { |
| 44 | if at <= now { |
| 45 | Err(ScheduleError::Past) |
| 46 | } else if at > now + Duration::days(MAX_DAYS_AHEAD) { |
| 47 | Err(ScheduleError::TooFar) |
| 48 | } else { |
| 49 | Ok(()) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | fn local_at(date: NaiveDate, time: NaiveTime) -> Option<DateTime<Local>> { |
| 54 | Local.from_local_datetime(&date.and_time(time)).earliest() |
| 55 | } |
| 56 | |
| 57 | fn morning(date: NaiveDate) -> Option<DateTime<Local>> { |
| 58 | local_at(date, NaiveTime::from_hms_opt(MORNING_HOUR, 0, 0)?) |
| 59 | } |
| 60 | |
| 61 | fn later_today(now: DateTime<Local>) -> Option<DateTime<Local>> { |
| 62 | let target = now + Duration::hours(LATER_TODAY_HOURS); |
| 63 | let past_slot = !target.minute().is_multiple_of(SLOT_MINUTES) |
| 64 | || target.second() != 0 |
| 65 | || target.nanosecond() != 0; |
| 66 | let minutes_to_slot = if past_slot { |
| 67 | i64::from(SLOT_MINUTES - target.minute() % SLOT_MINUTES) |
| 68 | } else { |
| 69 | 0 |
| 70 | }; |
| 71 | let rounded = (target + Duration::minutes(minutes_to_slot)) |
| 72 | .with_second(0)? |
| 73 | .with_nanosecond(0)?; |
| 74 | let today = rounded.date_naive() == now.date_naive(); |
| 75 | (today && rounded.hour() < LATER_TODAY_CUTOFF_HOUR).then_some(rounded) |
| 76 | } |
| 77 | |
| 78 | fn next_monday(today: NaiveDate) -> NaiveDate { |
| 79 | let days_ahead = 7 - i64::from(today.weekday().num_days_from_monday()); |
| 80 | today + Duration::days(days_ahead) |
| 81 | } |
| 82 | |
| 83 | pub fn presets(now: DateTime<Local>) -> Vec<Preset> { |
| 84 | let today = now.date_naive(); |
| 85 | let tomorrow = today + Duration::days(1); |
| 86 | let mut presets = Vec::new(); |
| 87 | if let Some(at) = later_today(now) { |
| 88 | presets.push(Preset { |
| 89 | kind: PresetKind::LaterToday, |
| 90 | label: "Later today", |
| 91 | time_label: at.format(crate::format::clock_format()).to_string(), |
| 92 | at, |
| 93 | }); |
| 94 | } |
| 95 | let weekend_ahead = matches!(tomorrow.weekday(), Weekday::Sat | Weekday::Sun); |
| 96 | let monday = if tomorrow.weekday() == Weekday::Mon { |
| 97 | None |
| 98 | } else { |
| 99 | morning(next_monday(today)) |
| 100 | }; |
| 101 | let tomorrow_morning = morning(tomorrow).filter(|_| !weekend_ahead); |
| 102 | for (kind, label, at) in [ |
| 103 | ( |
| 104 | PresetKind::TomorrowMorning, |
| 105 | "Tomorrow morning", |
| 106 | tomorrow_morning, |
| 107 | ), |
| 108 | (PresetKind::MondayMorning, "Monday morning", monday), |
| 109 | ] { |
| 110 | if let Some(at) = at.filter(|at| validate(*at, now).is_ok()) { |
| 111 | presets.push(Preset { |
| 112 | kind, |
| 113 | label, |
| 114 | time_label: weekday_clock(at), |
| 115 | at, |
| 116 | }); |
| 117 | } |
| 118 | } |
| 119 | presets |
| 120 | } |
| 121 | |
| 122 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 123 | pub struct DayChoice { |
| 124 | pub date: NaiveDate, |
| 125 | pub label: String, |
| 126 | } |
| 127 | |
| 128 | pub fn day_choices(today: NaiveDate) -> Vec<DayChoice> { |
| 129 | (0..DAY_CHOICES as i64) |
| 130 | .map(|offset| { |
| 131 | let date = today + Duration::days(offset); |
| 132 | DayChoice { |
| 133 | date, |
| 134 | label: date.format("%a %-d %b").to_string(), |
| 135 | } |
| 136 | }) |
| 137 | .collect() |
| 138 | } |
| 139 | |
| 140 | pub fn parse_time(text: &str) -> Option<NaiveTime> { |
| 141 | let (hours, minutes) = text.trim().split_once(':')?; |
| 142 | let well_formed = (1..=2).contains(&hours.len()) |
| 143 | && minutes.len() == 2 |
| 144 | && hours |
| 145 | .chars() |
| 146 | .chain(minutes.chars()) |
| 147 | .all(|digit| digit.is_ascii_digit()); |
| 148 | if !well_formed { |
| 149 | return None; |
| 150 | } |
| 151 | NaiveTime::from_hms_opt(hours.parse().ok()?, minutes.parse().ok()?, 0) |
| 152 | } |
| 153 | |
| 154 | pub fn custom_time(day: NaiveDate, text: &str) -> Option<DateTime<Local>> { |
| 155 | local_at(day, parse_time(text)?) |
| 156 | } |
| 157 | |
| 158 | pub fn default_custom_time(now: DateTime<Local>) -> NaiveTime { |
| 159 | let step = TIME_STEP_MINUTES as u32; |
| 160 | let minutes = now.hour() * 60 + now.minute(); |
| 161 | let next = (minutes / step + 1) * step; |
| 162 | NaiveTime::from_hms_opt(next / 60 % 24, next % 60, 0).unwrap_or_default() |
| 163 | } |
| 164 | |
| 165 | pub fn step_time(time: NaiveTime, steps: i32) -> NaiveTime { |
| 166 | let minutes = (time.hour() * 60 + time.minute()) as i32 + steps * TIME_STEP_MINUTES; |
| 167 | let wrapped = minutes.rem_euclid(24 * 60) as u32; |
| 168 | NaiveTime::from_hms_opt(wrapped / 60, wrapped % 60, 0).unwrap_or_default() |
| 169 | } |
| 170 | |
| 171 | pub fn format_time(time: NaiveTime) -> String { |
| 172 | time.format("%H:%M").to_string() |
| 173 | } |
| 174 | |
| 175 | pub fn describe(at: DateTime<Local>, now: DateTime<Local>) -> String { |
| 176 | let days_ahead = (at.date_naive() - now.date_naive()).num_days(); |
| 177 | match days_ahead { |
| 178 | 0 => format!("today {}", at.format(crate::format::clock_format())), |
| 179 | 1..=6 => weekday_clock(at), |
| 180 | _ => format!( |
| 181 | "{} {}", |
| 182 | at.format("%a %-d %b"), |
| 183 | at.format(crate::format::clock_format()) |
| 184 | ), |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | fn weekday_clock(at: DateTime<Local>) -> String { |
| 189 | format!( |
| 190 | "{} {}", |
| 191 | at.format("%a"), |
| 192 | at.format(crate::format::clock_format()) |
| 193 | ) |
| 194 | } |
| 195 | |
| 196 | #[cfg(test)] |
| 197 | mod tests { |
| 198 | use super::*; |
| 199 | |
| 200 | fn at(day: u32, hour: u32, minute: u32) -> DateTime<Local> { |
| 201 | Local |
| 202 | .with_ymd_and_hms(2026, 10, day, hour, minute, 0) |
| 203 | .unwrap() |
| 204 | } |
| 205 | |
| 206 | fn kinds(now: DateTime<Local>) -> Vec<PresetKind> { |
| 207 | presets(now).iter().map(|preset| preset.kind).collect() |
| 208 | } |
| 209 | |
| 210 | #[test] |
| 211 | fn later_today_is_three_hours_rounded_up_to_the_half_hour() { |
| 212 | let preset = &presets(at(6, 10, 10))[0]; |
| 213 | assert_eq!(preset.kind, PresetKind::LaterToday); |
| 214 | assert_eq!(preset.at, at(6, 13, 30)); |
| 215 | assert_eq!(preset.time_label, "13:30"); |
| 216 | assert_eq!(presets(at(6, 10, 31))[0].at, at(6, 14, 0)); |
| 217 | assert_eq!(presets(at(6, 10, 30))[0].at, at(6, 13, 30)); |
| 218 | } |
| 219 | |
| 220 | #[test] |
| 221 | fn later_today_needs_to_stay_today_and_before_eight_pm() { |
| 222 | assert_eq!(presets(at(6, 16, 20))[0].at, at(6, 19, 30)); |
| 223 | assert_ne!(kinds(at(6, 16, 31))[0], PresetKind::LaterToday); |
| 224 | assert_ne!(kinds(at(6, 22, 0))[0], PresetKind::LaterToday); |
| 225 | } |
| 226 | |
| 227 | #[test] |
| 228 | fn midweek_offers_tomorrow_and_next_monday() { |
| 229 | let found = presets(at(8, 9, 0)); |
| 230 | let labels: Vec<_> = found.iter().map(|preset| preset.label).collect(); |
| 231 | assert_eq!( |
| 232 | labels, |
| 233 | ["Later today", "Tomorrow morning", "Monday morning"] |
| 234 | ); |
| 235 | assert_eq!(found[1].time_label, "Fri 08:00"); |
| 236 | assert_eq!(found[1].at, at(9, 8, 0)); |
| 237 | assert_eq!(found[2].at, at(12, 8, 0)); |
| 238 | assert_eq!(found[2].time_label, "Mon 08:00"); |
| 239 | } |
| 240 | |
| 241 | #[test] |
| 242 | fn friday_and_saturday_replace_tomorrow_with_monday() { |
| 243 | for day in [9, 10] { |
| 244 | let found = presets(at(day, 21, 0)); |
| 245 | assert_eq!(found.len(), 1); |
| 246 | assert_eq!(found[0].kind, PresetKind::MondayMorning); |
| 247 | assert_eq!(found[0].at, at(12, 8, 0)); |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | #[test] |
| 252 | fn sunday_shows_tomorrow_only_because_monday_would_duplicate_it() { |
| 253 | let found = presets(at(11, 21, 0)); |
| 254 | assert_eq!(found.len(), 1); |
| 255 | assert_eq!(found[0].kind, PresetKind::TomorrowMorning); |
| 256 | assert_eq!(found[0].time_label, "Mon 08:00"); |
| 257 | } |
| 258 | |
| 259 | #[test] |
| 260 | fn next_monday_is_hidden_while_it_is_more_than_seven_days_away() { |
| 261 | assert_eq!( |
| 262 | kinds(at(5, 7, 0)), |
| 263 | [PresetKind::LaterToday, PresetKind::TomorrowMorning] |
| 264 | ); |
| 265 | assert_eq!( |
| 266 | kinds(at(5, 21, 0)), |
| 267 | [PresetKind::TomorrowMorning, PresetKind::MondayMorning] |
| 268 | ); |
| 269 | } |
| 270 | |
| 271 | #[test] |
| 272 | fn validation_blocks_the_past_and_more_than_seven_days() { |
| 273 | let now = at(6, 10, 0); |
| 274 | assert_eq!(validate(at(6, 9, 59), now), Err(ScheduleError::Past)); |
| 275 | assert_eq!(validate(now, now), Err(ScheduleError::Past)); |
| 276 | assert_eq!(validate(at(6, 10, 1), now), Ok(())); |
| 277 | assert_eq!(validate(at(13, 10, 0), now), Ok(())); |
| 278 | assert_eq!(validate(at(13, 10, 1), now), Err(ScheduleError::TooFar)); |
| 279 | assert_eq!(ScheduleError::Past.message(), "That time has passed."); |
| 280 | assert_eq!( |
| 281 | ScheduleError::TooFar.message(), |
| 282 | "Teams schedules up to 7 days ahead." |
| 283 | ); |
| 284 | } |
| 285 | |
| 286 | #[test] |
| 287 | fn day_choices_run_from_today_for_seven_days() { |
| 288 | let choices = day_choices(at(9, 12, 0).date_naive()); |
| 289 | assert_eq!(choices.len(), 7); |
| 290 | assert_eq!(choices[0].label, "Fri 9 Oct"); |
| 291 | assert_eq!(choices[6].label, "Thu 15 Oct"); |
| 292 | } |
| 293 | |
| 294 | #[test] |
| 295 | fn typed_times_accept_any_minute_and_reject_garbage() { |
| 296 | let day = at(9, 0, 0).date_naive(); |
| 297 | assert_eq!(custom_time(day, "9:07"), Some(at(9, 9, 7))); |
| 298 | assert_eq!(custom_time(day, " 09:45 "), Some(at(9, 9, 45))); |
| 299 | assert_eq!(custom_time(day, "23:59"), Some(at(9, 23, 59))); |
| 300 | for text in ["", "9", "24:00", "9:60", "9:5", "ab:cd", "9:30pm", "123:00"] { |
| 301 | assert_eq!(parse_time(text), None, "{text}"); |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | #[test] |
| 306 | fn the_default_custom_time_is_the_next_quarter_hour() { |
| 307 | assert_eq!(format_time(default_custom_time(at(9, 10, 0))), "10:15"); |
| 308 | assert_eq!(format_time(default_custom_time(at(9, 10, 14))), "10:15"); |
| 309 | assert_eq!(format_time(default_custom_time(at(9, 23, 50))), "00:00"); |
| 310 | } |
| 311 | |
| 312 | #[test] |
| 313 | fn stepping_moves_by_quarter_hours_and_wraps() { |
| 314 | let time = NaiveTime::from_hms_opt(23, 55, 0).unwrap(); |
| 315 | assert_eq!(format_time(step_time(time, 1)), "00:10"); |
| 316 | assert_eq!(format_time(step_time(time, -2)), "23:25"); |
| 317 | } |
| 318 | |
| 319 | #[test] |
| 320 | fn describing_a_time_names_today_or_the_weekday() { |
| 321 | let now = at(9, 10, 0); |
| 322 | assert_eq!(describe(at(9, 15, 30), now), "today 15:30"); |
| 323 | assert_eq!(describe(at(12, 8, 15), now), "Mon 08:15"); |
| 324 | assert_eq!(describe(at(16, 8, 15), now), "Fri 16 Oct 08:15"); |
| 325 | } |
| 326 | } |