//! Utilities to handle date and relative date selection use crate::error_handling::IdleError; use chrono::{Datelike, Duration, Local, Month, Months, NaiveDate, Weekday}; /// Returns the date corresponding to the implicit Weekday /// /// Aka the next day implied by the day given /// If no context is given, the date is the same day next week from the current day pub(crate) fn relative_day_to_date(day: Weekday, context: Option) -> NaiveDate { let context = context.unwrap_or(Local::now().date_naive()) + Duration::weeks(1); let offset = context.weekday() as i64 - day as i64; context - Duration::days(offset) } /// A placeholder for a partial date, as a date with no year associated #[derive(Debug)] pub(crate) struct PartialDate { /// The month implied in the date pub(crate) month: Option, /// The day of the month implied in the date pub(crate) day: u32, } /// Finds the date corresponding to the loosely defined implicit partial date /// /// If no context is given, the date will be inferred as the next valid date from now pub(crate) fn relative_date_to_date( date: PartialDate, context: Option, ) -> Result { let context = context.unwrap_or(Local::now().date_naive()); // Change the base date depending on the context match match date.month { Some(m) if m.number_from_month() >= context.month() => context .with_month(m.number_from_month()) .ok_or(IdleError::DateParsing), Some(_m) => context .checked_add_months(Months::new(12)) .ok_or(IdleError::DateParsing), None if date.day >= context.day() => Ok(context), None => context .checked_add_months(Months::new(1)) .ok_or(IdleError::DateParsing), } { Ok(new_base) => new_base .with_day(date.day) .ok_or(IdleError::DateParsing(date)), Err(_) => Err(IdleError::DateParsing(date)), } } #[cfg(test)] pub(crate) mod tests { use super::*; #[test] fn test_relative_dates() { let date = NaiveDate::from_ymd_opt(2024, 10, 30); let date_next_mon = NaiveDate::from_ymd_opt(2024, 11, 4); let date_next_tue = NaiveDate::from_ymd_opt(2024, 11, 7); let date2 = NaiveDate::from_ymd_opt(2024, 12, 30); let date2_next_sat = NaiveDate::from_ymd_opt(2025, 1, 11); let date3 = NaiveDate::from_ymd_opt(2025, 1, 16); let date3_next_sat = NaiveDate::from_ymd_opt(2025, 1, 26); assert_eq!( relative_day_to_date(Weekday::Mon, date), date_next_mon.unwrap() ); assert_eq!( relative_day_to_date(Weekday::Thu, date), date_next_tue.unwrap() ); assert_eq!( relative_day_to_date(Weekday::Sat, date2), date2_next_sat.unwrap() ); assert_eq!( relative_day_to_date(Weekday::Sun, date3), date3_next_sat.unwrap() ); } }