1use chrono::{Datelike, NaiveDate, TimeZone, Weekday};
17use orbital_base_components::{DatetimeTimezone, OrbitalDateTime, ToUnixSeconds};
18
19use super::visible_range::visible_range;
20use crate::{DateTimeRange, PlannedEvent, SchedulerFeatures, SchedulerView};
21
22const INSTANCE_SEPARATOR: &str = "::";
23const MAX_INSTANCES: u32 = 500;
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum RecurrenceFreq {
28 Daily,
29 Weekly,
30}
31
32#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct RecurrenceRule {
35 pub freq: RecurrenceFreq,
36 pub interval: u32,
37 pub by_day: Vec<Weekday>,
38 pub count: Option<u32>,
39 pub until: Option<NaiveDate>,
40}
41
42#[derive(Clone, Debug, PartialEq, Eq)]
44pub enum RecurrenceError {
45 Empty,
46 MissingFreq,
47 UnsupportedFreq,
48 InvalidToken,
49 CountAndUntil,
50}
51
52impl std::fmt::Display for RecurrenceError {
53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 match self {
55 Self::Empty => write!(f, "recurrence rule is empty"),
56 Self::MissingFreq => write!(f, "recurrence rule is missing FREQ"),
57 Self::UnsupportedFreq => write!(f, "unsupported recurrence FREQ"),
58 Self::InvalidToken => write!(f, "invalid recurrence rule token"),
59 Self::CountAndUntil => write!(f, "recurrence rule cannot set both COUNT and UNTIL"),
60 }
61 }
62}
63
64impl std::error::Error for RecurrenceError {}
65
66pub fn instance_id(master_id: &str, start: OrbitalDateTime) -> String {
68 format!("{master_id}{INSTANCE_SEPARATOR}{}", start.to_unix_seconds())
69}
70
71pub fn master_event_id(id: &str) -> &str {
73 id.split_once(INSTANCE_SEPARATOR)
74 .map(|(master, _)| master)
75 .unwrap_or(id)
76}
77
78pub fn occurrence_start_from_instance(
80 id: &str,
81 timezone: DatetimeTimezone,
82) -> Option<OrbitalDateTime> {
83 let (_, unix_str) = id.split_once(INSTANCE_SEPARATOR)?;
84 let secs: i64 = unix_str.parse().ok()?;
85 chrono::Utc
86 .timestamp_opt(secs, 0)
87 .single()
88 .map(|instant| OrbitalDateTime::from_instant(instant, timezone))
89}
90
91pub fn parse_recurrence_rule(rule: &str) -> Result<RecurrenceRule, RecurrenceError> {
93 let trimmed = rule.trim();
94 if trimmed.is_empty() {
95 return Err(RecurrenceError::Empty);
96 }
97
98 let mut freq = None;
99 let mut interval = 1_u32;
100 let mut by_day = Vec::new();
101 let mut count = None;
102 let mut until = None;
103
104 for part in trimmed.split(';') {
105 let part = part.trim();
106 if part.is_empty() {
107 continue;
108 }
109 let (key, value) = part.split_once('=').ok_or(RecurrenceError::InvalidToken)?;
110 match key.trim().to_uppercase().as_str() {
111 "FREQ" => {
112 freq = Some(match value.trim().to_uppercase().as_str() {
113 "DAILY" => RecurrenceFreq::Daily,
114 "WEEKLY" => RecurrenceFreq::Weekly,
115 _ => return Err(RecurrenceError::UnsupportedFreq),
116 });
117 }
118 "INTERVAL" => {
119 interval = value
120 .trim()
121 .parse()
122 .map_err(|_| RecurrenceError::InvalidToken)?;
123 if interval == 0 {
124 return Err(RecurrenceError::InvalidToken);
125 }
126 }
127 "BYDAY" => {
128 for token in value.split(',') {
129 by_day.push(parse_weekday(token.trim())?);
130 }
131 }
132 "COUNT" => {
133 count = Some(
134 value
135 .trim()
136 .parse()
137 .map_err(|_| RecurrenceError::InvalidToken)?,
138 );
139 }
140 "UNTIL" => {
141 until = Some(parse_until(value.trim())?);
142 }
143 _ => return Err(RecurrenceError::InvalidToken),
144 }
145 }
146
147 let freq = freq.ok_or(RecurrenceError::MissingFreq)?;
148 if count.is_some() && until.is_some() {
149 return Err(RecurrenceError::CountAndUntil);
150 }
151
152 Ok(RecurrenceRule {
153 freq,
154 interval,
155 by_day,
156 count,
157 until,
158 })
159}
160
161fn parse_weekday(token: &str) -> Result<Weekday, RecurrenceError> {
162 match token.to_uppercase().as_str() {
163 "MO" => Ok(Weekday::Mon),
164 "TU" => Ok(Weekday::Tue),
165 "WE" => Ok(Weekday::Wed),
166 "TH" => Ok(Weekday::Thu),
167 "FR" => Ok(Weekday::Fri),
168 "SA" => Ok(Weekday::Sat),
169 "SU" => Ok(Weekday::Sun),
170 _ => Err(RecurrenceError::InvalidToken),
171 }
172}
173
174fn parse_until(value: &str) -> Result<NaiveDate, RecurrenceError> {
175 if value.len() != 8 {
176 return Err(RecurrenceError::InvalidToken);
177 }
178 let year: i32 = value[0..4]
179 .parse()
180 .map_err(|_| RecurrenceError::InvalidToken)?;
181 let month: u32 = value[4..6]
182 .parse()
183 .map_err(|_| RecurrenceError::InvalidToken)?;
184 let day: u32 = value[6..8]
185 .parse()
186 .map_err(|_| RecurrenceError::InvalidToken)?;
187 NaiveDate::from_ymd_opt(year, month, day).ok_or(RecurrenceError::InvalidToken)
188}
189
190fn event_overlaps_range(event: &PlannedEvent, range: &DateTimeRange) -> bool {
191 event.start <= range.end && event.end >= range.start
192}
193
194fn duration_between(start: OrbitalDateTime, end: OrbitalDateTime) -> chrono::TimeDelta {
195 end.instant() - start.instant()
196}
197
198fn occurrence_end(start: OrbitalDateTime, master: &PlannedEvent) -> OrbitalDateTime {
199 let delta = duration_between(master.start, master.end);
200 OrbitalDateTime::from_instant(start.instant() + delta, master.end.timezone())
201}
202
203fn make_instance(master: &PlannedEvent, occurrence_start: OrbitalDateTime) -> PlannedEvent {
204 PlannedEvent {
205 id: instance_id(&master.id, occurrence_start),
206 title: master.title.clone(),
207 start: occurrence_start,
208 end: occurrence_end(occurrence_start, master),
209 resource_id: master.resource_id.clone(),
210 recurrence_rule: None,
211 color: master.color.clone(),
212 is_draggable: master.is_draggable,
213 is_resizable: master.is_resizable,
214 is_editable: master.is_editable,
215 }
216}
217
218fn within_until(occurrence_start: OrbitalDateTime, until: NaiveDate) -> bool {
219 occurrence_start.wall_date().is_some_and(|d| d <= until)
220}
221
222fn week_start_for(date: NaiveDate) -> NaiveDate {
223 let weekday = date.weekday().num_days_from_sunday();
224 date.checked_sub_days(chrono::Days::new(weekday as u64))
225 .unwrap_or(date)
226}
227
228fn date_for_weekday(week_start: NaiveDate, weekday: Weekday) -> NaiveDate {
229 let offset = weekday.num_days_from_sunday();
230 week_start
231 .checked_add_days(chrono::Days::new(offset as u64))
232 .unwrap_or(week_start)
233}
234
235fn occurrence_at(
236 date: NaiveDate,
237 hour: u32,
238 minute: u32,
239 second: u32,
240 timezone: DatetimeTimezone,
241) -> Option<OrbitalDateTime> {
242 OrbitalDateTime::from_naive_date(date, timezone)?.apply_hms(hour, minute, second)
243}
244
245pub fn expand_recurring_event(master: &PlannedEvent, range: &DateTimeRange) -> Vec<PlannedEvent> {
247 let Some(rule_str) = master.recurrence_rule.as_deref() else {
248 return if event_overlaps_range(master, range) {
249 vec![master.clone()]
250 } else {
251 Vec::new()
252 };
253 };
254
255 let Ok(rule) = parse_recurrence_rule(rule_str) else {
256 return if event_overlaps_range(master, range) {
257 vec![master.clone()]
258 } else {
259 Vec::new()
260 };
261 };
262
263 expand_with_rule(master, &rule, range)
264}
265
266fn expand_with_rule(
267 master: &PlannedEvent,
268 rule: &RecurrenceRule,
269 range: &DateTimeRange,
270) -> Vec<PlannedEvent> {
271 let tz = master.start.timezone();
272 let (hour, minute, second) = master.start.hour_minute_second().unwrap_or((0, 0, 0));
273
274 let mut out = Vec::new();
275 let mut emitted = 0_u32;
276
277 match rule.freq {
278 RecurrenceFreq::Daily => {
279 let mut cursor = master
280 .start
281 .wall_date()
282 .unwrap_or_else(|| master.start.instant().date_naive());
283 while emitted < MAX_INSTANCES {
284 if let Some(count) = rule.count {
285 if emitted >= count {
286 break;
287 }
288 }
289 if let Some(until) = rule.until {
290 if cursor > until {
291 break;
292 }
293 }
294
295 if let Some(occurrence_start) = occurrence_at(cursor, hour, minute, second, tz) {
296 if occurrence_start >= master.start
297 && rule.until.is_none_or(|u| within_until(occurrence_start, u))
298 {
299 let instance = make_instance(master, occurrence_start);
300 if event_overlaps_range(&instance, range) {
301 out.push(instance);
302 }
303 emitted += 1;
304 if rule.count.is_some_and(|c| emitted >= c) {
305 break;
306 }
307 }
308 if occurrence_start > range.end {
309 break;
310 }
311 }
312
313 cursor = match cursor.checked_add_days(chrono::Days::new(rule.interval as u64)) {
314 Some(next) => next,
315 None => break,
316 };
317 }
318 }
319 RecurrenceFreq::Weekly => {
320 let by_day = if rule.by_day.is_empty() {
321 vec![master
322 .start
323 .wall_date()
324 .map(|d| d.weekday())
325 .unwrap_or(Weekday::Mon)]
326 } else {
327 rule.by_day.clone()
328 };
329
330 let master_week = week_start_for(
331 master
332 .start
333 .wall_date()
334 .unwrap_or_else(|| master.start.instant().date_naive()),
335 );
336 let mut week_index = 0_u32;
337
338 'weeks: while emitted < MAX_INSTANCES {
339 if let Some(count) = rule.count {
340 if emitted >= count {
341 break;
342 }
343 }
344
345 let week_start = master_week
346 .checked_add_days(chrono::Days::new((week_index * rule.interval * 7) as u64))
347 .unwrap_or(master_week);
348
349 if let Some(until) = rule.until {
350 if week_start > until {
351 break;
352 }
353 }
354
355 for weekday in &by_day {
356 let date = date_for_weekday(week_start, *weekday);
357 if let Some(until) = rule.until {
358 if date > until {
359 continue;
360 }
361 }
362
363 if let Some(occurrence_start) = occurrence_at(date, hour, minute, second, tz) {
364 if occurrence_start < master.start {
365 continue;
366 }
367 if occurrence_start > range.end {
368 break 'weeks;
369 }
370
371 let instance = make_instance(master, occurrence_start);
372 if event_overlaps_range(&instance, range) {
373 out.push(instance);
374 }
375 emitted += 1;
376 if rule.count.is_some_and(|c| emitted >= c) {
377 break 'weeks;
378 }
379 if emitted >= MAX_INSTANCES {
380 break 'weeks;
381 }
382 }
383 }
384
385 week_index += 1;
386 if week_index > 520 {
387 break;
388 }
389 }
390 }
391 }
392
393 out
394}
395
396pub fn expand_recurring_events(
398 masters: &[PlannedEvent],
399 range: &DateTimeRange,
400 features: SchedulerFeatures,
401) -> Vec<PlannedEvent> {
402 let mut out = Vec::new();
403 for master in masters {
404 if master.recurrence_rule.is_some()
405 && features.contains(SchedulerFeatures::RECURRING_EVENTS)
406 {
407 out.extend(expand_recurring_event(master, range));
408 } else if event_overlaps_range(master, range) {
409 out.push(master.clone());
410 }
411 }
412 out
413}
414
415pub fn resolve_display_events(
417 masters: &[PlannedEvent],
418 visible_date: OrbitalDateTime,
419 view: SchedulerView,
420 display_tz: DatetimeTimezone,
421 features: SchedulerFeatures,
422) -> Vec<PlannedEvent> {
423 let Some(visible) = visible_range(visible_date, view, display_tz) else {
424 return Vec::new();
425 };
426 expand_recurring_events(masters, &visible.query, features)
427}
428
429#[cfg(test)]
430mod tests {
431 use super::*;
432
433 fn master_on(
434 day: NaiveDate,
435 start_hms: (u32, u32, u32),
436 end_hms: (u32, u32, u32),
437 ) -> PlannedEvent {
438 let tz = DatetimeTimezone::Utc;
439 let start = OrbitalDateTime::from_naive_date(day, tz)
440 .unwrap()
441 .apply_hms(start_hms.0, start_hms.1, start_hms.2)
442 .expect("start");
443 let end = OrbitalDateTime::from_naive_date(day, tz)
444 .unwrap()
445 .apply_hms(end_hms.0, end_hms.1, end_hms.2)
446 .expect("end");
447 PlannedEvent::new("weekly-standup", "Standup", start, end)
448 }
449
450 fn week_range() -> DateTimeRange {
451 let tz = DatetimeTimezone::Utc;
452 let anchor =
453 OrbitalDateTime::from_naive_date(NaiveDate::from_ymd_opt(2025, 1, 1).unwrap(), tz)
454 .expect("valid");
455 visible_range(anchor, SchedulerView::Week, tz)
456 .expect("range")
457 .query
458 }
459
460 #[test]
461 fn parse_daily_rule() {
462 let rule = parse_recurrence_rule("FREQ=DAILY;INTERVAL=2;COUNT=3").expect("parsed");
463 assert_eq!(rule.freq, RecurrenceFreq::Daily);
464 assert_eq!(rule.interval, 2);
465 assert_eq!(rule.count, Some(3));
466 }
467
468 #[test]
469 fn parse_weekly_byday() {
470 let rule = parse_recurrence_rule("FREQ=WEEKLY;BYDAY=MO,WE,FR").expect("parsed");
471 assert_eq!(rule.freq, RecurrenceFreq::Weekly);
472 assert_eq!(rule.by_day.len(), 3);
473 }
474
475 #[test]
476 fn reject_unsupported_freq() {
477 assert_eq!(
478 parse_recurrence_rule("FREQ=MONTHLY"),
479 Err(RecurrenceError::UnsupportedFreq)
480 );
481 }
482
483 #[test]
484 fn daily_expansion_respects_count() {
485 let day = NaiveDate::from_ymd_opt(2025, 1, 1).unwrap();
486 let mut master = master_on(day, (9, 0, 0), (9, 30, 0));
487 master.recurrence_rule = Some("FREQ=DAILY;INTERVAL=2;COUNT=3".into());
488 let range = week_range();
489 let extended_end = OrbitalDateTime::from_naive_date(
490 NaiveDate::from_ymd_opt(2025, 1, 10).unwrap(),
491 DatetimeTimezone::Utc,
492 )
493 .expect("valid")
494 .apply_hms(23, 59, 59)
495 .expect("end");
496 let extended = DateTimeRange::new(range.start, extended_end);
497 let instances = expand_recurring_event(&master, &extended);
498 assert_eq!(instances.len(), 3);
499 assert!(instances
500 .iter()
501 .all(|e| e.id.starts_with("weekly-standup::")));
502 }
503
504 #[test]
505 fn weekly_expansion_emits_byday_instances() {
506 let monday = NaiveDate::from_ymd_opt(2024, 12, 30).unwrap();
507 let mut master = master_on(monday, (9, 0, 0), (9, 30, 0));
508 master.recurrence_rule = Some("FREQ=WEEKLY;BYDAY=MO,WE,FR".into());
509 let instances = expand_recurring_event(&master, &week_range());
510 assert!(instances.len() >= 3);
511 }
512
513 #[test]
514 fn instance_id_round_trip() {
515 let day = NaiveDate::from_ymd_opt(2025, 1, 1).unwrap();
516 let master = master_on(day, (9, 0, 0), (9, 30, 0));
517 let id = instance_id(&master.id, master.start);
518 assert_eq!(master_event_id(&id), "weekly-standup");
519 let parsed = occurrence_start_from_instance(&id, master.start.timezone()).expect("parsed");
520 assert_eq!(parsed, master.start);
521 }
522
523 #[test]
524 fn expansion_gated_without_feature_flag() {
525 let day = NaiveDate::from_ymd_opt(2025, 1, 1).unwrap();
526 let mut master = master_on(day, (9, 0, 0), (9, 30, 0));
527 master.recurrence_rule = Some("FREQ=WEEKLY;BYDAY=MO,WE,FR".into());
528 let out =
529 expand_recurring_events(&[master.clone()], &week_range(), SchedulerFeatures::empty());
530 assert_eq!(out.len(), 1);
531 assert_eq!(out[0].id, master.id);
532 }
533
534 #[test]
535 fn until_boundary_excludes_later_dates() {
536 let day = NaiveDate::from_ymd_opt(2025, 1, 1).unwrap();
537 let mut master = master_on(day, (9, 0, 0), (9, 30, 0));
538 master.recurrence_rule = Some("FREQ=DAILY;UNTIL=20250102".into());
539 let range = week_range();
540 let instances = expand_recurring_event(&master, &range);
541 assert!(instances.len() <= 2);
542 }
543}