Skip to main content

aidaemon_memory/
dates.rs

1//! Dates the people store keeps (birthdays, important dates). They are
2//! machine dates the model fills: ISO 8601 `YYYY-MM-DD`, or `--MM-DD` when
3//! the year is unknown. Nothing else is read: a month name or a
4//! `05/03`-style date is locale prose (May 3 or March 5?), and a wrong
5//! reading sends a reminder on the wrong day.
6
7use chrono::{Datelike, NaiveDate};
8
9/// The categories of person facts whose value is such a date.
10pub const DATE_FACT_CATEGORIES: &[&str] = &["birthday", "important_date"];
11
12/// Whether a person-fact `category` holds a date.
13pub fn is_date_fact_category(category: &str) -> bool {
14    DATE_FACT_CATEGORIES.contains(&category.trim().to_ascii_lowercase().as_str())
15}
16
17/// The `(month, day)` of an ISO date `YYYY-MM-DD` or a yearless `--MM-DD`;
18/// `None` for anything else.
19pub fn parse_month_day(value: &str) -> Option<(u32, u32)> {
20    let value = value.trim();
21    if let Some(month_day) = value.strip_prefix("--") {
22        // Validate against a leap year so --02-29 is a real yearless date.
23        let date = NaiveDate::parse_from_str(&format!("2000-{month_day}"), "%Y-%m-%d").ok()?;
24        return (month_day.len() == 5).then_some((date.month(), date.day()));
25    }
26    let date = NaiveDate::parse_from_str(value, "%Y-%m-%d").ok()?;
27    (value.len() == 10).then_some((date.month(), date.day()))
28}
29
30/// Why a date argument was refused, for the model to correct.
31pub fn date_argument_error(value: &str) -> Option<String> {
32    parse_month_day(value).is_none().then(|| {
33        format!(
34            "'{}' is not an ISO date. Give YYYY-MM-DD, or --MM-DD when the year is unknown \
35             (May 3 is --05-03); ask the owner when the day and month are ambiguous.",
36            value.trim()
37        )
38    })
39}
40
41/// Days from `today` until the date's next anniversary (0 today), or `None`
42/// when `value` is not an ISO date or the day does not occur this year
43/// (Feb 29 outside a leap year).
44pub fn days_until_anniversary(value: &str, today: NaiveDate) -> Option<i64> {
45    let (month, day) = parse_month_day(value)?;
46    let this_year = NaiveDate::from_ymd_opt(today.year(), month, day)?;
47    let diff = (this_year - today).num_days();
48    Some(if diff < 0 { diff + 365 } else { diff })
49}
50
51/// A value stored before dates were ISO only, rewritten as ISO the way
52/// the old reader understood it: `YYYY-M-D`, numeric month first (`3/15`,
53/// `03-15`: March 15, as the old code read them), or an English month name
54/// and a day (`March 15`, `march 15,`). `None` when `value` is already ISO
55/// or the old reader could not read it either; those stay as written.
56pub fn legacy_date_to_iso(value: &str) -> Option<String> {
57    let value = value.trim();
58    if value.is_empty() || parse_month_day(value).is_some() {
59        return None;
60    }
61    if let Ok(date) = NaiveDate::parse_from_str(value, "%Y-%m-%d") {
62        return Some(date.format("%Y-%m-%d").to_string());
63    }
64    // Month-day forms, month first as the old reader meant them, checked
65    // against the leap year 2000 so 02-29 stays a real date. (The old
66    // reader's own format left out the year and so never matched; its
67    // intent, month first, is the reading kept here.)
68    for format in ["%Y-%m-%d", "%Y-%m/%d"] {
69        if let Ok(date) = NaiveDate::parse_from_str(&format!("2000-{value}"), format) {
70            return Some(format!("--{:02}-{:02}", date.month(), date.day()));
71        }
72    }
73    const MONTHS: [&str; 12] = [
74        "january",
75        "february",
76        "march",
77        "april",
78        "may",
79        "june",
80        "july",
81        "august",
82        "september",
83        "october",
84        "november",
85        "december",
86    ];
87    let lower = value.to_lowercase();
88    for (index, name) in MONTHS.iter().enumerate() {
89        if let Some(rest) = lower.strip_prefix(name) {
90            let rest = rest.trim().trim_start_matches([',', ' ']);
91            let month = index as u32 + 1;
92            let day = rest.parse::<u32>().ok()?;
93            NaiveDate::from_ymd_opt(2000, month, day)?;
94            return Some(format!("--{month:02}-{day:02}"));
95        }
96    }
97    None
98}
99
100#[cfg(test)]
101mod tests {
102    use super::*;
103
104    fn day(y: i32, m: u32, d: u32) -> NaiveDate {
105        NaiveDate::from_ymd_opt(y, m, d).unwrap()
106    }
107
108    #[test]
109    fn only_iso_dates_are_read() {
110        assert_eq!(parse_month_day("2019-04-02"), Some((4, 2)));
111        assert_eq!(parse_month_day("--05-03"), Some((5, 3)));
112        assert_eq!(parse_month_day("--02-29"), Some((2, 29)));
113        for ambiguous in [
114            "05/03", "5/3", "05-03", "March 15", "15 March", "2019-4-2", "--13-01",
115        ] {
116            assert_eq!(parse_month_day(ambiguous), None, "{ambiguous}");
117            assert!(date_argument_error(ambiguous).is_some(), "{ambiguous}");
118        }
119        assert!(date_argument_error("--05-03").is_none());
120    }
121
122    #[test]
123    fn legacy_dates_convert_as_the_old_reader_read_them() {
124        for (legacy, iso) in [
125            ("March 15", "--03-15"),
126            ("march 5", "--03-05"),
127            ("December, 1", "--12-01"),
128            ("03-15", "--03-15"),
129            ("3/15", "--03-15"),
130            // Month first, as the old reader read it: May 3, not March 5.
131            ("05/03", "--05-03"),
132            ("02-29", "--02-29"),
133            ("2019-4-2", "2019-04-02"),
134        ] {
135            assert_eq!(legacy_date_to_iso(legacy).as_deref(), Some(iso), "{legacy}");
136            assert!(parse_month_day(iso).is_some(), "{iso}");
137        }
138        for untouched in [
139            "--03-15",
140            "2019-04-02",
141            "15 March",
142            "March 15th",
143            "13/01",
144            "February 30",
145            "next spring",
146            "",
147        ] {
148            assert_eq!(legacy_date_to_iso(untouched), None, "{untouched}");
149        }
150    }
151
152    #[test]
153    fn days_count_to_the_next_anniversary() {
154        let today = day(2026, 5, 1);
155        assert_eq!(days_until_anniversary("--05-03", today), Some(2));
156        assert_eq!(days_until_anniversary("2019-05-01", today), Some(0));
157        assert_eq!(days_until_anniversary("--04-30", today), Some(364));
158        // The 31st of a month does not break a later shorter month.
159        assert_eq!(
160            days_until_anniversary("--06-30", day(2026, 5, 31)),
161            Some(30)
162        );
163        assert_eq!(days_until_anniversary("05/03", today), None);
164    }
165}