//! Utilities to handle date and relative date selection use crate::{date::date_parse::parse_simple_date, error_handling::IdleError}; use chrono::{Datelike, Duration, Local, Month, Months, NaiveDate, Weekday}; use serde::{Deserialize, Serialize}; use super::{ date_parse::{DateObject, DatePoint}, parse_str_into_date, }; /// 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 /// /// # Arguments /// /// * `day`: The desired weekday. /// * `context`: An optional date to use as a reference for calculating the relative day. /// If not provided, the current date plus one week is used. /// /// # Returns /// /// A [NaiveDate] representing the calculated date based on the given weekday and context. /// /// # Example /// /// ```rust /// # use chrono::{Weekday, Local}; /// # use idlefox::date::date_tools::relative_day_to_date; /// let today = Local::now().date_naive(); /// // Get the date for next Monday relative to today /// let monday = relative_day_to_date(Weekday::Mon, Some(today)); /// ``` pub fn relative_day_to_date(weekday: Weekday, context: Option) -> NaiveDate { let context = context.unwrap_or(Local::now().date_naive()) + Duration::weeks(1); let offset = context.weekday() as i64 - weekday as i64; context - Duration::days(offset) } /// The relative_date_to_date function finds the date corresponding to a loosely defined implicit partial date. /// /// The date returned will be the next valid date after the context. /// /// ### Arguments /// /// • date: The partial date to convert. /// • context: An optional context date. If no context is given, the date will be inferred as the next valid date from now. /// /// ### Returns /// /// A [chrono::NaiveDate] representing the date corresponding to the given partial date in the context of the provided date. /// /// ### Example /// ``` /// # use chrono::NaiveDate; /// # use idlefox::date::date_tools::relative_date_to_date; /// // In this context we are trying to get the dates relative to the 14th of the month /// let context_date = NaiveDate::from_ymd_opt(2023, 2, 14).unwrap(); /// // Get the next 16, relative to our context /// let date = relative_date_to_date(16, None, Some(context_date)).unwrap(); /// assert_eq!(date, NaiveDate::from_ymd_opt(2023, 2, 16).unwrap()); // The next 16th in in february /// // Get the next 1st, relative to our context /// let date = relative_date_to_date(1, None, Some(context_date)).unwrap(); /// assert_eq!(date, NaiveDate::from_ymd_opt(2023, 3, 1).unwrap()); // The next 1st in in march, the next month /// ``` pub fn relative_date_to_date( day: u32, month: Option, context: Option, ) -> Result { let context = context.unwrap_or(Local::now().date_naive()); let mut new_dat = NaiveDate::from_ymd_opt( context.year_ce().1 as i32, match month { Some(m) => m.number_from_month(), None => context.month(), }, day, ) .ok_or(IdleError::InvalidDate(day, month))?; if month.is_none() && day < context.day() { new_dat = new_dat.checked_add_months(Months::new(1)).unwrap(); } if new_dat.month() < context.month() { new_dat = new_dat.checked_add_months(Months::new(12)).unwrap(); } Ok(new_dat) } impl DatePoint { /// Converts a DatePoint to a NaiveDate, optionally relative to a given context date. /// /// The conversion depends on the specific type of [DatePoint]: /// - For `DatePoint::Date { day, month }`, it calculates the next valid date after the provided or current context. /// - For `DatePoint::Weekday(weekday)`, it finds the next occurrence of that weekday relative to the context. /// /// # Arguments /// /// * `self`: The [DatePoint] to convert. /// * `context`: An optional reference date. If not provided, the function uses the current date as a default. /// /// # Returns /// /// A Result containing a [NaiveDate] if successful, or an [IdleError] if the date could not be calculated due to invalid input. /// /// # Examples /// /// ``` ///use chrono::{Local, Month}; ///use idlefox::date::date_parse::{DateObject, DatePoint}; ///let today = Local::now().date_naive(); ///let date_point = DatePoint::Date { /// day: 14, /// month: Some(Month::February), ///}; ///let next_valid_date_object = DateObject::Single(date_point); ///let naive_date = next_valid_date_object /// .to_naive_date_object(Some(today)) /// .unwrap(); /// ``` fn to_naive_date(self, context: Option) -> Result { match self { DatePoint::Date { day, month } => relative_date_to_date(day, month, context), DatePoint::Weekday(weekday) => Ok(relative_day_to_date(weekday, context)), } } } /// An enum representing either a single [NaiveDate] or a date range between two [NaiveDate]. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] // #[cfg_attr(test, derive(PartialEq))] pub enum NaiveDateObject { /// A range between two dates, inclusive at both ends. Range { /// Start of the range start: NaiveDate, /// End of the range stop: NaiveDate, }, /// A single [NaiveDate] object. Single(NaiveDate), } /// A collection of [NaiveDateObject]s, allowing for sequential and random access to their start dates. /// /// This struct provides an abstraction over a list of date objects, enabling both sequential iteration /// over the dates in order or direct access to any date by its index. The structure is designed to handle /// different sources of date information, allowing for flexible data manipulation based on the provided dates. #[derive(Debug, Default, Serialize, Deserialize)] #[cfg_attr(test, derive(PartialEq, Clone))] pub struct NaiveDateList { /// The inner vector inner: Vec, /// The leftover, unparsed string unparsed: Option, } impl DateObject { /// Converts this [DateObject] to a corresponding [NaiveDateObject], using the provided context for relative date calculations. /// /// # Examples /// /// ``` /// # use idlefox::date::date_parse::{DateObject, DatePoint}; /// # use chrono::{Local, Month}; /// let today = Local::now().date_naive(); /// let date_point = DatePoint::Date { /// day: 14, /// month: Some(Month::March), /// }; // February 14 /// let next_valid_date_object = DateObject::Single(date_point); /// let naive_date = next_valid_date_object /// .to_naive_date_object(Some(today)) /// .unwrap(); /// ``` pub fn to_naive_date_object( &self, context: Option, ) -> Result { match self { DateObject::Range(date_range) => { // This shenenigan is important otherwise very long ranges can overlap and become negative making no sense let start = date_range.start.to_naive_date(context)?; Ok(NaiveDateObject::Range { start, stop: date_range.stop.to_naive_date(Some(start))?, }) } DateObject::Single(date_point) => { Ok(NaiveDateObject::Single(date_point.to_naive_date(context)?)) } } } } impl NaiveDateList { /// Creates a new [NaiveDateList] from an existing vector of [NaiveDateObject]s. pub fn new(inner: Vec, unparsed: Option<&str>) -> Self { Self { inner, unparsed: unparsed.map(|v| v.to_string()), } } /// Returns the number of dates in this [NaiveDateList]. pub fn len(&self) -> usize { self.inner.len() } /// Checks if this [NaiveDateList] is empty. pub fn is_empty(&self) -> bool { self.inner.is_empty() } /// Retrieves a reference to the [NaiveDateObject] at the specified index. pub fn get(&self, index: usize) -> Option<&NaiveDateObject> { self.inner.get(index) } /// Creates a new [NaiveDateList] from an existing vector of [DateObject]s and a context date. /// /// The `context` is used to resolve any relative dates in the `inner` list. /// /// # Examples /// /// ``` /// # use chrono::Local; /// # use idlefox::date::{ /// # date_parse::{DateObject, DatePoint}, /// # date_tools::NaiveDateList, /// # }; /// let today = Local::now().date_naive(); /// let date_point = DatePoint::Date { /// day: 14, /// month: Some(chrono::Month::January), /// }; /// let next_valid_date_object = DateObject::Single(date_point); /// let list = NaiveDateList::from_context(vec![next_valid_date_object], Some(today), None); /// assert!(list.is_ok()); /// ``` pub fn from_context( inner: Vec, context: Option, unparsed: Option<&str>, ) -> Result { let mut new = Vec::new(); for elem in inner { new.push(elem.to_naive_date_object(context)?); } Ok(Self { inner: new, unparsed: unparsed.map(|v| v.to_owned()), }) } } // // TODO: If needed, make an iterator over all dates that this list of date encompasses // impl IntoIterator for NaiveDateList { // type Item = NaiveDateObject; // type IntoIter = std::vec::IntoIter; // fn into_iter(self) -> Self::IntoIter { // self.inner.into_iter() // } // } /// This function parses a given input string representing date information and returns a `NaiveDateList`, /// which is a collection of sequential or random accessible date objects. If there are any unparsed parts /// left after processing the input, they can be retrieved using the `unparsed` method on the returned `Result`. /// /// The function uses the context provided to resolve any relative dates within the input string. /// /// # Arguments /// /// * `input` - A string slice containing the date information to be parsed. This string may include various date formats, /// single or range of dates, and possibly unparsed text. /// * `context` - An optional NaiveDate that provides a context for resolving relative dates within the input. If no context /// is provided, the function will attempt to use today's date as a fallback. /// /// # Returns /// /// A Result containing a `NaiveDateList` on success or an `IdleError` if parsing fails. The `Result` also includes any /// unparsed text that was left over after processing the input string. /// /// # Examples /// /// ``` /// # use idlefox::date::parse_date_list; /// # use chrono::NaiveDate; /// let input = "Oct 5, Nov 15 - 18, sat, mon , tue-fry and some other text"; /// let context = NaiveDate::from_ymd_opt(2023, 10, 1); /// let result = parse_date_list(input, context); /// assert!(result.is_ok()); /// match result { /// Ok(date_list) => println!("Parsed dates: {}", date_list.len()), /// Err(e) => eprintln!("Error parsing dates: {}", e), /// } /// ``` pub fn parse_date_list( input: &str, context: Option, ) -> Result { let (leftover, objects) = match parse_str_into_date(input)? { ("", objects) => (None, objects), (leftover, objects) => (Some(leftover), objects), }; NaiveDateList::from_context(objects, context, leftover) } /// This function parses a given input string representing a single date and returns a `NaiveDate`. /// The function uses the context provided to resolve any relative dates within the input string. /// /// # Arguments /// * `input` - A string slice containing the date information to be parsed. This string may include various date formats, /// and possibly unparsed text. /// * `context` - An optional NaiveDate that provides a context for resolving relative dates within the input. If no context /// is provided, the function will attempt to use today's date as a fallback. /// /// # Returns /// A Result containing a `NaiveDate` on success or an `IdleError` if parsing fails. pub fn parse_single_date(input: &str, context: Option) -> Result { // As we simply ignore the leftover, we can directly call the to_naive_date method parse_simple_date(input)?.1.to_naive_date(context) } #[cfg(test)] pub(crate) mod tests { use super::*; use crate::date::date_parse::DateRange; #[test] fn test_relative_days() { 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() ); } #[test] fn test_relative_date() { let context = Some(NaiveDate::from_ymd_opt(2024, 11, 10).unwrap()); assert_eq!( relative_date_to_date(16, Some(Month::December), context).unwrap(), NaiveDate::from_ymd_opt(2024, 12, 16).unwrap() ); assert_eq!( relative_date_to_date(7, Some(Month::January), context).unwrap(), NaiveDate::from_ymd_opt(2025, 1, 7).unwrap() ); assert_eq!( relative_date_to_date(17, None, context).unwrap(), NaiveDate::from_ymd_opt(2024, 11, 17).unwrap() ); assert_eq!( relative_date_to_date(5, None, context).unwrap(), NaiveDate::from_ymd_opt(2024, 12, 5).unwrap() ); assert!(relative_date_to_date(52, None, None).is_err()); // TODO: Do we consider this to be normal behaviour ? assert!(relative_date_to_date( 31, Some(Month::February), NaiveDate::from_ymd_opt(2020, 1, 30) ) .is_err()); assert_eq!( relative_date_to_date( 12, Some(Month::February), NaiveDate::from_ymd_opt(2020, 1, 30) ) .unwrap(), NaiveDate::from_ymd_opt(2020, 2, 12).unwrap() ); } #[test] fn test_impl_date() { let context = Some(NaiveDate::from_ymd_opt(2024, 11, 10).unwrap()); assert_eq!( DatePoint::Weekday(Weekday::Mon) .to_naive_date(context) .unwrap(), NaiveDate::from_ymd_opt(2024, 11, 11).unwrap() ); assert_eq!( DatePoint::Date { day: 10, month: Some(Month::January) } .to_naive_date(context) .unwrap(), NaiveDate::from_ymd_opt(2025, 1, 10).unwrap() ); } #[test] fn test_impl_dateobj() { let context = Some(NaiveDate::from_ymd_opt(2024, 11, 10).unwrap()); let date_a = DatePoint::Date { day: 10, month: Some(Month::January), }; let date_b = DatePoint::Date { day: 21, month: Some(Month::December), }; assert_eq!( DateObject::Single(date_a) .to_naive_date_object(context) .unwrap(), NaiveDateObject::Single(NaiveDate::from_ymd_opt(2025, 1, 10).unwrap()) ); let date_obj = DateObject::Range(DateRange { start: date_a, stop: date_b, }) .to_naive_date_object(context) .unwrap(); assert_eq!( date_obj, NaiveDateObject::Range { start: NaiveDate::from_ymd_opt(2025, 1, 10).unwrap(), stop: NaiveDate::from_ymd_opt(2025, 12, 21).unwrap() } ); let vec_obj = NaiveDateList::new(vec![date_obj.clone()], None); assert_eq!(vec_obj.len(), 1); assert!(!vec_obj.is_empty()); assert_eq!(vec_obj.get(0).unwrap(), &date_obj); assert!(!NaiveDateList::from_context( vec![DateObject::Single(date_a), DateObject::Single(date_a)], context, None, ) .unwrap() .is_empty()); assert!(NaiveDateList::from_context( vec![ DateObject::Single(DatePoint::Date { day: 32, month: None }), DateObject::Single(date_a) ], context, None, ) .is_err()); } #[test] fn test_date_list() { use chrono::NaiveDate; let input = "Oct 5, Nov 15 - 18, sat, mon , tue-fri and some other text"; let context = NaiveDate::from_ymd_opt(2023, 10, 1); let list = parse_date_list(input, context).unwrap(); assert_eq!(list.unparsed, Some("and some other text".to_string())); assert_eq!(list.len(), 5); let input = "Oct 5, Nov 15"; let list = parse_date_list(input, None).unwrap(); assert_eq!(list.unparsed, None); assert_eq!(list.len(), 2); } #[test] fn test_serialisation() { let input = "Oct 5, Nov 15 - 18, sat, mon , tue-fri and some other text"; let context = NaiveDate::from_ymd_opt(2023, 10, 1); let list = parse_date_list(input, context).unwrap(); let s = ron::to_string(&list).unwrap(); // Simple roundtrip assertion assert_eq!(list, ron::from_str(&s).unwrap()); } }