Skip to main content

dre_core/
dates.rs

1//! Calendar values for templates: `run.date`, `run.now`, `date()`, `datetime()` and the
2//! periods built from them. Everything is worked out at render time, so compiled SQL holds
3//! literals and a rerun with the same `DRE_RUN_DATE` renders the same text.
4//!
5//! Three types:
6//! - `Date`: a calendar day. Renders `YYYY-MM-DD`.
7//! - `DateTime`: an instant, shown in a timezone. Renders `YYYY-MM-DD HH:MM:SS[.ffffff]`.
8//! - `Period`: a run of whole days (a week, a month, ...). `start` and `end` are its first
9//!   and last instants; `start.date` and `end.date` its first and last days.
10//!
11//! A `Calendar` (the run's timezone, first day of the week and week numbering) travels with
12//! every value, so navigation and conversions agree with the project's settings.
13
14use std::fmt;
15use std::sync::Arc;
16
17use chrono::{
18    DateTime as ChronoDateTime, Datelike, Days, Duration, LocalResult, Months, NaiveDate, NaiveDateTime,
19    NaiveTime, Offset, TimeZone, Timelike, Utc, Weekday,
20};
21use chrono_tz::Tz;
22use minijinja::value::{Kwargs, Object, ObjectRepr, Value};
23use minijinja::{Environment, Error, ErrorKind, State};
24
25/// The first day of a week.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)]
27#[serde(rename_all = "lowercase")]
28#[schemars(inline)]
29pub enum WeekStart {
30    Monday,
31    Sunday,
32}
33
34impl WeekStart {
35    pub fn parse(s: &str) -> Option<WeekStart> {
36        match s {
37            "monday" => Some(WeekStart::Monday),
38            "sunday" => Some(WeekStart::Sunday),
39            _ => None,
40        }
41    }
42    fn weekday(self) -> Weekday {
43        match self {
44            WeekStart::Monday => Weekday::Mon,
45            WeekStart::Sunday => Weekday::Sun,
46        }
47    }
48}
49
50/// How weeks are numbered: `iso` (week 1 holds the year's first Thursday) or `us` (week 1
51/// holds 1 January).
52#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)]
53#[serde(rename_all = "lowercase")]
54#[schemars(inline)]
55pub enum WeekNumbering {
56    Iso,
57    Us,
58}
59
60impl WeekNumbering {
61    pub fn parse(s: &str) -> Option<WeekNumbering> {
62        match s {
63            "iso" => Some(WeekNumbering::Iso),
64            "us" => Some(WeekNumbering::Us),
65            _ => None,
66        }
67    }
68}
69
70/// The settings every date value carries.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct Calendar {
73    pub tz: Tz,
74    pub week_start: WeekStart,
75    pub numbering: WeekNumbering,
76}
77
78impl Default for Calendar {
79    fn default() -> Self {
80        Calendar {
81            tz: Tz::UTC,
82            week_start: WeekStart::Monday,
83            numbering: WeekNumbering::Iso,
84        }
85    }
86}
87
88/// Parse an IANA timezone name (`Australia/Sydney`, `UTC`).
89pub fn parse_tz(name: &str) -> Result<Tz, String> {
90    name.parse::<Tz>().map_err(|_| {
91        format!("`{name}` isn't a timezone; use an IANA name such as `UTC` or `Australia/Sydney`")
92    })
93}
94
95impl Calendar {
96    /// Today in this calendar's timezone.
97    pub fn today(&self) -> NaiveDate {
98        Utc::now().with_timezone(&self.tz).date_naive()
99    }
100
101    /// The first instant of `d` here: midnight, or the first valid time after a DST gap.
102    fn start_of(&self, d: NaiveDate) -> ChronoDateTime<Tz> {
103        let mut t = d.and_time(NaiveTime::MIN);
104        loop {
105            if let Some(x) = self.tz.from_local_datetime(&t).earliest() {
106                return x;
107            }
108            t += Duration::minutes(15);
109        }
110    }
111
112    /// The last microsecond of `d` here.
113    fn end_of(&self, d: NaiveDate) -> ChronoDateTime<Tz> {
114        self.start_of(d + Days::new(1)) - Duration::microseconds(1)
115    }
116
117    fn week_start_of(&self, d: NaiveDate) -> NaiveDate {
118        let back =
119            (7 + d.weekday().num_days_from_monday() - self.week_start.weekday().num_days_from_monday()) % 7;
120        d - Days::new(back as u64)
121    }
122
123    /// `(week_year, week)` in this calendar's numbering.
124    fn week_number(&self, d: NaiveDate) -> (i32, u32) {
125        match self.numbering {
126            WeekNumbering::Iso => (d.iso_week().year(), d.iso_week().week()),
127            WeekNumbering::Us => {
128                let first = self.week_start_of(NaiveDate::from_ymd_opt(d.year(), 1, 1).unwrap());
129                (d.year(), ((d - first).num_days() / 7) as u32 + 1)
130            }
131        }
132    }
133
134    /// The first day of week `w` of `year`, in this calendar's numbering.
135    fn week_of(&self, year: i32, w: u32) -> Result<NaiveDate, String> {
136        let bad = || format!("week_of({year}, {w}): there's no week {w} in {year}");
137        match self.numbering {
138            WeekNumbering::Iso => {
139                let monday = NaiveDate::from_isoywd_opt(year, w, Weekday::Mon).ok_or_else(bad)?;
140                Ok(self.week_start_of(monday))
141            }
142            WeekNumbering::Us => {
143                let jan1 = NaiveDate::from_ymd_opt(year, 1, 1).ok_or_else(bad)?;
144                let start = self.week_start_of(jan1) + Days::new(7 * (w.max(1) as u64 - 1));
145                if w == 0 || start.year() > year {
146                    return Err(bad());
147                }
148                Ok(start)
149            }
150        }
151    }
152}
153
154fn err(msg: impl Into<String>) -> Error {
155    Error::new(ErrorKind::InvalidOperation, msg.into())
156}
157
158fn quarter_start(d: NaiveDate) -> NaiveDate {
159    NaiveDate::from_ymd_opt(d.year(), (d.month() - 1) / 3 * 3 + 1, 1).unwrap()
160}
161
162fn month_start(d: NaiveDate) -> NaiveDate {
163    d.with_day(1).unwrap()
164}
165
166fn year_start(d: NaiveDate) -> NaiveDate {
167    NaiveDate::from_ymd_opt(d.year(), 1, 1).unwrap()
168}
169
170fn add_months(d: NaiveDate, n: i64) -> Option<NaiveDate> {
171    if n >= 0 {
172        d.checked_add_months(Months::new(n as u32))
173    } else {
174        d.checked_sub_months(Months::new(n.unsigned_abs() as u32))
175    }
176}
177
178fn add_days(d: NaiveDate, n: i64) -> Option<NaiveDate> {
179    if n >= 0 {
180        d.checked_add_days(Days::new(n as u64))
181    } else {
182        d.checked_sub_days(Days::new(n.unsigned_abs()))
183    }
184}
185
186/// `strftime` with an error instead of a panic for a bad format string.
187fn strftime(f: impl fmt::Display) -> Result<String, Error> {
188    use fmt::Write;
189    let mut out = String::new();
190    write!(out, "{f}").map_err(|_| err("invalid date format string"))?;
191    Ok(out)
192}
193
194// ---------------------------------------------------------------------------------------------
195// Date
196// ---------------------------------------------------------------------------------------------
197
198/// Every attribute of a `Date`, for `dre validate`'s check of `run.date.<name>`.
199pub const DATE_ATTRS: &[&str] = &[
200    "year",
201    "month",
202    "day",
203    "quarter",
204    "week",
205    "week_year",
206    "weekday",
207    "day_of_year",
208    "days_in_month",
209    "prev_day",
210    "next_day",
211    "week_start",
212    "week_end",
213    "month_start",
214    "month_end",
215    "quarter_start",
216    "quarter_end",
217    "year_start",
218    "year_end",
219    "this_week",
220    "prev_week",
221    "next_week",
222    "this_month",
223    "prev_month",
224    "next_month",
225    "this_quarter",
226    "prev_quarter",
227    "next_quarter",
228    "this_year",
229    "prev_year",
230    "next_year",
231    "start",
232    "end",
233    "date",
234    "unix",
235    "unix_ms",
236    "iso",
237    "yyyymmdd",
238    "ddmmyyyy",
239    "yyyy",
240    "mm",
241    "dd",
242    "add",
243    "format",
244    "as_period",
245];
246
247#[derive(Debug, Clone)]
248pub struct Date {
249    d: NaiveDate,
250    cal: Calendar,
251}
252
253impl Date {
254    pub fn value(d: NaiveDate, cal: Calendar) -> Value {
255        Value::from_object(Date { d, cal })
256    }
257
258    fn at(&self, d: NaiveDate) -> Value {
259        Date::value(d, self.cal)
260    }
261
262    fn period(&self, kind: Kind, first: NaiveDate) -> Value {
263        Period::value(Period::of(kind, first, self.cal))
264    }
265}
266
267impl fmt::Display for Date {
268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269        write!(f, "{}", self.d.format("%Y-%m-%d"))
270    }
271}
272
273impl Object for Date {
274    fn repr(self: &Arc<Self>) -> ObjectRepr {
275        ObjectRepr::Plain
276    }
277
278    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
279        let d = self.d;
280        let cal = self.cal;
281        let s = |f: &str| Some(Value::from(d.format(f).to_string()));
282        Some(match key.as_str()? {
283            "year" => Value::from(d.year()),
284            "month" => Value::from(d.month()),
285            "day" => Value::from(d.day()),
286            "quarter" => Value::from((d.month() - 1) / 3 + 1),
287            "week" => Value::from(cal.week_number(d).1),
288            "week_year" => Value::from(cal.week_number(d).0),
289            "weekday" => Value::from(d.weekday().number_from_monday()),
290            "day_of_year" => Value::from(d.ordinal()),
291            "days_in_month" => {
292                Value::from((add_months(month_start(d), 1).unwrap() - month_start(d)).num_days())
293            }
294            "prev_day" => self.at(d.pred_opt()?),
295            "next_day" => self.at(d.succ_opt()?),
296            "week_start" => self.at(cal.week_start_of(d)),
297            "week_end" => self.at(cal.week_start_of(d) + Days::new(6)),
298            "month_start" => self.at(month_start(d)),
299            "month_end" => self.at(add_months(month_start(d), 1)?.pred_opt()?),
300            "quarter_start" => self.at(quarter_start(d)),
301            "quarter_end" => self.at(add_months(quarter_start(d), 3)?.pred_opt()?),
302            "year_start" => self.at(year_start(d)),
303            "year_end" => self.at(NaiveDate::from_ymd_opt(d.year(), 12, 31)?),
304            "this_week" => self.period(Kind::Week, cal.week_start_of(d)),
305            "prev_week" => self.period(Kind::Week, cal.week_start_of(d) - Days::new(7)),
306            "next_week" => self.period(Kind::Week, cal.week_start_of(d) + Days::new(7)),
307            "this_month" => self.period(Kind::Month, month_start(d)),
308            "prev_month" => self.period(Kind::Month, add_months(month_start(d), -1)?),
309            "next_month" => self.period(Kind::Month, add_months(month_start(d), 1)?),
310            "this_quarter" => self.period(Kind::Quarter, quarter_start(d)),
311            "prev_quarter" => self.period(Kind::Quarter, add_months(quarter_start(d), -3)?),
312            "next_quarter" => self.period(Kind::Quarter, add_months(quarter_start(d), 3)?),
313            "this_year" => self.period(Kind::Year, year_start(d)),
314            "prev_year" => self.period(Kind::Year, add_months(year_start(d), -12)?),
315            "next_year" => self.period(Kind::Year, add_months(year_start(d), 12)?),
316            "start" => DateTime::value(cal.start_of(d), cal),
317            "end" => DateTime::value(cal.end_of(d), cal),
318            "date" => self.at(d),
319            "unix" => Value::from(cal.start_of(d).timestamp()),
320            "unix_ms" => Value::from(cal.start_of(d).timestamp_millis()),
321            "iso" => return s("%Y-%m-%d"),
322            "yyyymmdd" => return s("%Y%m%d"),
323            "ddmmyyyy" => return s("%d%m%Y"),
324            "yyyy" => return s("%Y"),
325            "mm" => return s("%m"),
326            "dd" => return s("%d"),
327            _ => return None,
328        })
329    }
330
331    fn call_method(
332        self: &Arc<Self>,
333        _: &State<'_, '_>,
334        method: &str,
335        args: &[Value],
336    ) -> Result<Value, Error> {
337        match method {
338            "format" => {
339                let (fmt,): (&str,) = minijinja::value::from_args(args)?;
340                Ok(Value::from(strftime(self.d.format(fmt))?))
341            }
342            "add" => {
343                let (kw,): (Kwargs,) = minijinja::value::from_args(args)?;
344                let get = |k: &str| -> Result<i64, Error> { Ok(kw.get::<Option<i64>>(k)?.unwrap_or(0)) };
345                let (years, months, weeks, days) =
346                    (get("years")?, get("months")?, get("weeks")?, get("days")?);
347                kw.assert_all_used()?;
348                let d = add_months(self.d, years * 12 + months)
349                    .and_then(|d| add_days(d, weeks * 7 + days))
350                    .ok_or_else(|| err("date out of range"))?;
351                Ok(self.at(d))
352            }
353            // `d.day` is the day of the month; the one-day period is `d.as_period()`.
354            "as_period" => Ok(self.period(Kind::Day, self.d)),
355            _ => Err(Error::from(ErrorKind::UnknownMethod)),
356        }
357    }
358
359    fn render(self: &Arc<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
360        fmt::Display::fmt(&**self, f)
361    }
362}
363
364// ---------------------------------------------------------------------------------------------
365// DateTime
366// ---------------------------------------------------------------------------------------------
367
368#[derive(Debug, Clone)]
369pub struct DateTime {
370    t: ChronoDateTime<Tz>,
371    cal: Calendar,
372}
373
374impl DateTime {
375    pub fn value(t: ChronoDateTime<Tz>, cal: Calendar) -> Value {
376        Value::from_object(DateTime { t, cal })
377    }
378
379    /// `run.now`: an instant shown in the run's timezone.
380    pub fn now(at: ChronoDateTime<Utc>, cal: Calendar) -> Value {
381        DateTime::value(at.with_timezone(&cal.tz), cal)
382    }
383
384    fn fraction(&self) -> &'static str {
385        if self.t.nanosecond() == 0 { "" } else { ".%6f" }
386    }
387}
388
389impl fmt::Display for DateTime {
390    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391        write!(
392            f,
393            "{}",
394            self.t.format(&format!("%Y-%m-%d %H:%M:%S{}", self.fraction()))
395        )
396    }
397}
398
399impl Object for DateTime {
400    fn repr(self: &Arc<Self>) -> ObjectRepr {
401        ObjectRepr::Plain
402    }
403
404    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
405        let t = self.t;
406        Some(match key.as_str()? {
407            "date" => Date::value(t.date_naive(), self.cal),
408            "time" => Value::from(t.format(&format!("%H:%M:%S{}", self.fraction())).to_string()),
409            "utc" => DateTime::value(t.with_timezone(&Tz::UTC), self.cal),
410            "iso" => {
411                let f = if t.nanosecond() == 0 {
412                    "%Y-%m-%dT%H:%M:%S%:z"
413                } else {
414                    "%Y-%m-%dT%H:%M:%S%.6f%:z"
415                };
416                Value::from(t.format(f).to_string())
417            }
418            "unix" => Value::from(t.timestamp()),
419            "unix_ms" => Value::from(t.timestamp_millis()),
420            "timezone" => Value::from(t.timezone().name()),
421            "offset" => Value::from(t.offset().fix().to_string()),
422            "year" => Value::from(t.year()),
423            "month" => Value::from(t.month()),
424            "day" => Value::from(t.day()),
425            "hour" => Value::from(t.hour()),
426            "minute" => Value::from(t.minute()),
427            "second" => Value::from(t.second()),
428            _ => return None,
429        })
430    }
431
432    fn call_method(
433        self: &Arc<Self>,
434        _: &State<'_, '_>,
435        method: &str,
436        args: &[Value],
437    ) -> Result<Value, Error> {
438        match method {
439            "format" => {
440                let (fmt,): (&str,) = minijinja::value::from_args(args)?;
441                Ok(Value::from(strftime(self.t.format(fmt))?))
442            }
443            "tz" => {
444                let (name,): (&str,) = minijinja::value::from_args(args)?;
445                let tz = parse_tz(name).map_err(err)?;
446                Ok(DateTime::value(self.t.with_timezone(&tz), self.cal))
447            }
448            "add" => {
449                let (kw,): (Kwargs,) = minijinja::value::from_args(args)?;
450                let get = |k: &str| -> Result<i64, Error> { Ok(kw.get::<Option<i64>>(k)?.unwrap_or(0)) };
451                let (years, months, weeks, days) =
452                    (get("years")?, get("months")?, get("weeks")?, get("days")?);
453                let (hours, minutes, seconds) = (get("hours")?, get("minutes")?, get("seconds")?);
454                kw.assert_all_used()?;
455                // Calendar parts move the wall clock (a day later is the same clock time, even
456                // across a daylight-saving change); clock parts move the instant.
457                let moved = if years == 0 && months == 0 && weeks == 0 && days == 0 {
458                    self.t
459                } else {
460                    let local = self.t.naive_local();
461                    let day = add_months(local.date(), years * 12 + months)
462                        .and_then(|d| add_days(d, weeks * 7 + days))
463                        .ok_or_else(|| err("date out of range"))?;
464                    let wall = day.and_time(local.time());
465                    let tz = self.t.timezone();
466                    let offset = self.t.offset().fix();
467                    match tz.from_local_datetime(&wall) {
468                        LocalResult::Single(t) => t,
469                        // A clock time that happens twice: keep the offset it had, if it can.
470                        LocalResult::Ambiguous(a, b) => {
471                            if b.offset().fix() == offset {
472                                b
473                            } else {
474                                a
475                            }
476                        }
477                        // A clock time the change skips: read it with the old offset, so 02:30
478                        // becomes 03:30 when 02:00 jumps to 03:00.
479                        LocalResult::None => tz.from_utc_datetime(&(wall - offset)),
480                    }
481                };
482                let t =
483                    moved + Duration::hours(hours) + Duration::minutes(minutes) + Duration::seconds(seconds);
484                Ok(DateTime::value(t, self.cal))
485            }
486            _ => Err(Error::from(ErrorKind::UnknownMethod)),
487        }
488    }
489
490    fn render(self: &Arc<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
491        fmt::Display::fmt(&**self, f)
492    }
493}
494
495// ---------------------------------------------------------------------------------------------
496// Period
497// ---------------------------------------------------------------------------------------------
498
499#[derive(Debug, Clone, Copy, PartialEq, Eq)]
500enum Kind {
501    Day,
502    Week,
503    Month,
504    Quarter,
505    Year,
506    /// Any run of days (`date_range()`): `next`/`prev` move by its length.
507    Days(u64),
508}
509
510#[derive(Debug, Clone)]
511pub struct Period {
512    kind: Kind,
513    first: NaiveDate,
514    last: NaiveDate,
515    cal: Calendar,
516}
517
518impl Period {
519    fn value(p: Period) -> Value {
520        Value::from_object(p)
521    }
522
523    fn of(kind: Kind, first: NaiveDate, cal: Calendar) -> Period {
524        let last = match kind {
525            Kind::Day => first,
526            Kind::Week => first + Days::new(6),
527            Kind::Month => add_months(first, 1).unwrap() - Days::new(1),
528            Kind::Quarter => add_months(first, 3).unwrap() - Days::new(1),
529            Kind::Year => add_months(first, 12).unwrap() - Days::new(1),
530            Kind::Days(n) => first + Days::new(n - 1),
531        };
532        Period {
533            kind,
534            first,
535            last,
536            cal,
537        }
538    }
539
540    fn shift(&self, forward: bool) -> Option<Period> {
541        let first = match (self.kind, forward) {
542            (Kind::Day, f) => add_days(self.first, if f { 1 } else { -1 })?,
543            (Kind::Week, f) => add_days(self.first, if f { 7 } else { -7 })?,
544            (Kind::Month, f) => add_months(self.first, if f { 1 } else { -1 })?,
545            (Kind::Quarter, f) => add_months(self.first, if f { 3 } else { -3 })?,
546            (Kind::Year, f) => add_months(self.first, if f { 12 } else { -12 })?,
547            (Kind::Days(n), f) => add_days(self.first, if f { n as i64 } else { -(n as i64) })?,
548        };
549        Some(Period::of(self.kind, first, self.cal))
550    }
551}
552
553impl Object for Period {
554    fn repr(self: &Arc<Self>) -> ObjectRepr {
555        ObjectRepr::Plain
556    }
557
558    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
559        let cal = self.cal;
560        Some(match key.as_str()? {
561            "start" => DateTime::value(cal.start_of(self.first), cal),
562            "end" => DateTime::value(cal.end_of(self.last), cal),
563            "first_day" => Date::value(self.first, cal),
564            "last_day" => Date::value(self.last, cal),
565            "next" => Period::value(self.shift(true)?),
566            "prev" => Period::value(self.shift(false)?),
567            "days" => Value::from((self.last - self.first).num_days() + 1),
568            _ => return None,
569        })
570    }
571
572    /// ISO 8601 interval notation, so a Period dropped into SQL by mistake is easy to spot.
573    fn render(self: &Arc<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
574        write!(
575            f,
576            "{}/{}",
577            self.first.format("%Y-%m-%d"),
578            self.last.format("%Y-%m-%d")
579        )
580    }
581}
582
583// ---------------------------------------------------------------------------------------------
584// Constructors
585// ---------------------------------------------------------------------------------------------
586
587fn parse_date(s: &str) -> Option<NaiveDate> {
588    let s = s.trim();
589    NaiveDate::parse_from_str(s, "%Y-%m-%d")
590        .or_else(|_| NaiveDate::parse_from_str(s, "%Y%m%d"))
591        .ok()
592        .or_else(|| {
593            s.get(..10)
594                .and_then(|p| NaiveDate::parse_from_str(p, "%Y-%m-%d").ok())
595        })
596}
597
598fn parse_datetime(s: &str, cal: Calendar) -> Option<ChronoDateTime<Tz>> {
599    let s = s.trim();
600    if let Ok(t) = ChronoDateTime::parse_from_rfc3339(s) {
601        return Some(t.with_timezone(&cal.tz));
602    }
603    for f in [
604        "%Y-%m-%d %H:%M:%S%.f%:z",
605        "%Y-%m-%d %H:%M:%S%:z",
606        "%Y-%m-%d %H:%M%:z",
607    ] {
608        if let Ok(t) = ChronoDateTime::parse_from_str(s, f) {
609            return Some(t.with_timezone(&cal.tz));
610        }
611    }
612    for f in [
613        "%Y-%m-%d %H:%M:%S%.f",
614        "%Y-%m-%dT%H:%M:%S%.f",
615        "%Y-%m-%d %H:%M",
616        "%Y-%m-%dT%H:%M",
617    ] {
618        if let Ok(t) = NaiveDateTime::parse_from_str(s, f) {
619            return cal.tz.from_local_datetime(&t).earliest();
620        }
621    }
622    NaiveDate::parse_from_str(s, "%Y-%m-%d")
623        .ok()
624        .map(|d| cal.start_of(d))
625}
626
627/// A Date from a value: a Date, a DateTime (its day), or a string.
628fn to_date(v: &Value, cal: Calendar) -> Result<NaiveDate, Error> {
629    if let Some(d) = v.downcast_object_ref::<Date>() {
630        return Ok(d.d);
631    }
632    if let Some(t) = v.downcast_object_ref::<DateTime>() {
633        return Ok(t.t.date_naive());
634    }
635    let _ = cal;
636    v.as_str()
637        .and_then(parse_date)
638        .ok_or_else(|| err(format!("`{v}` isn't a date; use `YYYY-MM-DD`")))
639}
640
641fn to_datetime(v: &Value, cal: Calendar) -> Result<ChronoDateTime<Tz>, Error> {
642    if let Some(t) = v.downcast_object_ref::<DateTime>() {
643        return Ok(t.t);
644    }
645    if let Some(d) = v.downcast_object_ref::<Date>() {
646        return Ok(cal.start_of(d.d));
647    }
648    v.as_str().and_then(|s| parse_datetime(s, cal)).ok_or_else(|| {
649        err(format!(
650            "`{v}` isn't a date and time; use `YYYY-MM-DD HH:MM:SS`, optionally with an offset"
651        ))
652    })
653}
654
655fn ymd(y: i32, m: u32, d: u32) -> Result<NaiveDate, Error> {
656    NaiveDate::from_ymd_opt(y, m, d).ok_or_else(|| err(format!("{y}-{m:02}-{d:02} isn't a date")))
657}
658
659/// The named periods `period()` knows.
660pub const PERIOD_PRESETS: &[&str] = &[
661    "today",
662    "yesterday",
663    "this_week",
664    "last_week",
665    "this_month",
666    "last_month",
667    "mtd",
668    "this_quarter",
669    "last_quarter",
670    "qtd",
671    "this_year",
672    "last_year",
673    "ytd",
674    "last_n_days",
675    "last_n_months",
676];
677
678/// A named period relative to `as_of`: `last_month`, `mtd`, `last_n_days` (with `n`), ...
679/// `mtd`, `qtd` and `ytd` run through `as_of` itself; `last_n_days` ends the day before it.
680fn preset(name: &str, as_of: NaiveDate, n: Option<i64>, cal: Calendar) -> Result<Period, String> {
681    let d = as_of;
682    let week = cal.week_start_of(d);
683    let range = |first: NaiveDate, last: NaiveDate| {
684        Period::of(Kind::Days((last - first).num_days() as u64 + 1), first, cal)
685    };
686    let need_n = || match n {
687        Some(n) if n > 0 => Ok(n),
688        _ => Err(format!(
689            "period('{name}') needs a positive `n`, e.g. period('{name}', n=7)"
690        )),
691    };
692    let bad = || "date out of range".to_string();
693    Ok(match name {
694        "today" => Period::of(Kind::Day, d, cal),
695        "yesterday" => Period::of(Kind::Day, d.pred_opt().ok_or_else(bad)?, cal),
696        "this_week" => Period::of(Kind::Week, week, cal),
697        "last_week" => Period::of(Kind::Week, week - Days::new(7), cal),
698        "this_month" => Period::of(Kind::Month, month_start(d), cal),
699        "last_month" => Period::of(Kind::Month, add_months(month_start(d), -1).ok_or_else(bad)?, cal),
700        "mtd" => range(month_start(d), d),
701        "this_quarter" => Period::of(Kind::Quarter, quarter_start(d), cal),
702        "last_quarter" => Period::of(
703            Kind::Quarter,
704            add_months(quarter_start(d), -3).ok_or_else(bad)?,
705            cal,
706        ),
707        "qtd" => range(quarter_start(d), d),
708        "this_year" => Period::of(Kind::Year, year_start(d), cal),
709        "last_year" => Period::of(Kind::Year, add_months(year_start(d), -12).ok_or_else(bad)?, cal),
710        "ytd" => range(year_start(d), d),
711        "last_n_days" => {
712            let n = need_n()?;
713            range(add_days(d, -n).ok_or_else(bad)?, d.pred_opt().ok_or_else(bad)?)
714        }
715        "last_n_months" => {
716            let n = need_n()?;
717            let first = add_months(month_start(d), -n).ok_or_else(bad)?;
718            range(first, month_start(d).pred_opt().ok_or_else(bad)?)
719        }
720        _ => {
721            return Err(format!(
722                "period('{name}'): unknown period; use one of {}",
723                PERIOD_PRESETS.join(", ")
724            ));
725        }
726    })
727}
728
729/// Add `date()`, `datetime()`, `period()`, `date_range()`, `month_of()`, `quarter_of()`,
730/// `year_of()`, `week_of()` and the `as_date` / `as_datetime` filters. `run_date` is what
731/// `period()` counts from by default.
732pub fn register(env: &mut Environment<'static>, cal: Calendar, run_date: NaiveDate) {
733    env.add_function(
734        "period",
735        move |name: String, kwargs: Kwargs| -> Result<Value, Error> {
736            let as_of: Option<Value> = kwargs.get("as_of")?;
737            let n: Option<i64> = kwargs.get("n")?;
738            kwargs.assert_all_used()?;
739            let d = match as_of {
740                Some(v) => to_date(&v, cal)?,
741                None => run_date,
742            };
743            Ok(Period::value(preset(&name, d, n, cal).map_err(err)?))
744        },
745    );
746    env.add_function(
747        "date",
748        move |a: Value, m: Option<u32>, d: Option<u32>| -> Result<Value, Error> {
749            match (m, d) {
750                (Some(m), Some(d)) => {
751                    let y =
752                        i32::try_from(a).map_err(|_| err("date(year, month, day) takes three numbers"))?;
753                    Ok(Date::value(ymd(y, m, d)?, cal))
754                }
755                (None, None) => Ok(Date::value(to_date(&a, cal)?, cal)),
756                _ => Err(err("date() takes a `YYYY-MM-DD` string or (year, month, day)")),
757            }
758        },
759    );
760    env.add_function("datetime", move |a: Value| -> Result<Value, Error> {
761        Ok(DateTime::value(to_datetime(&a, cal)?, cal))
762    });
763    env.add_filter("as_date", move |a: Value| -> Result<Value, Error> {
764        Ok(Date::value(to_date(&a, cal)?, cal))
765    });
766    env.add_filter("as_datetime", move |a: Value| -> Result<Value, Error> {
767        Ok(DateTime::value(to_datetime(&a, cal)?, cal))
768    });
769    env.add_function("date_range", move |a: Value, b: Value| -> Result<Value, Error> {
770        let (first, last) = (to_date(&a, cal)?, to_date(&b, cal)?);
771        if last < first {
772            return Err(err(format!(
773                "date_range({first}, {last}): the end is before the start"
774            )));
775        }
776        let n = (last - first).num_days() as u64 + 1;
777        Ok(Period::value(Period::of(Kind::Days(n), first, cal)))
778    });
779    env.add_function("month_of", move |y: i32, m: u32| -> Result<Value, Error> {
780        Ok(Period::value(Period::of(Kind::Month, ymd(y, m, 1)?, cal)))
781    });
782    env.add_function("quarter_of", move |y: i32, q: u32| -> Result<Value, Error> {
783        if !(1..=4).contains(&q) {
784            return Err(err(format!("quarter_of({y}, {q}): the quarter must be 1 to 4")));
785        }
786        Ok(Period::value(Period::of(
787            Kind::Quarter,
788            ymd(y, (q - 1) * 3 + 1, 1)?,
789            cal,
790        )))
791    });
792    env.add_function("year_of", move |y: i32| -> Result<Value, Error> {
793        Ok(Period::value(Period::of(Kind::Year, ymd(y, 1, 1)?, cal)))
794    });
795    env.add_function("week_of", move |y: i32, w: u32| -> Result<Value, Error> {
796        Ok(Period::value(Period::of(
797            Kind::Week,
798            cal.week_of(y, w).map_err(err)?,
799            cal,
800        )))
801    });
802}
803
804#[cfg(test)]
805mod tests {
806    use super::*;
807
808    fn cal(tz: &str) -> Calendar {
809        Calendar {
810            tz: parse_tz(tz).unwrap(),
811            ..Calendar::default()
812        }
813    }
814
815    fn render_with(c: Calendar, today: &str, src: &str) -> String {
816        let mut env = Environment::new();
817        env.set_undefined_behavior(minijinja::UndefinedBehavior::Strict);
818        let today = parse_date(today).unwrap();
819        register(&mut env, c, today);
820        let d = Date::value(today, c);
821        env.render_str(src, minijinja::context! { d => d })
822            .unwrap_or_else(|e| format!("ERROR: {e:#}"))
823    }
824
825    fn render(today: &str, src: &str) -> String {
826        render_with(Calendar::default(), today, src)
827    }
828
829    #[test]
830    fn date_navigation_table() {
831        let cases = [
832            ("2026-03-15", "{{ d }}", "2026-03-15"),
833            (
834                "2026-03-15",
835                "{{ d.prev_day }} {{ d.next_day }}",
836                "2026-03-14 2026-03-16",
837            ),
838            ("2026-03-01", "{{ d.prev_day }}", "2026-02-28"),
839            ("2024-03-01", "{{ d.prev_day }}", "2024-02-29"),
840            ("2026-01-31", "{{ d.add(months=1) }}", "2026-02-28"),
841            ("2024-01-31", "{{ d.add(months=1) }}", "2024-02-29"),
842            (
843                "2024-02-29",
844                "{{ d.add(years=1) }} {{ d.add(years=-4) }}",
845                "2025-02-28 2020-02-29",
846            ),
847            (
848                "2026-03-15",
849                "{{ d.add(days=-15) }} {{ d.add(weeks=2) }}",
850                "2026-02-28 2026-03-29",
851            ),
852            (
853                "2026-03-15",
854                "{{ d.month_start }} {{ d.month_end }}",
855                "2026-03-01 2026-03-31",
856            ),
857            (
858                "2026-02-10",
859                "{{ d.month_end }} {{ d.days_in_month }}",
860                "2026-02-28 28",
861            ),
862            (
863                "2026-05-20",
864                "{{ d.quarter }} {{ d.quarter_start }} {{ d.quarter_end }}",
865                "2 2026-04-01 2026-06-30",
866            ),
867            (
868                "2026-05-20",
869                "{{ d.year_start }} {{ d.year_end }} {{ d.day_of_year }}",
870                "2026-01-01 2026-12-31 140",
871            ),
872            // 2026-03-15 is a Sunday.
873            (
874                "2026-03-15",
875                "{{ d.weekday }} {{ d.week_start }} {{ d.week_end }}",
876                "7 2026-03-09 2026-03-15",
877            ),
878            (
879                "2026-03-15",
880                "{{ d.year }}-{{ d.month }}-{{ d.day }}",
881                "2026-3-15",
882            ),
883            (
884                "2026-03-15",
885                "{{ d.yyyymmdd }} {{ d.ddmmyyyy }} {{ d.yyyy }}{{ d.mm }}{{ d.dd }} {{ d.iso }}",
886                "20260315 15032026 20260315 2026-03-15",
887            ),
888            ("2026-03-15", "{{ d.format('%d/%m/%Y') }}", "15/03/2026"),
889        ];
890        for (today, src, want) in cases {
891            assert_eq!(render(today, src), want, "{src} on {today}");
892        }
893    }
894
895    #[test]
896    fn periods_table() {
897        let p = |x: &str| format!("{{{{ {x}.start.date }}}}..{{{{ {x}.end.date }}}} {{{{ {x}.days }}}}");
898        let cases = [
899            ("2026-03-15", p("d.prev_month"), "2026-02-01..2026-02-28 28"),
900            ("2026-01-10", p("d.prev_month"), "2025-12-01..2025-12-31 31"),
901            ("2026-12-10", p("d.next_month"), "2027-01-01..2027-01-31 31"),
902            ("2026-03-15", p("d.this_month"), "2026-03-01..2026-03-31 31"),
903            ("2026-02-15", p("d.prev_quarter"), "2025-10-01..2025-12-31 92"),
904            ("2026-02-15", p("d.next_quarter"), "2026-04-01..2026-06-30 91"),
905            ("2026-02-15", p("d.prev_year"), "2025-01-01..2025-12-31 365"),
906            ("2024-02-15", p("d.this_year"), "2024-01-01..2024-12-31 366"),
907            ("2026-03-15", p("d.prev_week"), "2026-03-02..2026-03-08 7"),
908            ("2026-03-15", p("d.next_week"), "2026-03-16..2026-03-22 7"),
909            ("2026-03-15", p("d.as_period()"), "2026-03-15..2026-03-15 1"),
910            ("2026-03-15", p("d.prev_month.prev"), "2026-01-01..2026-01-31 31"),
911            ("2026-03-15", p("d.prev_month.next"), "2026-03-01..2026-03-31 31"),
912            ("2026-03-15", p("month_of(2024, 2)"), "2024-02-01..2024-02-29 29"),
913            (
914                "2026-03-15",
915                p("quarter_of(2026, 4)"),
916                "2026-10-01..2026-12-31 92",
917            ),
918            ("2026-03-15", p("year_of(2025)"), "2025-01-01..2025-12-31 365"),
919            (
920                "2026-03-15",
921                p("date_range('2026-01-05', '2026-01-11').next"),
922                "2026-01-12..2026-01-18 7",
923            ),
924            ("2026-03-15", "{{ d.prev_month }}".into(), "2026-02-01/2026-02-28"),
925            (
926                "2026-03-15",
927                "{{ d.prev_month.start }} {{ d.prev_month.end }}".into(),
928                "2026-02-01 00:00:00 2026-02-28 23:59:59.999999",
929            ),
930            (
931                "2026-03-15",
932                "{{ d.prev_month.next.start }}".into(),
933                "2026-03-01 00:00:00",
934            ),
935            (
936                "2026-03-15",
937                "{{ d.prev_month.first_day }} {{ d.prev_month.last_day }}".into(),
938                "2026-02-01 2026-02-28",
939            ),
940        ];
941        for (today, src, want) in cases {
942            assert_eq!(render(today, &src), want, "{src} on {today}");
943        }
944    }
945
946    #[test]
947    fn iso_and_us_week_numbers() {
948        let iso = Calendar::default();
949        let us = Calendar {
950            week_start: WeekStart::Sunday,
951            numbering: WeekNumbering::Us,
952            ..Calendar::default()
953        };
954        let w = "{{ d.week_year }}-W{{ d.week }}";
955        // ISO: 2021-01-03 (Sunday) is in 2020's week 53; 2024-12-30 is in 2025's week 1.
956        assert_eq!(render_with(iso, "2021-01-03", w), "2020-W53");
957        assert_eq!(render_with(iso, "2021-01-04", w), "2021-W1");
958        assert_eq!(render_with(iso, "2024-12-30", w), "2025-W1");
959        // US: the week holding 1 January is week 1, weeks start on Sunday.
960        assert_eq!(render_with(us, "2021-01-02", w), "2021-W1");
961        assert_eq!(render_with(us, "2021-01-03", w), "2021-W2");
962        assert_eq!(render_with(us, "2024-12-31", w), "2024-W53");
963        let wk = "{{ week_of(2026, 1).start.date }} {{ week_of(2026, 1).end.date }}";
964        assert_eq!(render_with(iso, "2026-03-15", wk), "2025-12-29 2026-01-04");
965        assert_eq!(render_with(us, "2026-03-15", wk), "2025-12-28 2026-01-03");
966        assert_eq!(
967            render_with(iso, "2026-03-15", "{{ week_of(2020, 53).start.date }}"),
968            "2020-12-28"
969        );
970        assert!(render_with(iso, "2026-03-15", "{{ week_of(2021, 53) }}").starts_with("ERROR"));
971        // Sunday weeks move week_start/week_end and week periods.
972        assert_eq!(
973            render_with(
974                us,
975                "2026-03-18",
976                "{{ d.week_start }} {{ d.week_end }} {{ d.prev_week.start.date }}"
977            ),
978            "2026-03-15 2026-03-21 2026-03-08"
979        );
980    }
981
982    #[test]
983    fn constructors_and_errors() {
984        assert_eq!(
985            render(
986                "2026-03-15",
987                "{{ date('2026-07-04') }} {{ date(2026, 7, 4).weekday }}"
988            ),
989            "2026-07-04 6"
990        );
991        assert_eq!(
992            render("2026-03-15", "{{ ('2026-07-04' | as_date).month_end }}"),
993            "2026-07-31"
994        );
995        assert_eq!(render("2026-03-15", "{{ '20260704' | as_date }}"), "2026-07-04");
996        assert!(render("2026-03-15", "{{ date('2026-02-30') }}").contains("isn't a date"));
997        assert!(render("2026-03-15", "{{ date(2026, 2, 30) }}").contains("isn't a date"));
998        assert!(render("2026-03-15", "{{ 'soon' | as_date }}").contains("isn't a date"));
999        assert!(render("2026-03-15", "{{ quarter_of(2026, 5) }}").contains("1 to 4"));
1000        assert!(
1001            render("2026-03-15", "{{ date_range('2026-02-01', '2026-01-01') }}").contains("before the start")
1002        );
1003        assert!(render("2026-03-15", "{{ d.add(fortnights=1) }}").starts_with("ERROR"));
1004        assert!(render("2026-03-15", "{{ d.nope }}").starts_with("ERROR"));
1005    }
1006
1007    #[test]
1008    fn datetimes_timezones_and_unix() {
1009        let syd = cal("Australia/Sydney");
1010        // Sydney is UTC+11 in March (daylight time).
1011        assert_eq!(
1012            render_with(
1013                syd,
1014                "2026-03-15",
1015                "{{ d.start }} | {{ d.start.utc }} | {{ d.start.iso }}"
1016            ),
1017            "2026-03-15 00:00:00 | 2026-03-14 13:00:00 | 2026-03-15T00:00:00+11:00"
1018        );
1019        assert_eq!(
1020            render_with(
1021                syd,
1022                "2026-03-15",
1023                "{{ d.unix }} {{ d.start.unix }} {{ d.start.utc.unix }} {{ d.unix_ms }}"
1024            ),
1025            "1773493200 1773493200 1773493200 1773493200000"
1026        );
1027        assert_eq!(render("2026-03-15", "{{ d.unix }}"), "1773532800");
1028        assert_eq!(
1029            render_with(syd, "2026-03-15", "{{ d.end.iso }}"),
1030            "2026-03-15T23:59:59.999999+11:00"
1031        );
1032        assert_eq!(
1033            render_with(
1034                syd,
1035                "2026-03-15",
1036                "{{ d.start.tz('Europe/London') }} {{ d.start.tz('Europe/London').offset }}"
1037            ),
1038            "2026-03-14 13:00:00 +00:00"
1039        );
1040        assert!(render_with(syd, "2026-03-15", "{{ d.start.tz('Mars/Base') }}").contains("isn't a timezone"));
1041        // 2026-04-05: Sydney leaves daylight time at 03:00, so the day has 25 hours.
1042        assert_eq!(
1043            render_with(
1044                syd,
1045                "2026-04-05",
1046                "{{ d.end.unix - d.start.unix + 1 }} {{ d.next_day.start.iso }}"
1047            ),
1048            "90000 2026-04-06T00:00:00+10:00"
1049        );
1050        // Datetime strings: in the run zone unless they carry an offset.
1051        assert_eq!(
1052            render_with(syd, "2026-03-15", "{{ datetime('2026-03-15 10:30:00').utc }}"),
1053            "2026-03-14 23:30:00"
1054        );
1055        assert_eq!(
1056            render_with(syd, "2026-03-15", "{{ datetime('2026-03-15T10:30:00Z') }}"),
1057            "2026-03-15 21:30:00"
1058        );
1059        assert_eq!(
1060            render_with(syd, "2026-03-15", "{{ datetime('2026-03-15 10:30:00.25').time }}"),
1061            "10:30:00.250000"
1062        );
1063        assert_eq!(
1064            render_with(
1065                syd,
1066                "2026-03-15",
1067                "{{ ('2026-03-15 10:30' | as_datetime).add(hours=2, days=1) }}"
1068            ),
1069            "2026-03-16 12:30:00"
1070        );
1071        assert_eq!(
1072            render_with(
1073                syd,
1074                "2026-03-15",
1075                "{{ datetime('2026-03-15 10:30').format('%H%M') }} {{ datetime('2026-03-15 10:30').date.prev_day }}"
1076            ),
1077            "1030 2026-03-14"
1078        );
1079        assert!(render_with(syd, "2026-03-15", "{{ datetime('later') }}").contains("isn't a date and time"));
1080    }
1081
1082    #[test]
1083    fn period_presets() {
1084        let p = |x: &str| format!("{{% set p = {x} %}}{{{{ p.start.date }}}}..{{{{ p.end.date }}}}");
1085        // 2026-03-18 is a Wednesday.
1086        let cases = [
1087            ("period('today')", "2026-03-18..2026-03-18"),
1088            ("period('yesterday')", "2026-03-17..2026-03-17"),
1089            ("period('this_week')", "2026-03-16..2026-03-22"),
1090            ("period('last_week')", "2026-03-09..2026-03-15"),
1091            ("period('this_month')", "2026-03-01..2026-03-31"),
1092            ("period('last_month')", "2026-02-01..2026-02-28"),
1093            ("period('mtd')", "2026-03-01..2026-03-18"),
1094            ("period('this_quarter')", "2026-01-01..2026-03-31"),
1095            ("period('last_quarter')", "2025-10-01..2025-12-31"),
1096            ("period('qtd')", "2026-01-01..2026-03-18"),
1097            ("period('this_year')", "2026-01-01..2026-12-31"),
1098            ("period('last_year')", "2025-01-01..2025-12-31"),
1099            ("period('ytd')", "2026-01-01..2026-03-18"),
1100            ("period('last_n_days', n=7)", "2026-03-11..2026-03-17"),
1101            ("period('last_n_months', n=3)", "2025-12-01..2026-02-28"),
1102            // Year boundary, and an explicit as_of.
1103            (
1104                "period('last_month', as_of='2026-01-10')",
1105                "2025-12-01..2025-12-31",
1106            ),
1107            ("period('ytd', as_of=date(2026, 1, 1))", "2026-01-01..2026-01-01"),
1108            (
1109                "period('last_week', as_of='2026-01-01')",
1110                "2025-12-22..2025-12-28",
1111            ),
1112        ];
1113        for (x, want) in cases {
1114            assert_eq!(render("2026-03-18", &p(x)), want, "{x}");
1115        }
1116        let e = render("2026-03-18", "{{ period('fortnight') }}");
1117        assert!(e.contains("unknown period; use one of today, yesterday"), "{e}");
1118        assert!(render("2026-03-18", "{{ period('last_n_days') }}").contains("needs a positive `n`"));
1119        assert!(render("2026-03-18", "{{ period('last_n_days', n=0) }}").contains("needs a positive `n`"));
1120    }
1121
1122    #[test]
1123    fn datetime_add_across_daylight_saving_changes() {
1124        let ny = cal("America/New_York");
1125        // 2026-03-08 02:30 doesn't exist in New York: the clocks skip from 02:00 to 03:00.
1126        assert_eq!(
1127            render_with(
1128                ny,
1129                "2026-03-07",
1130                "{{ datetime('2026-03-07 02:30').add(days=1).iso }}"
1131            ),
1132            "2026-03-08T03:30:00-04:00"
1133        );
1134        // 2026-11-01 01:30 happens twice; an hour after the first is the second.
1135        assert_eq!(
1136            render_with(
1137                ny,
1138                "2026-11-01",
1139                "{% set t = datetime('2026-11-01 01:30') %}{{ t.iso }} {{ t.add(hours=1).iso }} {{ t.add(hours=1).unix - t.unix }}"
1140            ),
1141            "2026-11-01T01:30:00-04:00 2026-11-01T01:30:00-05:00 3600"
1142        );
1143        // A day later from the second 01:30 keeps the clock time.
1144        assert_eq!(
1145            render_with(
1146                ny,
1147                "2026-11-01",
1148                "{{ datetime('2026-11-01 01:30').add(hours=1).add(days=1).iso }}"
1149            ),
1150            "2026-11-02T01:30:00-05:00"
1151        );
1152    }
1153
1154    #[test]
1155    fn dst_gap_starts_at_first_valid_instant() {
1156        // Santiago springs forward at midnight: 2026-09-06 begins at 01:00.
1157        let c = cal("America/Santiago");
1158        assert_eq!(
1159            render_with(c, "2026-09-06", "{{ d.start }}"),
1160            "2026-09-06 01:00:00"
1161        );
1162    }
1163
1164    #[test]
1165    fn now_renders_in_the_run_zone() {
1166        let at = Utc.with_ymd_and_hms(2026, 3, 14, 20, 0, 0).unwrap();
1167        let v = DateTime::now(at, cal("Australia/Sydney"));
1168        assert_eq!(v.to_string(), "2026-03-15 07:00:00");
1169    }
1170}