1
//! The one date parser and the date helpers of the clients.
2

            
3
use chrono::{
4
    DateTime, Days, Duration, NaiveDate, NaiveDateTime, NaiveTime, SecondsFormat, TimeZone, Utc,
5
};
6

            
7
const DATE_FORMAT: &str = "%Y-%m-%d";
8
const SECOND_OUTPUT: &str = "%Y-%m-%dT%H:%M:%S";
9
const MINUTE_OUTPUT: &str = "%Y-%m-%dT%H:%M";
10
const DATETIME_FORMATS: [&str; 3] = [SECOND_OUTPUT, MINUTE_OUTPUT, "%Y-%m-%d %H:%M"];
11

            
12
/// [`parse_date_in`] for UTC.
13
291840
pub fn parse_date(s: &str, range_end: bool) -> Result<DateTime<Utc>, String> {
14
291840
    parse_date_in(s, range_end, &Utc)
15
291840
}
16

            
17
/// Parse RFC3339 (full precision), `YYYY-MM-DD`, `YYYY-MM-DDTHH:MM[:SS]` or
18
/// `YYYY-MM-DD HH:MM` (offset-free forms are UTC). A date-only value is the start of
19
/// that day in `zone`, or, when `range_end` is set, the last microsecond (the finest
20
/// instant Postgres stores) before the next local day starts.
21
340044
pub fn parse_date_in<Z: TimeZone>(
22
340044
    s: &str,
23
340044
    range_end: bool,
24
340044
    zone: &Z,
25
340044
) -> Result<DateTime<Utc>, String> {
26
340044
    let s = s.trim();
27
340044
    if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
28
160257
        return Ok(dt.with_timezone(&Utc));
29
179787
    }
30
179787
    if let Some(naive) = DATETIME_FORMATS
31
179787
        .iter()
32
535136
        .find_map(|format| NaiveDateTime::parse_from_str(s, format).ok())
33
    {
34
4417
        return Ok(naive.and_utc());
35
175370
    }
36
175370
    let date = NaiveDate::parse_from_str(s, DATE_FORMAT)
37
8741
        .map_err(|e| format!("invalid date '{s}': {e}"))?;
38
166629
    let bound = if range_end {
39
77825
        date.checked_add_days(Days::new(1))
40
77825
            .and_then(|next| day_start(zone, next))
41
77825
            .and_then(|start| start.checked_sub_signed(Duration::microseconds(1)))
42
    } else {
43
88804
        day_start(zone, date)
44
    };
45
166629
    bound.ok_or_else(|| format!("date '{s}' is out of range"))
46
340044
}
47

            
48
/// A calendar day `YYYY-MM-DD`; a value with a time is refused, never truncated.
49
10944
pub fn parse_day(s: &str) -> Result<NaiveDate, String> {
50
10944
    let s = s.trim();
51
10944
    NaiveDate::parse_from_str(s, DATE_FORMAT)
52
2688
        .map_err(|_| format!("'{s}' is not a day, expected YYYY-MM-DD"))
53
10944
}
54

            
55
/// [`parse_date`] for a transaction post date: a date-only value is noon UTC, so it
56
/// stays on that day for every zone from UTC-12 to UTC+11.
57
97920
pub fn parse_post_date(s: &str) -> Result<DateTime<Utc>, String> {
58
97920
    let s = s.trim();
59
97920
    match NaiveDate::parse_from_str(s, DATE_FORMAT) {
60
35712
        Ok(date) => date
61
35712
            .and_hms_opt(12, 0, 0)
62
35712
            .map(|noon| noon.and_utc())
63
            .ok_or_else(|| format!("date '{s}' is out of range")),
64
62208
        Err(_) => parse_date(s, false),
65
    }
66
97920
}
67

            
68
/// The first instant on or after local midnight of `date`: the earlier of a repeated
69
/// midnight, and the end of the gap when midnight or the whole day is skipped.
70
166629
fn day_start<Z: TimeZone>(zone: &Z, date: NaiveDate) -> Option<DateTime<Utc>> {
71
166629
    let midnight = date.and_time(NaiveTime::MIN);
72
166629
    if let Some(start) = zone.from_local_datetime(&midnight).earliest() {
73
166623
        return Some(start.with_timezone(&Utc));
74
6
    }
75
108
    let reached = |seconds: i64| {
76
108
        DateTime::from_timestamp(seconds, 0)
77
108
            .is_some_and(|at| zone.from_utc_datetime(&at.naive_utc()).naive_local() >= midnight)
78
108
    };
79
    // The largest UTC offset magnitude is 14h; 26h leaves a margin for a skipped day.
80
6
    let around = Duration::hours(26).num_seconds();
81
6
    let mut before = midnight.and_utc().timestamp() - around;
82
6
    let mut after = midnight.and_utc().timestamp() + around;
83
114
    while after - before > 1 {
84
108
        let middle = before + (after - before) / 2;
85
108
        if reached(middle) {
86
51
            after = middle;
87
        } else {
88
57
            before = middle;
89
        }
90
    }
91
6
    DateTime::from_timestamp(after, 0)
92
166629
}
93

            
94
/// The current instant as a full RFC3339 UTC value, the seed of an empty date.
95
#[must_use]
96
127680
pub fn now_instant() -> String {
97
127680
    Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true)
98
127680
}
99

            
100
/// Add `delta_days` to the date in `s`. An RFC3339 value keeps its offset,
101
/// seconds and fractions; `YYYY-MM-DDTHH:MM:SS` keeps its seconds; a date-only value stays
102
/// date-only; other forms step to `YYYY-MM-DDTHH:MM`. `None`
103
/// leaves the caller's buffer untouched (unparseable input or overflow).
104
#[must_use]
105
5376
pub fn step_date(s: &str, delta_days: i64) -> Option<String> {
106
5376
    let s = s.trim();
107
5376
    let delta = Duration::try_days(delta_days)?;
108
5184
    if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
109
576
        let stepped = dt.checked_add_signed(delta)?;
110
576
        return Some(stepped.to_rfc3339_opts(SecondsFormat::AutoSi, true));
111
4608
    }
112
4608
    if let Ok(date) = NaiveDate::parse_from_str(s, DATE_FORMAT) {
113
        return Some(
114
2496
            date.checked_add_signed(delta)?
115
2496
                .format(DATE_FORMAT)
116
                .to_string(),
117
        );
118
2112
    }
119
2112
    let stepped = parse_date(s, false).ok()?.checked_add_signed(delta)?;
120
1728
    let output = if NaiveDateTime::parse_from_str(s, SECOND_OUTPUT).is_ok() {
121
384
        SECOND_OUTPUT
122
    } else {
123
1344
        MINUTE_OUTPUT
124
    };
125
1728
    Some(stepped.format(output).to_string())
126
5376
}