ocpi-tariffs 0.52.0

OCPI tariff calculations
Documentation
//! Parse an IANA Timezone from JSON or find a timezone in a CDR.

#[cfg(test)]
pub mod test;

#[cfg(test)]
mod test_find_or_infer;

use std::{borrow::Cow, fmt};

use chrono_tz::Tz;
use tracing::{debug, instrument};

use crate::{
    cdr, country, from_warning_all, json,
    schema::{self, FromSchema as _, HasElement as _},
    warning::{self, GatherWarnings as _, WithElement as _},
    IntoCaveat as _, Verdict,
};

/// The warnings possible when parsing or linting an IANA timezone.
#[derive(Debug)]
pub enum Warning {
    /// A timezone can't be inferred from the `location`'s `country`.
    CantInferTimezoneFromCountry(&'static str),

    /// Neither the timezone or country field require char escape codes.
    ContainsEscapeCodes,

    /// The CDR location is not a valid `ISO 3166-1` alpha-3 code.
    Country(country::Warning),

    /// The field at the path could not be decoded.
    Decode(json::decode::Warning),

    /// The CDR location did not contain a valid IANA time-zone.
    ///
    /// See: <https://www.iana.org/time-zones>.
    InvalidTimezone,

    /// The `location.country` field should be an alpha-3 country code.
    ///
    /// The alpha-2 code can be converted into an alpha-3 but the caller should be warned.
    LocationCountryShouldBeAlpha3,

    /// The CDR's `location` has no `country` element and so the timezone can't be inferred.
    NoLocationCountry,

    /// The CDR has no `location` element and so the timezone can't be found or inferred.
    NoLocation,

    /// A v221 CDR is given but it contains a `location` field instead of a `cdr_location` as defined in the spec.
    V221CdrHasLocationField,
}

from_warning_all!(
    country::Warning => Warning::Country,
    json::decode::Warning => Warning::Decode
);

impl fmt::Display for Warning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CantInferTimezoneFromCountry(country_code) => write!(f, "Unable to infer timezone from the `location`'s `country`: `{country_code}`"),
            Self::ContainsEscapeCodes => f.write_str("The CDR location contains needless escape codes."),
            Self::Country(kind) => fmt::Display::fmt(kind, f),
            Self::Decode(warning) => fmt::Display::fmt(warning, f),
            Self::InvalidTimezone => f.write_str("The CDR location did not contain a valid IANA time-zone."),
            Self::LocationCountryShouldBeAlpha3 => f.write_str("The `location.country` field should be an alpha-3 country code."),
            Self::NoLocationCountry => {
                f.write_str("The CDR's `location` has no `country` element and so the timezone can't be inferred.")
            },
            Self::NoLocation => {
                f.write_str("The CDR has no `location` element and so the timezone can't be found or inferred.")                   
            }
            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."),

        }
    }
}

impl crate::Warning for Warning {
    fn id(&self) -> warning::Id {
        match self {
            Self::CantInferTimezoneFromCountry(_) => {
                warning::Id::from_static("cant_infer_timezone_from_country")
            }
            Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
            Self::Decode(warning) => warning.id(),
            Self::Country(warning) => warning.id(),
            Self::InvalidTimezone => warning::Id::from_static("invalid_timezone"),
            Self::LocationCountryShouldBeAlpha3 => {
                warning::Id::from_static("location_country_should_be_alpha3")
            }
            Self::NoLocationCountry => warning::Id::from_static("no_location_country"),
            Self::NoLocation => warning::Id::from_static("no_location"),
            Self::V221CdrHasLocationField => {
                warning::Id::from_static("v221_cdr_has_location_field")
            }
        }
    }
}

/// The source of the timezone.
#[derive(Copy, Clone, Debug)]
pub enum Source {
    /// The timezone was found in the `location` element.
    Found(Tz),

    /// The timezone is inferred from the `location`'s `country`.
    Inferred(Tz),
}

impl Source {
    /// Return the timezone and disregard where it came from.
    pub fn into_timezone(self) -> Tz {
        match self {
            Source::Found(tz) | Source::Inferred(tz) => tz,
        }
    }
}

/// Try to find or infer the timezone from the `CDR` JSON.
///
/// Return `Some` if the timezone can be found or inferred.
/// Return `None` if the timezone is not found and can't be inferred.
///
/// Finding a timezone is an infallible operation. If invalid data is found a `None` is returned
/// with an appropriate warning.
///
/// If the `CDR` contains a `time_zone` in the location object then that is simply returned.
/// Only pre-`v2.2.1` CDR's have a `time_zone` field in the `Location` object.
///
/// Inferring the timezone only works for `CDR`s from European countries.
///
pub fn find_or_infer(cdr: &cdr::Versioned<'_>) -> Verdict<Source, Warning> {
    let mut warnings = warning::Set::new();

    let location = location(cdr)?.gather_warnings_into(&mut warnings);

    debug!("Searching for time-zone in CDR");

    // The `location::time_zone` field is optional in v211 and not part of the v221 spec,
    // where the schema reports it as a `NonSpecField` and reads it anyway.
    //
    // See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#mod_cdrs_cdr_location_class>
    // See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_locations.md#31-location-object>
    let tz = match &location.time_zone {
        schema::Integrity::Ok(Some(tz)) => try_parse_location_timezone(tz),
        // An absent, `null`, or wrongly typed `time_zone` is located by the schema walk.
        // There may still be a country to infer from, so the search continues.
        schema::Integrity::Ok(None) | schema::Integrity::Missing(_) | schema::Integrity::Err(_) => {
            return infer_from_country(&location, warnings)
        }
    };

    // A `time_zone` that is present but unusable is not fatal. The failure is deescalated to
    // a warning and the country is tried instead.
    let tz = match tz {
        Ok(tz) => Some(tz.gather_warnings_into(&mut warnings)),
        Err(err_set) => {
            warnings.deescalate_error(err_set);
            None
        }
    };

    let Some(tz) = tz else {
        return infer_from_country(&location, warnings);
    };

    Ok(Source::Found(tz).into_caveat(warnings))
}

/// The two fields a timezone can be found or inferred from, borrowed out of whichever
/// version's location object carries them.
struct Location<'a, 'buf> {
    time_zone: &'a schema::Integrity<Option<schema::Str<'buf>>>,
    country: &'a schema::Integrity<schema::Str<'buf>>,
}

/// Borrow the location fields out of the CDR's schema IR.
///
/// Describes the location that the charge-session took place at. The v211 CDR has a
/// `location` field while the v221 CDR has a `cdr_location` field. A v221 CDR that still
/// uses the old name is read from it anyway, because that is the only place its timezone
/// can be.
///
/// * See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#131-cdr-object>
/// * See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_cdrs.md#3-object-description>
fn location<'a, 'buf>(cdr: &'a cdr::Versioned<'buf>) -> Verdict<Location<'a, 'buf>, Warning> {
    let mut warnings = warning::Set::new();

    let (time_zone, country) = match cdr.schema() {
        cdr::Version::V211(ir) => match &ir.location {
            schema::Integrity::Ok(location) => (&location.time_zone, &location.country),
            schema::Integrity::Missing(elem) | schema::Integrity::Err(elem) => {
                return warnings.bail_at(elem.clone(), Warning::NoLocation)
            }
        },
        // A `location` object in a v221 CDR is the v211 field name. It is preferred over
        // `cdr_location`, because a CDR that carries it put the timezone there.
        cdr::Version::V221(ir) => match (&ir.location, &ir.cdr_location) {
            (schema::Integrity::Ok(location), _) => {
                // Anchored at the document rather than at the field: the schema walk's
                // `NonSpecField` warning already locates the field itself.
                warnings.insert(cdr.as_element(), Warning::V221CdrHasLocationField);

                (&location.time_zone, &location.country)
            }
            (_, schema::Integrity::Ok(location)) => (&location.time_zone, &location.country),
            (_, schema::Integrity::Missing(elem) | schema::Integrity::Err(elem)) => {
                return warnings.bail_at(elem.clone(), Warning::NoLocation)
            }
        },
    };

    Ok(Location { time_zone, country }.into_caveat(warnings))
}

/// Infer the timezone from the location's `country`, having found no usable `time_zone`.
fn infer_from_country(
    location: &Location<'_, '_>,
    mut warnings: warning::Set<Warning>,
) -> Verdict<Source, Warning> {
    debug!("No time-zone found in CDR; trying to infer time-zone from country");

    // `ISO 3166-1 alpha-3` code for the country of this location. The field is required in
    // both versions.
    //
    // See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#mod_cdrs_cdr_location_class>
    // See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_locations.md#31-location-object>
    let country = match &location.country {
        schema::Integrity::Ok(country) => country,
        schema::Integrity::Missing(elem) | schema::Integrity::Err(elem) => {
            return warnings.bail_at(elem.clone(), Warning::NoLocationCountry)
        }
    };

    let tz = infer_timezone_from_location_country(country).gather_warnings_into(&mut warnings)?;

    Ok(Source::Inferred(tz).into_caveat(warnings))
}

/// Try to parse the location's `time_zone` into a `Tz`.
fn try_parse_location_timezone(tz: &schema::Str<'_>) -> Verdict<Tz, Warning> {
    let elem = tz.element();
    let mut warnings = warning::Set::new();

    // The schema proved the value is a JSON string but keeps it raw, so it is decoded here.
    let raw = tz.value();
    let tz = raw
        .decode_escapes()
        .with_element(elem)
        .gather_warnings_into(&mut warnings);

    if matches!(tz, Cow::Owned(_)) {
        warnings.insert(elem, Warning::ContainsEscapeCodes);
    }

    debug!(%tz, "Escaped time-zone found in CDR");

    let Ok(tz) = tz.parse::<Tz>() else {
        return warnings.bail(elem, Warning::InvalidTimezone);
    };

    Ok(tz.into_caveat(warnings))
}

/// Try to infer a timezone from the location's `country` field.
#[instrument(skip_all)]
fn infer_timezone_from_location_country(country: &schema::Str<'_>) -> Verdict<Tz, Warning> {
    let elem = country.element();
    let mut warnings = warning::Set::new();
    let code_set = country::CodeSet::from_schema(country)?.gather_warnings_into(&mut warnings);

    // The `location.country` field should be an alpha-3 country code.
    //
    // The alpha-2 code can be converted into an alpha-3 but the caller should be warned.
    let country_code = match code_set {
        country::CodeSet::Alpha2(code) => {
            warnings.insert(elem, Warning::LocationCountryShouldBeAlpha3);
            code
        }
        country::CodeSet::Alpha3(code) => code,
    };
    let Some(tz) = try_detect_timezone(country_code) else {
        return warnings.bail(
            elem,
            Warning::CantInferTimezoneFromCountry(country_code.into_alpha_2_str()),
        );
    };

    Ok(tz.into_caveat(warnings))
}

/// Mapping of European countries to time-zones with geographical naming
///
/// This is only possible for countries with a single time-zone and only for countries as they
/// currently exist (2024). It's a best effort approach to determine a time-zone from just an
/// ALPHA-3 `ISO 3166-1` country code.
///
/// In small edge cases (e.g. Gibraltar) this detection might generate the wrong time-zone.
#[instrument]
#[expect(
    clippy::wildcard_enum_match_arm,
    reason = "There are many `Code` variants that do not map to a timezone."
)]
fn try_detect_timezone(country_code: country::Code) -> Option<Tz> {
    let tz = match country_code {
        country::Code::Ad => Tz::Europe__Andorra,
        country::Code::Al => Tz::Europe__Tirane,
        country::Code::At => Tz::Europe__Vienna,
        country::Code::Ba => Tz::Europe__Sarajevo,
        country::Code::Be => Tz::Europe__Brussels,
        country::Code::Bg => Tz::Europe__Sofia,
        country::Code::By => Tz::Europe__Minsk,
        country::Code::Ch => Tz::Europe__Zurich,
        country::Code::Cy => Tz::Europe__Nicosia,
        country::Code::Cz => Tz::Europe__Prague,
        country::Code::De => Tz::Europe__Berlin,
        country::Code::Dk => Tz::Europe__Copenhagen,
        country::Code::Ee => Tz::Europe__Tallinn,
        country::Code::Es => Tz::Europe__Madrid,
        country::Code::Fi => Tz::Europe__Helsinki,
        country::Code::Fr => Tz::Europe__Paris,
        country::Code::Gb => Tz::Europe__London,
        country::Code::Gr => Tz::Europe__Athens,
        country::Code::Hr => Tz::Europe__Zagreb,
        country::Code::Hu => Tz::Europe__Budapest,
        country::Code::Ie => Tz::Europe__Dublin,
        country::Code::Is => Tz::Iceland,
        country::Code::It => Tz::Europe__Rome,
        country::Code::Li => Tz::Europe__Vaduz,
        country::Code::Lt => Tz::Europe__Vilnius,
        country::Code::Lu => Tz::Europe__Luxembourg,
        country::Code::Lv => Tz::Europe__Riga,
        country::Code::Mc => Tz::Europe__Monaco,
        country::Code::Md => Tz::Europe__Chisinau,
        country::Code::Me => Tz::Europe__Podgorica,
        country::Code::Mk => Tz::Europe__Skopje,
        country::Code::Mt => Tz::Europe__Malta,
        country::Code::Nl => Tz::Europe__Amsterdam,
        country::Code::No => Tz::Europe__Oslo,
        country::Code::Pl => Tz::Europe__Warsaw,
        country::Code::Pt => Tz::Europe__Lisbon,
        country::Code::Ro => Tz::Europe__Bucharest,
        country::Code::Rs => Tz::Europe__Belgrade,
        country::Code::Ru => Tz::Europe__Moscow,
        country::Code::Se => Tz::Europe__Stockholm,
        country::Code::Si => Tz::Europe__Ljubljana,
        country::Code::Sk => Tz::Europe__Bratislava,
        country::Code::Sm => Tz::Europe__San_Marino,
        country::Code::Tr => Tz::Turkey,
        country::Code::Ua => Tz::Europe__Kiev,
        _ => return None,
    };

    debug!(%tz, "time-zone detected");

    Some(tz)
}