Skip to main content

automapper_validation/eval/
timezone.rs

1//! DST timezone helpers for German MESZ/MEZ validation.
2//!
3//! EU DST rule: MESZ (summer time) starts the last Sunday of March at 01:00 UTC,
4//! and ends the last Sunday of October at 01:00 UTC.
5
6use chrono::{Datelike, NaiveDate};
7
8use super::evaluator::ConditionResult;
9
10/// Parse EDIFACT DTM format 303 (`CCYYMMDDHHMM`, already UTC per BDEW convention)
11/// into UTC epoch minutes. Any timezone suffix (e.g. `+00`, `UTC`) is ignored —
12/// BDEW values are always UTC.
13///
14/// Returns `None` if the value is too short or contains invalid digits.
15pub fn parse_dtm303(value: &str) -> Option<i64> {
16    let s = value.trim();
17    if s.len() < 12 {
18        return None;
19    }
20    let year: i32 = s.get(0..4).and_then(|v| v.parse().ok())?;
21    let month: u32 = s.get(4..6).and_then(|v| v.parse().ok())?;
22    let day: u32 = s.get(6..8).and_then(|v| v.parse().ok())?;
23    let hour: u32 = s.get(8..10).and_then(|v| v.parse().ok())?;
24    let minute: u32 = s.get(10..12).and_then(|v| v.parse().ok())?;
25    let dt = NaiveDate::from_ymd_opt(year, month, day)?.and_hms_opt(hour, minute, 0)?;
26    Some(dt.and_utc().timestamp() / 60)
27}
28
29/// UTC epoch minutes at which a DTM value begins: the instant itself for
30/// format 303 (`CCYYMMDDHHMM`, UTC), the German midnight that starts the day
31/// for format 102 (`CCYYMMDD`, a calendar day in German time).
32///
33/// Returns `None` for other formats and for values that do not parse.
34pub fn dtm_start_utc_min(value: &str, format: &str) -> Option<i64> {
35    match format {
36        "303" => parse_dtm303(value),
37        "102" => {
38            let s = value.trim();
39            if s.len() != 8 {
40                return None;
41            }
42            let utc_midnight = parse_dtm303(&format!("{s}0000"))?;
43            // German midnight is 22:00 UTC the day before in MESZ, 23:00 in
44            // MEZ. Clocks change at 01:00 UTC, never at German midnight.
45            let mesz_midnight = utc_midnight - 120;
46            let mesz = chrono::DateTime::from_timestamp(mesz_midnight * 60, 0)?
47                .format("%Y%m%d%H%M")
48                .to_string();
49            match is_mesz_utc(&mesz) {
50                ConditionResult::True => Some(mesz_midnight),
51                ConditionResult::False => Some(utc_midnight - 60),
52                ConditionResult::Unknown => None,
53            }
54        }
55        _ => None,
56    }
57}
58
59/// Whether a DTM value (format 303 or 102) lies after a format-303 reference,
60/// such as the document date in DTM+137. A 102 day lies after it when it
61/// begins after it — a later German calendar day.
62///
63/// A value that is no date of its format lies after nothing: `False`.
64/// `Unknown` when the format is neither 303 nor 102 or the reference does
65/// not parse.
66pub fn dtm_after(value: &str, format: &str, reference_303: &str) -> ConditionResult {
67    if !matches!(format, "303" | "102") {
68        return ConditionResult::Unknown;
69    }
70    let Some(reference) = parse_dtm303(reference_303) else {
71        return ConditionResult::Unknown;
72    };
73    match dtm_start_utc_min(value, format) {
74        Some(v) => ConditionResult::from(v > reference),
75        None => ConditionResult::False,
76    }
77}
78
79/// Whether a DTM value lies no later than a format-303 reference, such as
80/// the document date in DTM+137 (`[495]` "Der Zeitpunkt muss ≤ dem Wert im
81/// DE2380 des DTM+137 sein"). A 102 day qualifies when it begins no later —
82/// the reference's German day or one before (`[515]`); a 304 instant compares
83/// to the second. Comparing the strings put `20241115230000+00` (304) after
84/// `202411152300+00`, since `0` sorts after `+`.
85///
86/// `format` `None` (no segment in hand) and formats without an instant
87/// (610 `CCYYMM`, 602 `CCYY`) compare as strings, which orders fixed-width
88/// prefixes correctly. A value that is no date of its format is `False`.
89pub fn dtm_not_after(value: &str, format: Option<&str>, reference_303: &str) -> ConditionResult {
90    let Some(reference) = parse_dtm303(reference_303) else {
91        return ConditionResult::Unknown;
92    };
93    match format {
94        Some(format @ ("303" | "102")) => match dtm_start_utc_min(value, format) {
95            Some(v) => ConditionResult::from(v <= reference),
96            None => ConditionResult::False,
97        },
98        Some("304") => {
99            let seconds = value.get(12..14).and_then(|s| s.parse::<u32>().ok());
100            match (parse_dtm303(value), seconds) {
101                (Some(v), Some(seconds)) => {
102                    ConditionResult::from(v < reference || (v == reference && seconds == 0))
103                }
104                _ => ConditionResult::False,
105            }
106        }
107        _ => ConditionResult::from(value <= reference_303),
108    }
109}
110
111/// Net DST delta across two UTC instants (expressed in epoch minutes).
112///
113/// Returns the net wall-clock/UTC divergence introduced by EU DST transitions
114/// lying strictly between `a` and `b` (in the half-open interval
115/// `[min(a,b), max(a,b))`):
116///
117/// * `0`   — no transition crossed, or equal number of forward/backward crossings
118/// * `+60` — net winter→summer crossing (spring forward, last Sunday of March 01:00 UTC)
119/// * `-60` — net summer→winter crossing (fall back, last Sunday of October 01:00 UTC)
120///
121/// For short intervals (under a few months) the result is at most one transition.
122pub fn dst_transitions_between(a_utc_min: i64, b_utc_min: i64) -> i32 {
123    let (lo, hi) = if a_utc_min <= b_utc_min {
124        (a_utc_min, b_utc_min)
125    } else {
126        (b_utc_min, a_utc_min)
127    };
128    if lo == hi {
129        return 0;
130    }
131    let lo_year = year_of_epoch_min(lo);
132    let hi_year = year_of_epoch_min(hi);
133    let mut delta: i32 = 0;
134    for y in lo_year..=hi_year {
135        let spring_forward = dst_instant_min(y, 3);
136        if lo <= spring_forward && spring_forward < hi {
137            delta += 60;
138        }
139        let fall_back = dst_instant_min(y, 10);
140        if lo <= fall_back && fall_back < hi {
141            delta -= 60;
142        }
143    }
144    delta
145}
146
147fn dst_instant_min(year: i32, month: u32) -> i64 {
148    let date = last_sunday_of_month(year, month);
149    date.and_hms_opt(1, 0, 0).unwrap().and_utc().timestamp() / 60
150}
151
152fn year_of_epoch_min(epoch_min: i64) -> i32 {
153    chrono::DateTime::from_timestamp(epoch_min * 60, 0)
154        .map(|dt| dt.date_naive().year())
155        .unwrap_or(1970)
156}
157
158/// Returns `True` if the given CCYYMMDDHHMM value falls within German summer time (MESZ),
159/// `False` if it falls in winter time (MEZ), or `Unknown` if the input is invalid/too short.
160///
161/// Only the first 12 characters are used, so a 15-char value with timezone suffix also works.
162pub fn is_mesz_utc(dtm_value: &str) -> ConditionResult {
163    let s = dtm_value.trim();
164    if s.len() < 8 {
165        return ConditionResult::Unknown;
166    }
167
168    let year: i32 = match s[0..4].parse() {
169        Ok(v) => v,
170        Err(_) => return ConditionResult::Unknown,
171    };
172    let month: u32 = match s[4..6].parse() {
173        Ok(v) => v,
174        Err(_) => return ConditionResult::Unknown,
175    };
176    let day: u32 = match s[6..8].parse() {
177        Ok(v) => v,
178        Err(_) => return ConditionResult::Unknown,
179    };
180    let hour: u32 = if s.len() >= 10 {
181        match s[8..10].parse() {
182            Ok(v) => v,
183            Err(_) => return ConditionResult::Unknown,
184        }
185    } else {
186        0
187    };
188    let minute: u32 = if s.len() >= 12 {
189        match s[10..12].parse() {
190            Ok(v) => v,
191            Err(_) => return ConditionResult::Unknown,
192        }
193    } else {
194        0
195    };
196
197    let Some(dt) =
198        NaiveDate::from_ymd_opt(year, month, day).and_then(|d| d.and_hms_opt(hour, minute, 0))
199    else {
200        return ConditionResult::Unknown;
201    };
202
203    let mesz_start = last_sunday_of_month(year, 3).and_hms_opt(1, 0, 0).unwrap();
204    let mesz_end = last_sunday_of_month(year, 10).and_hms_opt(1, 0, 0).unwrap();
205
206    ConditionResult::from(dt >= mesz_start && dt < mesz_end)
207}
208
209/// Returns `True` if the given CCYYMMDDHHMM value falls within German winter time (MEZ).
210///
211/// This is the complement of [`is_mesz_utc`].
212pub fn is_mez_utc(dtm_value: &str) -> ConditionResult {
213    match is_mesz_utc(dtm_value) {
214        ConditionResult::True => ConditionResult::False,
215        ConditionResult::False => ConditionResult::True,
216        ConditionResult::Unknown => ConditionResult::Unknown,
217    }
218}
219
220/// Last Sunday of the given month as a `NaiveDate`.
221fn last_sunday_of_month(year: i32, month: u32) -> NaiveDate {
222    // Start from the last day of the month and walk backwards to Sunday
223    let last_day = NaiveDate::from_ymd_opt(year, month + 1, 1)
224        .unwrap_or_else(|| NaiveDate::from_ymd_opt(year + 1, 1, 1).unwrap())
225        .pred_opt()
226        .unwrap();
227    let days_since_sunday = last_day.weekday().num_days_from_sunday();
228    last_day - chrono::Duration::days(days_since_sunday as i64)
229}
230
231#[cfg(test)]
232mod tests {
233
234    #[test]
235    fn not_after_compares_each_format_as_what_it_means() {
236        let reference = "202411152300+00"; // German 16 Nov 2024, 00:00
237        let not_after = |v: &str, f: Option<&str>| dtm_not_after(v, f, reference);
238        assert_eq!(
239            not_after("20241115230000+00", Some("304")),
240            ConditionResult::True
241        );
242        assert_eq!(
243            not_after("20241115230001+00", Some("304")),
244            ConditionResult::False
245        );
246        assert_eq!(
247            not_after("202411152300+00", Some("303")),
248            ConditionResult::True
249        );
250        assert_eq!(
251            not_after("202411152301+00", Some("303")),
252            ConditionResult::False
253        );
254        // The day the reference opens, and the one before it.
255        assert_eq!(not_after("20241116", Some("102")), ConditionResult::True);
256        assert_eq!(not_after("20241115", Some("102")), ConditionResult::True);
257        assert_eq!(not_after("20241117", Some("102")), ConditionResult::False);
258        assert_eq!(not_after("202411", Some("610")), ConditionResult::True);
259        assert_eq!(not_after("202412", Some("610")), ConditionResult::False);
260        assert_eq!(not_after("1", Some("102")), ConditionResult::False);
261    }
262
263    use super::*;
264
265    #[test]
266    fn test_known_mesz_date() {
267        assert_eq!(is_mesz_utc("202607151200"), ConditionResult::True);
268    }
269
270    #[test]
271    fn test_known_mez_date() {
272        assert_eq!(is_mesz_utc("202601151200"), ConditionResult::False);
273    }
274
275    #[test]
276    fn test_march_transition_2026() {
277        // Last Sunday of March 2026 = March 29
278        assert_eq!(is_mesz_utc("202603290059"), ConditionResult::False);
279        assert_eq!(is_mesz_utc("202603290100"), ConditionResult::True);
280    }
281
282    #[test]
283    fn test_october_transition_2026() {
284        // Last Sunday of October 2026 = October 25
285        assert_eq!(is_mesz_utc("202610250059"), ConditionResult::True);
286        assert_eq!(is_mesz_utc("202610250100"), ConditionResult::False);
287    }
288
289    #[test]
290    fn test_short_input() {
291        assert_eq!(is_mesz_utc("2026"), ConditionResult::Unknown);
292        assert_eq!(is_mesz_utc(""), ConditionResult::Unknown);
293        assert_eq!(is_mesz_utc("20260715"), ConditionResult::True);
294        assert_eq!(is_mesz_utc("20260115"), ConditionResult::False);
295    }
296
297    #[test]
298    fn test_invalid_input_returns_unknown() {
299        assert_eq!(is_mesz_utc("abcdefghijkl"), ConditionResult::Unknown);
300        assert_eq!(is_mesz_utc("202613151200"), ConditionResult::Unknown);
301        assert_eq!(is_mesz_utc("202601321200"), ConditionResult::Unknown);
302    }
303
304    #[test]
305    fn test_is_mez_complements_is_mesz() {
306        assert_eq!(is_mez_utc("202607151200"), ConditionResult::False);
307        assert_eq!(is_mez_utc("202601151200"), ConditionResult::True);
308        assert_eq!(is_mez_utc("short"), ConditionResult::Unknown);
309    }
310
311    #[test]
312    fn test_value_with_timezone_suffix() {
313        assert_eq!(is_mesz_utc("202607151200UTC"), ConditionResult::True);
314        assert_eq!(is_mesz_utc("202601151200303"), ConditionResult::False);
315    }
316
317    #[test]
318    fn test_last_sunday_of_march_2026() {
319        assert_eq!(
320            last_sunday_of_month(2026, 3),
321            NaiveDate::from_ymd_opt(2026, 3, 29).unwrap()
322        );
323    }
324
325    #[test]
326    fn test_last_sunday_of_october_2026() {
327        assert_eq!(
328            last_sunday_of_month(2026, 10),
329            NaiveDate::from_ymd_opt(2026, 10, 25).unwrap()
330        );
331    }
332
333    #[test]
334    fn test_parse_dtm303_valid() {
335        // 2026-01-15 12:00 UTC
336        let m = parse_dtm303("202601151200").unwrap();
337        // Sanity: same as chrono naive UTC
338        let expected = NaiveDate::from_ymd_opt(2026, 1, 15)
339            .unwrap()
340            .and_hms_opt(12, 0, 0)
341            .unwrap()
342            .and_utc()
343            .timestamp()
344            / 60;
345        assert_eq!(m, expected);
346    }
347
348    #[test]
349    fn test_parse_dtm303_ignores_tz_suffix() {
350        let a = parse_dtm303("202603290100").unwrap();
351        let b = parse_dtm303("202603290100+00").unwrap();
352        let c = parse_dtm303("202603290100UTC").unwrap();
353        assert_eq!(a, b);
354        assert_eq!(a, c);
355    }
356
357    #[test]
358    fn test_parse_dtm303_rejects_short() {
359        assert!(parse_dtm303("20260115").is_none());
360        assert!(parse_dtm303("").is_none());
361    }
362
363    #[test]
364    fn test_parse_dtm303_rejects_invalid() {
365        assert!(parse_dtm303("2026ZZ151200").is_none());
366        assert!(parse_dtm303("202613151200").is_none());
367    }
368
369    #[test]
370    fn test_dst_no_transition_same_day() {
371        let a = parse_dtm303("202601150800").unwrap();
372        let b = parse_dtm303("202601151200").unwrap();
373        assert_eq!(dst_transitions_between(a, b), 0);
374    }
375
376    #[test]
377    fn test_dst_spring_forward_2026() {
378        // March transition 2026: last Sunday of March = 29th, 01:00 UTC
379        let before = parse_dtm303("202603290030").unwrap();
380        let after = parse_dtm303("202603290130").unwrap();
381        assert_eq!(dst_transitions_between(before, after), 60);
382        // Symmetric
383        assert_eq!(dst_transitions_between(after, before), 60);
384    }
385
386    #[test]
387    fn test_dst_fall_back_2026() {
388        // October transition 2026: last Sunday of October = 25th, 01:00 UTC
389        let before = parse_dtm303("202610250030").unwrap();
390        let after = parse_dtm303("202610250130").unwrap();
391        assert_eq!(dst_transitions_between(before, after), -60);
392        assert_eq!(dst_transitions_between(after, before), -60);
393    }
394
395    #[test]
396    fn test_dst_transition_at_exact_boundary() {
397        // Interval [spring_forward, spring_forward) is empty — no transition.
398        let at_boundary = parse_dtm303("202603290100").unwrap();
399        assert_eq!(dst_transitions_between(at_boundary, at_boundary), 0);
400        // Interval that includes the boundary.
401        let after = parse_dtm303("202603290200").unwrap();
402        assert_eq!(dst_transitions_between(at_boundary, after), 60);
403    }
404
405    #[test]
406    fn test_dst_both_transitions_cancel() {
407        // Full year span: spring forward + fall back = net zero.
408        let winter_a = parse_dtm303("202601010000").unwrap();
409        let winter_b = parse_dtm303("202612310000").unwrap();
410        assert_eq!(dst_transitions_between(winter_a, winter_b), 0);
411    }
412
413    #[test]
414    fn test_different_years() {
415        assert_eq!(
416            last_sunday_of_month(2025, 3),
417            NaiveDate::from_ymd_opt(2025, 3, 30).unwrap()
418        );
419        assert_eq!(
420            last_sunday_of_month(2025, 10),
421            NaiveDate::from_ymd_opt(2025, 10, 26).unwrap()
422        );
423        assert_eq!(
424            last_sunday_of_month(2024, 3),
425            NaiveDate::from_ymd_opt(2024, 3, 31).unwrap()
426        );
427        assert_eq!(
428            last_sunday_of_month(2024, 10),
429            NaiveDate::from_ymd_opt(2024, 10, 27).unwrap()
430        );
431    }
432}