Skip to main content

carrier_core/
calendar.rs

1//! Working days (Arbeitstage, AT).
2//!
3//! A1 V5.4.1 §2.5 counts deadlines in „Arbeitstage (Mo – Fr)"; WBCI 2.0 §12.6 keeps the
4//! interface available „an bundeseinheitlichen Arbeitstagen". [`Calendar::wbci`] reads both
5//! together: Monday to Friday without the nine nationwide public holidays. That is an
6//! interpretation until the certifier confirms it; [`Calendar::mon_fri`] is the literal
7//! reading, and [`Calendar::with_closed`] adds regional or company closing days.
8//!
9//! S/PRI also counts in Werktage (Monday to Saturday) where the Arbeitshandbuch says so, e.g.
10//! the 10 Werktage the service provider has to answer a TAM (AH4S/PRI 2.9.5 §3.4):
11//! [`Calendar::werktage`] is Monday to Saturday without the nationwide public holidays.
12
13use std::collections::BTreeSet;
14
15use jiff::civil::{Date, Weekday};
16use jiff::tz::TimeZone;
17
18static BERLIN: TimeZone = jiff::tz::get!("Europe/Berlin");
19
20/// The `Europe/Berlin` time zone, compiled in (no system database is read).
21#[must_use]
22pub fn berlin() -> TimeZone {
23    BERLIN.clone()
24}
25
26/// Why a day is not a working day.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28pub enum Closed {
29    /// Saturday or Sunday.
30    Weekend,
31    /// A nationwide public holiday, by name.
32    Holiday(&'static str),
33    /// A day the caller closed.
34    Extra,
35}
36
37impl core::fmt::Display for Closed {
38    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
39        match self {
40            Self::Weekend => f.write_str("weekend"),
41            Self::Holiday(name) => f.write_str(name),
42            Self::Extra => f.write_str("closed day"),
43        }
44    }
45}
46
47/// Which days count as working days.
48#[derive(Debug, Clone, PartialEq, Eq, Default)]
49pub struct Calendar {
50    literal: bool,
51    saturday: bool,
52    extra: BTreeSet<Date>,
53}
54
55impl Calendar {
56    /// Monday to Friday without the nationwide public holidays — the default, and the reading
57    /// of „bundeseinheitliche Arbeitstage" that WBCI 2.0 §12.6 and S/PRI 4.4 §11.3 share.
58    #[must_use]
59    pub fn wbci() -> Self {
60        Self::default()
61    }
62
63    /// Monday to Friday, holidays included: the literal reading of A1 §2.5.
64    #[must_use]
65    pub fn mon_fri() -> Self {
66        Self { literal: true, saturday: false, extra: BTreeSet::new() }
67    }
68
69    /// Werktage: Monday to Saturday without the nationwide public holidays (AH4S/PRI 2.9.5
70    /// §3.4 „10 WT", S/PRI 4.4 §5.1.1 „nächster Werktag (Mo–Sa)").
71    #[must_use]
72    pub fn werktage() -> Self {
73        Self { literal: false, saturday: true, extra: BTreeSet::new() }
74    }
75
76    /// Whether Saturday counts (the [`Calendar::werktage`] reading).
77    #[must_use]
78    pub const fn counts_saturday(&self) -> bool {
79        self.saturday
80    }
81
82    /// Adds a closed day, e.g. a regional holiday that matters to a party.
83    #[must_use]
84    pub fn with_closed(mut self, day: Date) -> Self {
85        self.extra.insert(day);
86        self
87    }
88
89    /// Why `day` is not a working day, or `None` if it is one.
90    #[must_use]
91    pub fn closed(&self, day: Date) -> Option<Closed> {
92        match day.weekday() {
93            Weekday::Sunday => return Some(Closed::Weekend),
94            Weekday::Saturday if !self.saturday => return Some(Closed::Weekend),
95            _ => {}
96        }
97        if !self.literal
98            && let Some(name) = holiday(day)
99        {
100            return Some(Closed::Holiday(name));
101        }
102        self.extra.contains(&day).then_some(Closed::Extra)
103    }
104
105    /// Whether `day` is a working day.
106    #[must_use]
107    pub fn is_working_day(&self, day: Date) -> bool {
108        self.closed(day).is_none()
109    }
110
111    /// The `n`-th working day after `day` (A1 §2.5 „X+n AT"); `day` itself is not counted.
112    #[must_use]
113    pub fn add_working_days(&self, day: Date, n: u32) -> Date {
114        self.walk(day, n, 1).0
115    }
116
117    /// The `n`-th working day before `day` (A1 §2.5 „X−n AT").
118    #[must_use]
119    pub fn sub_working_days(&self, day: Date, n: u32) -> Date {
120        self.walk(day, n, -1).0
121    }
122
123    /// Walks `n` working days in `step` direction (positive: forwards), recording the days
124    /// counted and skipped. Returns the last day reached.
125    #[must_use]
126    pub fn walk(&self, start: Date, n: u32, step: i8) -> (Date, Vec<Date>, Vec<(Date, Closed)>) {
127        let mut day = start;
128        let mut counted = Vec::new();
129        let mut skipped = Vec::new();
130        while counted.len() < n as usize {
131            day = if step > 0 { day.tomorrow() } else { day.yesterday() }.unwrap_or(day);
132            match self.closed(day) {
133                None => counted.push(day),
134                Some(reason) => skipped.push((day, reason)),
135            }
136            if day == Date::MAX || day == Date::MIN {
137                break;
138            }
139        }
140        (day, counted, skipped)
141    }
142}
143
144/// The nationwide public holiday on `day`, if any.
145///
146/// Neujahr, Karfreitag, Ostermontag, Tag der Arbeit, Christi Himmelfahrt, Pfingstmontag,
147/// Tag der Deutschen Einheit, 1. and 2. Weihnachtstag.
148#[must_use]
149pub fn holiday(day: Date) -> Option<&'static str> {
150    let fixed = match (day.month(), day.day()) {
151        (1, 1) => Some("Neujahr"),
152        (5, 1) => Some("Tag der Arbeit"),
153        (10, 3) => Some("Tag der Deutschen Einheit"),
154        (12, 25) => Some("1. Weihnachtstag"),
155        (12, 26) => Some("2. Weihnachtstag"),
156        _ => None,
157    };
158    if fixed.is_some() {
159        return fixed;
160    }
161    let easter = easter_sunday(day.year())?;
162    let offset = (day - easter).get_days();
163    match offset {
164        -2 => Some("Karfreitag"),
165        1 => Some("Ostermontag"),
166        39 => Some("Christi Himmelfahrt"),
167        50 => Some("Pfingstmontag"),
168        _ => None,
169    }
170}
171
172/// Easter Sunday in the Gregorian calendar (anonymous Gregorian algorithm).
173#[must_use]
174#[allow(clippy::many_single_char_names)] // the algorithm's own notation
175pub fn easter_sunday(year: i16) -> Option<Date> {
176    let y = i32::from(year);
177    let a = y % 19;
178    let b = y / 100;
179    let c = y % 100;
180    let d = b / 4;
181    let e = b % 4;
182    let f = (b + 8) / 25;
183    let g = (b - f + 1) / 3;
184    let h = (19 * a + b - d - g + 15) % 30;
185    let i = c / 4;
186    let k = c % 4;
187    let l = (32 + 2 * e + 2 * i - h - k) % 7;
188    let m = (a + 11 * h + 22 * l) / 451;
189    let month = (h + l - 7 * m + 114) / 31;
190    let day = (h + l - 7 * m + 114) % 31 + 1;
191    Date::new(year, i8::try_from(month).ok()?, i8::try_from(day).ok()?).ok()
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197    use jiff::civil::date;
198
199    #[test]
200    fn easter_dates() {
201        assert_eq!(easter_sunday(2024), Some(date(2024, 3, 31)));
202        assert_eq!(easter_sunday(2026), Some(date(2026, 4, 5)));
203        assert_eq!(easter_sunday(2027), Some(date(2027, 3, 28)));
204        assert_eq!(easter_sunday(2038), Some(date(2038, 4, 25)));
205    }
206
207    #[test]
208    fn holidays_2026() {
209        assert_eq!(holiday(date(2026, 4, 3)), Some("Karfreitag"));
210        assert_eq!(holiday(date(2026, 4, 6)), Some("Ostermontag"));
211        assert_eq!(holiday(date(2026, 5, 14)), Some("Christi Himmelfahrt"));
212        assert_eq!(holiday(date(2026, 5, 25)), Some("Pfingstmontag"));
213        assert_eq!(holiday(date(2026, 10, 3)), Some("Tag der Deutschen Einheit"));
214        assert_eq!(holiday(date(2026, 11, 20)), None);
215    }
216
217    #[test]
218    fn counting_skips_weekends_and_holidays() {
219        let cal = Calendar::wbci();
220        // Wednesday 23.12.2026 + 2 AT: Thu 24 counts, 25/26 holiday/weekend, 27 Sunday, Mon 28.
221        assert_eq!(cal.add_working_days(date(2026, 12, 23), 2), date(2026, 12, 28));
222        assert_eq!(Calendar::mon_fri().add_working_days(date(2026, 12, 23), 2), date(2026, 12, 25));
223        assert_eq!(cal.sub_working_days(date(2026, 4, 7), 1), date(2026, 4, 2));
224        let closed = Calendar::wbci().with_closed(date(2026, 11, 23));
225        assert_eq!(closed.add_working_days(date(2026, 11, 20), 1), date(2026, 11, 24));
226    }
227
228    #[test]
229    fn werktage_count_saturdays_but_not_holidays() {
230        let cal = Calendar::werktage();
231        assert!(cal.counts_saturday());
232        assert!(!Calendar::wbci().counts_saturday());
233        assert!(cal.is_working_day(date(2026, 11, 21))); // Saturday
234        assert_eq!(cal.closed(date(2026, 11, 22)), Some(Closed::Weekend)); // Sunday
235        assert_eq!(cal.closed(date(2026, 12, 26)), Some(Closed::Holiday("2. Weihnachtstag"))); // a Saturday
236        // Friday 20.11.2026 + 10 WT: Sa 21, Mo 23 … Sa 28, Mo 30, Di 01.12, Mi 02.12.
237        assert_eq!(cal.add_working_days(date(2026, 11, 20), 10), date(2026, 12, 2));
238        assert_eq!(Calendar::wbci().add_working_days(date(2026, 11, 20), 10), date(2026, 12, 4));
239        // Wednesday 23.12.2026 + 2 WT: Thu 24, (25, 26 holidays, 27 Sunday), Mon 28.
240        assert_eq!(cal.add_working_days(date(2026, 12, 23), 2), date(2026, 12, 28));
241        assert_eq!(cal.sub_working_days(date(2026, 11, 23), 1), date(2026, 11, 21));
242        let closed = Calendar::werktage().with_closed(date(2026, 11, 21));
243        assert_eq!(closed.closed(date(2026, 11, 21)), Some(Closed::Extra));
244        // The other calendars are unchanged.
245        assert_eq!(Calendar::wbci().closed(date(2026, 11, 21)), Some(Closed::Weekend));
246        assert_eq!(Calendar::mon_fri().closed(date(2026, 11, 21)), Some(Closed::Weekend));
247    }
248
249    #[test]
250    fn berlin_is_compiled_in() {
251        let ts = date(2026, 7, 1).at(12, 0, 0, 0).to_zoned_datetime(berlin()).unwrap().timestamp();
252        assert_eq!(berlin().to_offset(ts).seconds(), 7200);
253    }
254}