ocpi_tariffs/
datetime.rs

1//! Timestamps are formatted as a string with a max length of 25 chars. Each timestamp follows RFC 3339,
2//! with some additional limitations. All timestamps are expected to be in UTC. The absence of the
3//! timezone designator implies a UTC timestamp. Fractional seconds may be used.
4//!
5//! # Examples
6//!
7//! Example of how timestamps should be formatted in OCPI, other formats/patterns are not allowed:
8//!
9//! - `"2015-06-29T20:39:09Z"`
10//! - `"2015-06-29T20:39:09"`
11//! - `"2016-12-29T17:45:09.2Z"`
12//! - `"2016-12-29T17:45:09.2"`
13//! - `"2018-01-01T01:08:01.123Z"`
14//! - `"2018-01-01T01:08:01.123"`
15
16use std::fmt;
17
18use chrono::{DateTime, NaiveDateTime, TimeZone as _, Utc};
19
20use crate::{
21    into_caveat, into_caveat_all, json,
22    warning::{self, GatherWarnings as _},
23    IntoCaveat, Verdict,
24};
25
26/// The warnings that can happen when parsing or linting a `NaiveDate`, `NaiveTime`, or `DateTime`.
27#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
28pub enum WarningKind {
29    /// The datetime does not need to contain escape codes.
30    ContainsEscapeCodes,
31
32    /// The field at the path could not be decoded.
33    Decode(json::decode::WarningKind),
34
35    /// The datetime is not valid.
36    ///
37    /// Timestamps are formatted as a string with a max length of 25 chars. Each timestamp follows RFC 3339,
38    /// with some additional limitations. All timestamps are expected to be in UTC. The absence of the
39    /// timezone designator implies a UTC timestamp. Fractional seconds may be used.
40    ///
41    /// # Examples
42    ///
43    /// Example of how timestamps should be formatted in OCPI, other formats/patterns are not allowed:
44    ///
45    /// - `"2015-06-29T20:39:09Z"`
46    /// - `"2015-06-29T20:39:09"`
47    /// - `"2016-12-29T17:45:09.2Z"`
48    /// - `"2016-12-29T17:45:09.2"`
49    /// - `"2018-01-01T01:08:01.123Z"`
50    /// - `"2018-01-01T01:08:01.123"`
51    Invalid(String),
52
53    /// The JSON value given is not a string.
54    InvalidType,
55}
56
57impl fmt::Display for WarningKind {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        match self {
60            WarningKind::ContainsEscapeCodes => write!(f, "contains_escape_codes"),
61            WarningKind::Decode(warning) => fmt::Display::fmt(warning, f),
62            WarningKind::Invalid(_) => write!(f, "invalid"),
63            WarningKind::InvalidType => write!(f, "invalid_type"),
64        }
65    }
66}
67
68impl warning::Kind for WarningKind {
69    fn id(&self) -> std::borrow::Cow<'static, str> {
70        match self {
71            WarningKind::ContainsEscapeCodes => "contains_escape_codes".into(),
72            WarningKind::Decode(kind) => kind.id(),
73            WarningKind::Invalid(_) => "invalid".into(),
74            WarningKind::InvalidType => "invalid_type".into(),
75        }
76    }
77}
78
79impl From<json::decode::WarningKind> for WarningKind {
80    fn from(warn_kind: json::decode::WarningKind) -> Self {
81        Self::Decode(warn_kind)
82    }
83}
84
85into_caveat!(DateTime<Utc>);
86into_caveat_all!(chrono::NaiveTime, chrono::NaiveDate);
87
88impl json::FromJson<'_, '_> for DateTime<Utc> {
89    type WarningKind = WarningKind;
90
91    fn from_json(elem: &json::Element<'_>) -> Verdict<Self, Self::WarningKind> {
92        let mut warnings = warning::Set::new();
93        let Some(s) = elem.as_raw_str() else {
94            return warnings.bail(WarningKind::InvalidType, elem);
95        };
96
97        let pending_str = s.has_escapes(elem).gather_warnings_into(&mut warnings);
98
99        let s = match pending_str {
100            json::decode::PendingStr::NoEscapes(s) => s,
101            json::decode::PendingStr::HasEscapes(_) => {
102                return warnings.bail(WarningKind::ContainsEscapeCodes, elem);
103            }
104        };
105
106        // First try parsing with a timezone, if that doesn't work try to parse without
107        let err = match s.parse::<DateTime<Utc>>() {
108            Ok(date) => return Ok(date.into_caveat(warnings)),
109            Err(err) => err,
110        };
111
112        let Ok(date) = s.parse::<NaiveDateTime>() else {
113            return warnings.bail(WarningKind::Invalid(err.to_string()), elem);
114        };
115
116        let datetime = Utc.from_utc_datetime(&date);
117        Ok(datetime.into_caveat(warnings))
118    }
119}
120
121impl json::FromJson<'_, '_> for chrono::NaiveDate {
122    type WarningKind = WarningKind;
123
124    fn from_json(elem: &json::Element<'_>) -> Verdict<Self, Self::WarningKind> {
125        let mut warnings = warning::Set::new();
126        let Some(s) = elem.as_raw_str() else {
127            return warnings.bail(WarningKind::InvalidType, elem);
128        };
129
130        let pending_str = s.has_escapes(elem).gather_warnings_into(&mut warnings);
131
132        let s = match pending_str {
133            json::decode::PendingStr::NoEscapes(s) => s,
134            json::decode::PendingStr::HasEscapes(_) => {
135                return warnings.bail(WarningKind::ContainsEscapeCodes, elem);
136            }
137        };
138
139        let date = match s.parse::<chrono::NaiveDate>() {
140            Ok(v) => v,
141            Err(err) => {
142                return warnings.bail(WarningKind::Invalid(err.to_string()), elem);
143            }
144        };
145
146        Ok(date.into_caveat(warnings))
147    }
148}
149
150impl json::FromJson<'_, '_> for chrono::NaiveTime {
151    type WarningKind = WarningKind;
152
153    fn from_json(elem: &json::Element<'_>) -> Verdict<Self, Self::WarningKind> {
154        let mut warnings = warning::Set::new();
155        let value = elem.as_value();
156
157        let Some(s) = value.as_raw_str() else {
158            return warnings.bail(WarningKind::InvalidType, elem);
159        };
160
161        let pending_str = s.has_escapes(elem).gather_warnings_into(&mut warnings);
162
163        let s = match pending_str {
164            json::decode::PendingStr::NoEscapes(s) => s,
165            json::decode::PendingStr::HasEscapes(_) => {
166                return warnings.bail(WarningKind::ContainsEscapeCodes, elem);
167            }
168        };
169
170        let date = match chrono::NaiveTime::parse_from_str(s, "%H:%M") {
171            Ok(v) => v,
172            Err(err) => {
173                return warnings.bail(WarningKind::Invalid(err.to_string()), elem);
174            }
175        };
176
177        Ok(date.into_caveat(warnings))
178    }
179}
180
181#[cfg(test)]
182pub mod test {
183    use chrono::{DateTime, NaiveDateTime, TimeZone as _, Utc};
184
185    use crate::test::ApproxEq;
186
187    impl ApproxEq for DateTime<Utc> {
188        fn approx_eq(&self, other: &Self) -> bool {
189            /// Use a tolerance of 2 second when comparing `DateTime` amounts.
190            const EQ_TOLERANCE: i64 = 2;
191
192            let diff = *self - *other;
193            diff.num_seconds().abs() <= EQ_TOLERANCE
194        }
195    }
196
197    /// Deserialize an OCPI date as string into a `DateTime<Utc>`.
198    pub fn deser_to_utc<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
199    where
200        D: serde::Deserializer<'de>,
201    {
202        use serde::Deserialize;
203
204        let date_string = String::deserialize(deserializer)?;
205
206        // First try parsing with a timezone, if that doesn't work try to parse without
207        let err = match date_string.parse::<DateTime<Utc>>() {
208            Ok(date) => return Ok(date),
209            Err(err) => err,
210        };
211
212        if let Ok(date) = date_string.parse::<NaiveDateTime>() {
213            Ok(Utc.from_utc_datetime(&date))
214        } else {
215            Err(serde::de::Error::custom(err))
216        }
217    }
218}
219
220#[cfg(test)]
221mod test_datetime_from_json {
222    #![allow(
223        clippy::unwrap_in_result,
224        reason = "unwraps are allowed anywhere in tests"
225    )]
226
227    use assert_matches::assert_matches;
228    use chrono::{DateTime, TimeZone, Utc};
229
230    use crate::{
231        json::{self, FromJson as _},
232        Verdict,
233    };
234
235    use super::WarningKind;
236
237    #[track_caller]
238    fn parse_timestamp_from_json(json: &'static str) -> Verdict<DateTime<Utc>, WarningKind> {
239        let elem = json::parse(json).unwrap();
240        let date_time_time = elem.find_field("start_date_time").unwrap();
241        DateTime::<Utc>::from_json(date_time_time.element())
242    }
243
244    #[test]
245    fn should_parse_utc_datetime() {
246        const JSON: &str = r#"{ "start_date_time": "2015-06-29T22:39:09Z" }"#;
247
248        let (datetime, warnings) = parse_timestamp_from_json(JSON).unwrap().into_parts();
249        assert_matches!(*warnings, []);
250        assert_eq!(
251            datetime,
252            Utc.with_ymd_and_hms(2015, 6, 29, 22, 39, 9).unwrap()
253        );
254    }
255
256    #[test]
257    fn should_parse_timezone_to_utc() {
258        const JSON: &str = r#"{ "start_date_time": "2015-06-29T22:39:09+02:00" }"#;
259
260        let (datetime, warnings) = parse_timestamp_from_json(JSON).unwrap().into_parts();
261        assert_matches!(*warnings, []);
262        assert_eq!(
263            datetime,
264            Utc.with_ymd_and_hms(2015, 6, 29, 20, 39, 9).unwrap()
265        );
266    }
267
268    #[test]
269    fn should_parse_timezone_naive_to_utc() {
270        // This is a mess, but unfortunately OCPI 2.1.1 and 2.2 specify that datetimes without any
271        // timezone specification are also allowed
272        const JSON: &str = r#"{ "start_date_time": "2015-06-29T22:39:09" }"#;
273
274        let (datetime, warnings) = parse_timestamp_from_json(JSON).unwrap().into_parts();
275        assert_matches!(*warnings, []);
276
277        assert_eq!(
278            datetime,
279            Utc.with_ymd_and_hms(2015, 6, 29, 22, 39, 9).unwrap()
280        );
281    }
282}