ocpi-tariffs 0.55.0

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

/// Test support shared by this module's other test files.
#[cfg(test)]
pub mod test;

#[cfg(test)]
mod test_find_or_infer;

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

use jiff::tz::{self, TimeZone};
use tracing::{debug, instrument};

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

/// 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 `time_zone` names an IANA time zone in the wrong letter case, such as
    /// `europe/amsterdam` for `Europe/Amsterdam`.
    ///
    /// No two IANA names differ only in case, so [`find_or_infer`] still finds the time zone
    /// and returns it as [`Source::Found`].
    MiscasedTimezone,

    /// 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::MiscasedTimezone => f.write_str("The CDR location's time-zone differs in letter case from the IANA name."),
            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::MiscasedTimezone => warning::Id::from_static("miscased_timezone"),
            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(Clone, Debug)]
pub enum Source {
    /// The timezone was found in the `location` element.
    Found(TimeZone),

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

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

/// Find the timezone stated in the `CDR`, or infer one from its country.
///
/// [`Source`] says which of the two happened, because a stated timezone is the CDR's own
/// claim while an inferred one is this library's guess.
///
/// `find_or_infer` takes the CDR that [`cdr::check`] returns, so it can run before
/// [`cdr::build`], and a CDR that `build` refuses can still get a timezone.
/// [`Source::into_timezone`] gives the timezone that [`cdr::price`] takes.
///
/// A `time_zone` field is read wherever it appears. `v2.2.1` dropped it from `CdrLocation`, but
/// enough CDRs still carry it that the schema reads it and reports `NonSpecField`, and a `v2.2.1`
/// CDR carrying the old `location` object is preferred over its `cdr_location`, since that is
/// where such a CDR put the timezone. A `time_zone` that is present but unusable is not fatal: it
/// becomes a warning and the country is tried instead.
///
/// Inferring works only for a country with a single timezone, which in practice means Europe.
///
/// # Errors
///
/// The CDR has no usable location object, its location states no country, or that country maps to
/// no timezone.
pub fn find_or_infer(cdr: &cdr::Checked<'_>) -> Verdict<Source, Warning> {
    let mut warnings = warning::Gatherer::new();
    let source = find_or_infer_into(cdr, &mut warnings);
    warnings.into_verdict(source)
}

/// Find the timezone stated in the CDR, or infer one from its country,
/// gathering the warnings into `warnings`.
fn find_or_infer_into(
    cdr: &cdr::Checked<'_>,
    warnings: &mut dyn warning::Gather<Warning>,
) -> Result<Source, warning::Error<Warning>> {
    let location = location(cdr, 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/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc#mod_cdrs_cdr_location_class>
    // See: <https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_locations.md#31-location-object>
    let tz = match &location.time_zone {
        schema::Integrity::Ok(Some(tz)) => try_parse_location_timezone(tz, warnings),
        // 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 de-escalated to
    // a warning and the country is tried instead.
    let tz = match tz {
        Ok(tz) => tz,
        Err(error) => {
            warnings.deescalate(error);
            return infer_from_country(&location, warnings);
        }
    };

    Ok(Source::Found(tz))
}

/// 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/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc#mod_cdrs_cdr_object>
/// * See: <https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_cdrs.md#3-object-description>
fn location<'a, 'buf>(
    cdr: &'a cdr::Checked<'buf>,
    warnings: &mut dyn warning::Gather<Warning>,
) -> Result<Location<'a, 'buf>, warning::Error<Warning>> {
    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 Err(warning::Error::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 Err(warning::Error::at(elem.clone(), Warning::NoLocation));
            }
        },
    };

    Ok(Location { time_zone, country })
}

/// Infer the timezone from the location's `country`, having found no usable `time_zone`.
fn infer_from_country(
    location: &Location<'_, '_>,
    warnings: &mut dyn warning::Gather<Warning>,
) -> Result<Source, warning::Error<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/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc#mod_cdrs_cdr_location_class>
    // See: <https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/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 Err(warning::Error::at(elem.clone(), Warning::NoLocationCountry));
        }
    };

    let tz = infer_timezone_from_location_country(country, warnings)?;

    Ok(Source::Inferred(tz))
}

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

    // The schema proved the value is a JSON string but keeps it raw, so it is decoded here.
    let raw = tz.value();
    let (tz, warning) = raw.decode_escapes();

    if let Some(warning) = warning {
        warnings.insert(elem, warning.into());
    }

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

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

    let Ok(timezone) = TimeZone::get(&tz) else {
        return Err(warning::Error::new(elem, Warning::InvalidTimezone));
    };

    // jiff looks a name up without regard to ASCII case, and returns the name as the
    // database spells it. It returns an alias such as `Europe/Kiev` as itself, not as
    // `Europe/Kyiv`. So a returned name that differs from the input differs only in case.
    if timezone.iana_name() != Some(&*tz) {
        warnings.insert(elem, Warning::MiscasedTimezone);
    }

    Ok(timezone)
}

/// Try to infer a timezone from the location's `country` field.
#[instrument(skip_all)]
fn infer_timezone_from_location_country(
    country: &schema::Str<'_>,
    warnings: &mut dyn warning::Gather<Warning>,
) -> Result<TimeZone, warning::Error<Warning>> {
    let elem = country.element();
    let code_set = country::CodeSet::from_schema(country, 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 Err(warning::Error::new(
            elem,
            Warning::CantInferTimezoneFromCountry(country_code.into_alpha_2_str()),
        ));
    };

    Ok(tz)
}

/// 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<TimeZone> {
    let tz = match country_code {
        country::Code::Ad => tz::get!("Europe/Andorra"),
        country::Code::Al => tz::get!("Europe/Tirane"),
        country::Code::At => tz::get!("Europe/Vienna"),
        country::Code::Ba => tz::get!("Europe/Sarajevo"),
        country::Code::Be => tz::get!("Europe/Brussels"),
        country::Code::Bg => tz::get!("Europe/Sofia"),
        country::Code::By => tz::get!("Europe/Minsk"),
        country::Code::Ch => tz::get!("Europe/Zurich"),
        country::Code::Cy => tz::get!("Europe/Nicosia"),
        country::Code::Cz => tz::get!("Europe/Prague"),
        country::Code::De => tz::get!("Europe/Berlin"),
        country::Code::Dk => tz::get!("Europe/Copenhagen"),
        country::Code::Ee => tz::get!("Europe/Tallinn"),
        country::Code::Es => tz::get!("Europe/Madrid"),
        country::Code::Fi => tz::get!("Europe/Helsinki"),
        country::Code::Fr => tz::get!("Europe/Paris"),
        country::Code::Gb => tz::get!("Europe/London"),
        country::Code::Gr => tz::get!("Europe/Athens"),
        country::Code::Hr => tz::get!("Europe/Zagreb"),
        country::Code::Hu => tz::get!("Europe/Budapest"),
        country::Code::Ie => tz::get!("Europe/Dublin"),
        country::Code::Is => tz::get!("Atlantic/Reykjavik"),
        country::Code::It => tz::get!("Europe/Rome"),
        country::Code::Li => tz::get!("Europe/Vaduz"),
        country::Code::Lt => tz::get!("Europe/Vilnius"),
        country::Code::Lu => tz::get!("Europe/Luxembourg"),
        country::Code::Lv => tz::get!("Europe/Riga"),
        country::Code::Mc => tz::get!("Europe/Monaco"),
        country::Code::Md => tz::get!("Europe/Chisinau"),
        country::Code::Me => tz::get!("Europe/Podgorica"),
        country::Code::Mk => tz::get!("Europe/Skopje"),
        country::Code::Mt => tz::get!("Europe/Malta"),
        country::Code::Nl => tz::get!("Europe/Amsterdam"),
        country::Code::No => tz::get!("Europe/Oslo"),
        country::Code::Pl => tz::get!("Europe/Warsaw"),
        country::Code::Pt => tz::get!("Europe/Lisbon"),
        country::Code::Ro => tz::get!("Europe/Bucharest"),
        country::Code::Rs => tz::get!("Europe/Belgrade"),
        country::Code::Ru => tz::get!("Europe/Moscow"),
        country::Code::Se => tz::get!("Europe/Stockholm"),
        country::Code::Si => tz::get!("Europe/Ljubljana"),
        country::Code::Sk => tz::get!("Europe/Bratislava"),
        country::Code::Sm => tz::get!("Europe/San_Marino"),
        country::Code::Tr => tz::get!("Europe/Istanbul"),
        country::Code::Ua => tz::get!("Europe/Kyiv"),
        _ => return None,
    };

    debug!(tz = tz.iana_name(), "time-zone detected");

    Some(tz)
}