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,
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
138impl Source {
139    /// Return the timezone and disregard where it came from.
140    pub fn into_timezone(self) -> Tz {
141        match self {
142            Source::Found(tz) | Source::Inferred(tz) => tz,
143        }
144    }
145}
146
147/// Try to find or infer the timezone from the `CDR` JSON.
148///
149/// Return `Some` if the timezone can be found or inferred.
150/// Return `None` if the timezone is not found and can't be inferred.
151///
152/// Finding a timezone is an infallible operation. If invalid data is found a `None` is returned
153/// with an appropriate warning.
154///
155/// If the `CDR` contains a `time_zone` in the location object then that is simply returned.
156/// Only pre-`v2.2.1` CDR's have a `time_zone` field in the `Location` object.
157///
158/// Inferring the timezone only works for `CDR`s from European countries.
159///
160pub fn find_or_infer(cdr: &cdr::Versioned<'_>) -> Verdict<Source, Warning> {
161    const LOCATION_FIELD_V211: &str = "location";
162    const LOCATION_FIELD_V221: &str = "cdr_location";
163    const TIMEZONE_FIELD: &str = "time_zone";
164    const COUNTRY_FIELD: &str = "country";
165
166    let mut warnings = warning::Set::new();
167
168    let cdr_root = cdr.as_element();
169    let Some(fields) = cdr_root.as_object_fields() else {
170        return warnings.bail(Warning::ShouldBeAnObject, cdr_root);
171    };
172
173    let cdr_fields = fields.as_raw_map();
174
175    let v211_location = cdr_fields.get(LOCATION_FIELD_V211);
176
177    // OCPI v221 changed the `location` field to `cdr_location`.
178    //
179    // * See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#131-cdr-object>
180    // * See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_cdrs.md#3-object-description>
181    if cdr.version() == Version::V221 && v211_location.is_some() {
182        warnings.insert(Warning::V221CdrHasLocationField, cdr_root);
183    }
184
185    // Describes the location that the charge-session took place at.
186    //
187    // The v211 CDR has a `location` field, while the v221 CDR has a `cdr_location` field.
188    //
189    // * See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#131-cdr-object>
190    // * See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_cdrs.md#3-object-description>
191    let Some(location_elem) = v211_location.or_else(|| cdr_fields.get(LOCATION_FIELD_V221)) else {
192        return warnings.bail(Warning::NoLocation, cdr_root);
193    };
194
195    let json::Value::Object(fields) = location_elem.as_value() else {
196        return warnings.bail(Warning::InvalidLocationType, cdr_root);
197    };
198
199    let location_fields = fields.as_raw_map();
200
201    debug!("Searching for time-zone in CDR");
202
203    // The `location::time_zone` field is optional in v211 and not defined in the v221 spec.
204    //
205    // See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#mod_cdrs_cdr_location_class>
206    // See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_locations.md#31-location-object>
207    let tz = location_fields
208        .get(TIMEZONE_FIELD)
209        .map(|elem| try_parse_location_timezone(elem).gather_warnings_into(&mut warnings))
210        .transpose();
211
212    // We first try to find/parse the timezone in the location object.
213    // If the timezone is not found there or there are any failures,
214    // The failures are deescalated to warnings.
215    let tz = tz
216        .map_err(|err_set| {
217            warnings.deescalate_error(err_set);
218        })
219        .ok()
220        .flatten();
221
222    if let Some(tz) = tz {
223        return Ok(Source::Found(tz).into_caveat(warnings));
224    }
225
226    debug!("No time-zone found in CDR; trying to infer time-zone from country");
227
228    // ISO 3166-1 alpha-3 code for the country of this location.
229    let Some(country_elem) = location_fields.get(COUNTRY_FIELD) else {
230        // The `location::country` field is required.
231        //
232        // See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#mod_cdrs_cdr_location_class>
233        // See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_locations.md#31-location-object>
234        return warnings.bail(Warning::NoLocationCountry, location_elem);
235    };
236    let tz =
237        infer_timezone_from_location_country(country_elem).gather_warnings_into(&mut warnings)?;
238
239    Ok(Source::Inferred(tz).into_caveat(warnings))
240}
241
242/// Try to parse the `location` element's timezone into a `Tz`.
243fn try_parse_location_timezone(tz_elem: &json::Element<'_>) -> Verdict<Tz, Warning> {
244    let tz = tz_elem.as_value();
245    debug!(tz = %tz, "Raw time-zone found in CDR");
246
247    let mut warnings = warning::Set::new();
248    let Some(tz) = tz.to_raw_str() else {
249        return warnings.bail(Warning::InvalidTimezoneType, tz_elem);
250    };
251
252    let tz = tz
253        .decode_escapes(tz_elem)
254        .gather_warnings_into(&mut warnings);
255
256    if matches!(tz, Cow::Owned(_)) {
257        warnings.insert(Warning::ContainsEscapeCodes, tz_elem);
258    }
259
260    debug!(%tz, "Escaped time-zone found in CDR");
261
262    let Ok(tz) = tz.parse::<Tz>() else {
263        return warnings.bail(Warning::InvalidTimezone, tz_elem);
264    };
265
266    Ok(tz.into_caveat(warnings))
267}
268
269/// Try to infer a timezone from the `location` elements `country` field.
270#[instrument(skip_all)]
271fn infer_timezone_from_location_country(country_elem: &json::Element<'_>) -> Verdict<Tz, Warning> {
272    let mut warnings = warning::Set::new();
273    let code_set = country::CodeSet::from_json(country_elem)?.gather_warnings_into(&mut warnings);
274
275    // The `location.country` field should be an alpha-3 country code.
276    //
277    // The alpha-2 code can be converted into an alpha-3 but the caller should be warned.
278    let country_code = match code_set {
279        country::CodeSet::Alpha2(code) => {
280            warnings.insert(Warning::LocationCountryShouldBeAlpha3, country_elem);
281            code
282        }
283        country::CodeSet::Alpha3(code) => code,
284    };
285    let Some(tz) = try_detect_timezone(country_code) else {
286        return warnings.bail(
287            Warning::CantInferTimezoneFromCountry(country_code.into_alpha_2_str()),
288            country_elem,
289        );
290    };
291
292    Ok(tz.into_caveat(warnings))
293}
294
295/// Mapping of European countries to time-zones with geographical naming
296///
297/// This is only possible for countries with a single time-zone and only for countries as they
298/// currently exist (2024). It's a best effort approach to determine a time-zone from just an
299/// ALPHA-3 ISO 3166-1 country code.
300///
301/// In small edge cases (e.g. Gibraltar) this detection might generate the wrong time-zone.
302#[instrument]
303fn try_detect_timezone(country_code: country::Code) -> Option<Tz> {
304    let tz = match country_code {
305        country::Code::Ad => Tz::Europe__Andorra,
306        country::Code::Al => Tz::Europe__Tirane,
307        country::Code::At => Tz::Europe__Vienna,
308        country::Code::Ba => Tz::Europe__Sarajevo,
309        country::Code::Be => Tz::Europe__Brussels,
310        country::Code::Bg => Tz::Europe__Sofia,
311        country::Code::By => Tz::Europe__Minsk,
312        country::Code::Ch => Tz::Europe__Zurich,
313        country::Code::Cy => Tz::Europe__Nicosia,
314        country::Code::Cz => Tz::Europe__Prague,
315        country::Code::De => Tz::Europe__Berlin,
316        country::Code::Dk => Tz::Europe__Copenhagen,
317        country::Code::Ee => Tz::Europe__Tallinn,
318        country::Code::Es => Tz::Europe__Madrid,
319        country::Code::Fi => Tz::Europe__Helsinki,
320        country::Code::Fr => Tz::Europe__Paris,
321        country::Code::Gb => Tz::Europe__London,
322        country::Code::Gr => Tz::Europe__Athens,
323        country::Code::Hr => Tz::Europe__Zagreb,
324        country::Code::Hu => Tz::Europe__Budapest,
325        country::Code::Ie => Tz::Europe__Dublin,
326        country::Code::Is => Tz::Iceland,
327        country::Code::It => Tz::Europe__Rome,
328        country::Code::Li => Tz::Europe__Vaduz,
329        country::Code::Lt => Tz::Europe__Vilnius,
330        country::Code::Lu => Tz::Europe__Luxembourg,
331        country::Code::Lv => Tz::Europe__Riga,
332        country::Code::Mc => Tz::Europe__Monaco,
333        country::Code::Md => Tz::Europe__Chisinau,
334        country::Code::Me => Tz::Europe__Podgorica,
335        country::Code::Mk => Tz::Europe__Skopje,
336        country::Code::Mt => Tz::Europe__Malta,
337        country::Code::Nl => Tz::Europe__Amsterdam,
338        country::Code::No => Tz::Europe__Oslo,
339        country::Code::Pl => Tz::Europe__Warsaw,
340        country::Code::Pt => Tz::Europe__Lisbon,
341        country::Code::Ro => Tz::Europe__Bucharest,
342        country::Code::Rs => Tz::Europe__Belgrade,
343        country::Code::Ru => Tz::Europe__Moscow,
344        country::Code::Se => Tz::Europe__Stockholm,
345        country::Code::Si => Tz::Europe__Ljubljana,
346        country::Code::Sk => Tz::Europe__Bratislava,
347        country::Code::Sm => Tz::Europe__San_Marino,
348        country::Code::Tr => Tz::Turkey,
349        country::Code::Ua => Tz::Europe__Kiev,
350        _ => return None,
351    };
352
353    debug!(%tz, "time-zone detected");
354
355    Some(tz)
356}