Skip to main content

ocpi_tariffs/
timezone.rs

1//! Parse an IANA Timezone from JSON or find a timezone in a CDR.
2#[cfg(test)]
3pub mod test;
4
5#[cfg(test)]
6mod test_find_or_infer;
7
8use std::{borrow::Cow, fmt};
9
10use chrono_tz::Tz;
11use tracing::{debug, instrument};
12
13use crate::{
14    cdr, country, from_warning_all, into_caveat_all,
15    json::{self, FieldsAsExt as _, FromJson as _},
16    warning::{self, GatherWarnings as _},
17    IntoCaveat, ParseError, Verdict, Version, Versioned,
18};
19
20/// The warnings possible when parsing or linting an IANA timezone.
21#[derive(Debug)]
22pub enum Warning {
23    /// A timezone can't be inferred from the `location`'s `country`.
24    CantInferTimezoneFromCountry(&'static str),
25
26    /// Neither the timezone or country field require char escape codes.
27    ContainsEscapeCodes,
28
29    /// The CDR location is not a valid ISO 3166-1 alpha-3 code.
30    Country(country::Warning),
31
32    /// The field at the path could not be decoded.
33    Decode(json::decode::Warning),
34
35    /// An error occurred while deserializing the `CDR`.
36    Deserialize(ParseError),
37
38    /// The CDR location is not a String.
39    InvalidLocationType,
40
41    /// The CDR location did not contain a valid IANA time-zone.
42    ///
43    /// See: <https://www.iana.org/time-zones>.
44    InvalidTimezone,
45
46    /// The CDR timezone is not a String.
47    InvalidTimezoneType,
48
49    /// The `location.country` field should be an alpha-3 country code.
50    ///
51    /// The alpha-2 code can be converted into an alpha-3 but the caller should be warned.
52    LocationCountryShouldBeAlpha3,
53
54    /// The CDR's `location` has no `country` element and so the timezone can't be inferred.
55    NoLocationCountry,
56
57    /// The CDR has no `location` element and so the timezone can't be found or inferred.
58    NoLocation,
59
60    /// An `Error` occurred while parsing the JSON or deferred JSON String decode.
61    Parser(json::Error),
62
63    /// Both the CDR and tariff JSON should be an Object.
64    ShouldBeAnObject,
65
66    /// A v221 CDR is given but it contains a `location` field instead of a `cdr_location` as defined in the spec.
67    V221CdrHasLocationField,
68}
69
70from_warning_all!(
71    country::Warning => Warning::Country,
72    json::decode::Warning => Warning::Decode
73);
74
75impl fmt::Display for Warning {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        match self {
78            Self::CantInferTimezoneFromCountry(country_code) => write!(f, "Unable to infer timezone from the `location`'s `country`: `{country_code}`"),
79            Self::ContainsEscapeCodes => f.write_str("The CDR location contains needless escape codes."),
80            Self::Country(kind) => fmt::Display::fmt(kind, f),
81            Self::Decode(warning) => fmt::Display::fmt(warning, f),
82            Self::Deserialize(err) => fmt::Display::fmt(err, f),
83            Self::InvalidLocationType => f.write_str("The CDR location is not a String."),
84            Self::InvalidTimezone => f.write_str("The CDR location did not contain a valid IANA time-zone."),
85            Self::InvalidTimezoneType => f.write_str("The CDR timezone is not a String."),
86            Self::LocationCountryShouldBeAlpha3 => f.write_str("The `location.country` field should be an alpha-3 country code."),
87            Self::NoLocationCountry => {
88                f.write_str("The CDR's `location` has no `country` element and so the timezone can't be inferred.")
89            },
90            Self::NoLocation => {
91                f.write_str("The CDR has no `location` element and so the timezone can't be found or inferred.")                   
92            }
93            Self::Parser(err) => fmt::Display::fmt(err, f),
94            Self::ShouldBeAnObject => f.write_str("The CDR should be a JSON object"),
95            Self::V221CdrHasLocationField => f.write_str("the v2.2.1 CDR contains a `location` field but the v2.2.1 spec defines a `cdr_location` field."),
96
97        }
98    }
99}
100
101impl crate::Warning for Warning {
102    fn id(&self) -> warning::Id {
103        match self {
104            Self::CantInferTimezoneFromCountry(_) => {
105                warning::Id::from_static("cant_infer_timezone_from_country")
106            }
107            Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
108            Self::Decode(warning) => warning.id(),
109            Self::Deserialize(err) => warning::Id::from_string(format!("deserialize.{err}")),
110            Self::Country(warning) => warning.id(),
111            Self::InvalidLocationType => warning::Id::from_static("invalid_location_type"),
112            Self::InvalidTimezone => warning::Id::from_static("invalid_timezone"),
113            Self::InvalidTimezoneType => warning::Id::from_static("invalid_timezone_type"),
114            Self::LocationCountryShouldBeAlpha3 => {
115                warning::Id::from_static("location_country_should_be_alpha3")
116            }
117            Self::NoLocationCountry => warning::Id::from_static("no_location_country"),
118            Self::NoLocation => warning::Id::from_static("no_location"),
119            Self::Parser(_err) => warning::Id::from_static("parser_error"),
120            Self::ShouldBeAnObject => warning::Id::from_static("should_be_an_object"),
121            Self::V221CdrHasLocationField => {
122                warning::Id::from_static("v221_cdr_has_location_field")
123            }
124        }
125    }
126}
127
128/// The source of the timezone
129#[derive(Copy, Clone, Debug)]
130pub enum Source {
131    /// The timezone was found in the `location` element.
132    Found(Tz),
133
134    /// The timezone is inferred from the `location`'s `country`.
135    Inferred(Tz),
136}
137
138into_caveat_all!(Source, Tz);
139
140impl Source {
141    /// Return the timezone and disregard where it came from.
142    pub fn into_timezone(self) -> Tz {
143        match self {
144            Source::Found(tz) | Source::Inferred(tz) => tz,
145        }
146    }
147}
148
149/// Try to find or infer the timezone from the `CDR` JSON.
150///
151/// Return `Some` if the timezone can be found or inferred.
152/// Return `None` if the timezone is not found and can't be inferred.
153///
154/// Finding a timezone is an infallible operation. If invalid data is found a `None` is returned
155/// with an appropriate warning.
156///
157/// If the `CDR` contains a `time_zone` in the location object then that is simply returned.
158/// Only pre-v2.2.1 CDR's have a `time_zone` field in the `Location` object.
159///
160/// Inferring the timezone only works for `CDR`s from European countries.
161///
162pub fn find_or_infer(cdr: &cdr::Versioned<'_>) -> Verdict<Source, Warning> {
163    const LOCATION_FIELD_V211: &str = "location";
164    const LOCATION_FIELD_V221: &str = "cdr_location";
165    const TIMEZONE_FIELD: &str = "time_zone";
166    const COUNTRY_FIELD: &str = "country";
167
168    let mut warnings = warning::Set::new();
169
170    let cdr_root = cdr.as_element();
171    let Some(fields) = cdr_root.as_object_fields() else {
172        return warnings.bail(Warning::ShouldBeAnObject, cdr_root);
173    };
174
175    let cdr_fields = fields.as_raw_map();
176
177    let v211_location = cdr_fields.get(LOCATION_FIELD_V211);
178
179    // OCPI v221 changed the `location` field to `cdr_location`.
180    //
181    // * See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#131-cdr-object>
182    // * See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_cdrs.md#3-object-description>
183    if cdr.version() == Version::V221 && v211_location.is_some() {
184        warnings.insert(Warning::V221CdrHasLocationField, cdr_root);
185    }
186
187    // Describes the location that the charge-session took place at.
188    //
189    // The v211 CDR has a `location` field, while the v221 CDR has a `cdr_location` field.
190    //
191    // * See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#131-cdr-object>
192    // * See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_cdrs.md#3-object-description>
193    let Some(location_elem) = v211_location.or_else(|| cdr_fields.get(LOCATION_FIELD_V221)) else {
194        return warnings.bail(Warning::NoLocation, cdr_root);
195    };
196
197    let json::Value::Object(fields) = location_elem.as_value() else {
198        return warnings.bail(Warning::InvalidLocationType, cdr_root);
199    };
200
201    let location_fields = fields.as_raw_map();
202
203    debug!("Searching for time-zone in CDR");
204
205    // The `location::time_zone` field is optional in v211 and not defined in the v221 spec.
206    //
207    // See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#mod_cdrs_cdr_location_class>
208    // See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_locations.md#31-location-object>
209    let tz = location_fields
210        .get(TIMEZONE_FIELD)
211        .map(|elem| try_parse_location_timezone(elem).gather_warnings_into(&mut warnings))
212        .transpose();
213
214    // We first try to find/parse the timezone in the location object.
215    // If the timezone is not found there or there are any failures,
216    // The failures are deescalated to warnings.
217    let tz = tz
218        .map_err(|err_set| {
219            warnings.deescalate_error(err_set);
220        })
221        .ok()
222        .flatten();
223
224    if let Some(tz) = tz {
225        return Ok(Source::Found(tz).into_caveat(warnings));
226    }
227
228    debug!("No time-zone found in CDR; trying to infer time-zone from country");
229
230    // ISO 3166-1 alpha-3 code for the country of this location.
231    let Some(country_elem) = location_fields.get(COUNTRY_FIELD) else {
232        // The `location::country` field is required.
233        //
234        // See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#mod_cdrs_cdr_location_class>
235        // See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_locations.md#31-location-object>
236        return warnings.bail(Warning::NoLocationCountry, location_elem);
237    };
238    let tz =
239        infer_timezone_from_location_country(country_elem).gather_warnings_into(&mut warnings)?;
240
241    Ok(Source::Inferred(tz).into_caveat(warnings))
242}
243
244/// Try to parse the `location` element's timezone into a `Tz`.
245fn try_parse_location_timezone(tz_elem: &json::Element<'_>) -> Verdict<Tz, Warning> {
246    let tz = tz_elem.as_value();
247    debug!(tz = %tz, "Raw time-zone found in CDR");
248
249    let mut warnings = warning::Set::new();
250    let Some(tz) = tz.as_raw_str() else {
251        return warnings.bail(Warning::InvalidTimezoneType, tz_elem);
252    };
253
254    let tz = tz
255        .decode_escapes(tz_elem)
256        .gather_warnings_into(&mut warnings);
257
258    if matches!(tz, Cow::Owned(_)) {
259        warnings.insert(Warning::ContainsEscapeCodes, tz_elem);
260    }
261
262    debug!(%tz, "Escaped time-zone found in CDR");
263
264    let Ok(tz) = tz.parse::<Tz>() else {
265        return warnings.bail(Warning::InvalidTimezone, tz_elem);
266    };
267
268    Ok(tz.into_caveat(warnings))
269}
270
271/// Try to infer a timezone from the `location` elements `country` field.
272#[instrument(skip_all)]
273fn infer_timezone_from_location_country(country_elem: &json::Element<'_>) -> Verdict<Tz, Warning> {
274    let mut warnings = warning::Set::new();
275    let code_set = country::CodeSet::from_json(country_elem)?.gather_warnings_into(&mut warnings);
276
277    // The `location.country` field should be an alpha-3 country code.
278    //
279    // The alpha-2 code can be converted into an alpha-3 but the caller should be warned.
280    let country_code = match code_set {
281        country::CodeSet::Alpha2(code) => {
282            warnings.insert(Warning::LocationCountryShouldBeAlpha3, country_elem);
283            code
284        }
285        country::CodeSet::Alpha3(code) => code,
286    };
287    let Some(tz) = try_detect_timezone(country_code) else {
288        return warnings.bail(
289            Warning::CantInferTimezoneFromCountry(country_code.into_str()),
290            country_elem,
291        );
292    };
293
294    Ok(tz.into_caveat(warnings))
295}
296
297/// Mapping of European countries to time-zones with geographical naming
298///
299/// This is only possible for countries with a single time-zone and only for countries as they
300/// currently exist (2024). It's a best effort approach to determine a time-zone from just an
301/// ALPHA-3 ISO 3166-1 country code.
302///
303/// In small edge cases (e.g. Gibraltar) this detection might generate the wrong time-zone.
304#[instrument]
305fn try_detect_timezone(country_code: country::Code) -> Option<Tz> {
306    let tz = match country_code {
307        country::Code::Ad => Tz::Europe__Andorra,
308        country::Code::Al => Tz::Europe__Tirane,
309        country::Code::At => Tz::Europe__Vienna,
310        country::Code::Ba => Tz::Europe__Sarajevo,
311        country::Code::Be => Tz::Europe__Brussels,
312        country::Code::Bg => Tz::Europe__Sofia,
313        country::Code::By => Tz::Europe__Minsk,
314        country::Code::Ch => Tz::Europe__Zurich,
315        country::Code::Cy => Tz::Europe__Nicosia,
316        country::Code::Cz => Tz::Europe__Prague,
317        country::Code::De => Tz::Europe__Berlin,
318        country::Code::Dk => Tz::Europe__Copenhagen,
319        country::Code::Ee => Tz::Europe__Tallinn,
320        country::Code::Es => Tz::Europe__Madrid,
321        country::Code::Fi => Tz::Europe__Helsinki,
322        country::Code::Fr => Tz::Europe__Paris,
323        country::Code::Gb => Tz::Europe__London,
324        country::Code::Gr => Tz::Europe__Athens,
325        country::Code::Hr => Tz::Europe__Zagreb,
326        country::Code::Hu => Tz::Europe__Budapest,
327        country::Code::Ie => Tz::Europe__Dublin,
328        country::Code::Is => Tz::Iceland,
329        country::Code::It => Tz::Europe__Rome,
330        country::Code::Li => Tz::Europe__Vaduz,
331        country::Code::Lt => Tz::Europe__Vilnius,
332        country::Code::Lu => Tz::Europe__Luxembourg,
333        country::Code::Lv => Tz::Europe__Riga,
334        country::Code::Mc => Tz::Europe__Monaco,
335        country::Code::Md => Tz::Europe__Chisinau,
336        country::Code::Me => Tz::Europe__Podgorica,
337        country::Code::Mk => Tz::Europe__Skopje,
338        country::Code::Mt => Tz::Europe__Malta,
339        country::Code::Nl => Tz::Europe__Amsterdam,
340        country::Code::No => Tz::Europe__Oslo,
341        country::Code::Pl => Tz::Europe__Warsaw,
342        country::Code::Pt => Tz::Europe__Lisbon,
343        country::Code::Ro => Tz::Europe__Bucharest,
344        country::Code::Rs => Tz::Europe__Belgrade,
345        country::Code::Ru => Tz::Europe__Moscow,
346        country::Code::Se => Tz::Europe__Stockholm,
347        country::Code::Si => Tz::Europe__Ljubljana,
348        country::Code::Sk => Tz::Europe__Bratislava,
349        country::Code::Sm => Tz::Europe__San_Marino,
350        country::Code::Tr => Tz::Turkey,
351        country::Code::Ua => Tz::Europe__Kiev,
352        _ => return None,
353    };
354
355    debug!(%tz, "time-zone detected");
356
357    Some(tz)
358}