ocpi-tariffs 0.55.0

OCPI tariff calculations
Documentation
//! The OCPI versions this crate supports, and the guess at which version a CDR or tariff is.

#[cfg(test)]
mod test;

#[cfg(test)]
mod test_guess_cdr;

#[cfg(test)]
mod test_guess_tariff;

#[cfg(test)]
mod test_real_world;

use std::fmt;

use tracing::debug;

use crate::{cdr, json, tariff};

/// The OCPI versions supported by this crate.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Version {
    /// OCPI version 2.2.1.
    ///
    /// See: <https://github.com/ocpi/ocpi/tree/a57ecb624fbe0f19537ac7956a11f3019a65018f>.
    V221,

    /// OCPI version 2.1.1.
    ///
    /// See: <https://github.com/ocpi/ocpi/tree/28ea45329a50c3dbfd790505b97860854db1d4a6>.
    V211,
}

impl Versioned for Version {
    fn version(&self) -> Version {
        *self
    }
}

impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Version::V221 => f.write_str("v221"),
            Version::V211 => f.write_str("v211"),
        }
    }
}

/// An object for a specific OCPI [`Version`].
pub trait Versioned: fmt::Debug {
    /// Return the OCPI `Version` of this object.
    fn version(&self) -> Version;
}

/// An object with an uncertain [`Version`].
pub trait Unversioned: fmt::Debug {
    /// The concrete [`Versioned`] type.
    type Versioned: Versioned;

    /// Forced an [`Unversioned`] object to be the given [`Version`].
    ///
    /// This does not change the structure of the OCPI object.
    /// It simply relabels the object as a different OCPI Version.
    ///
    /// Use this with care.
    fn force_into_versioned(self, version: Version) -> Self::Versioned;
}

/// An OCPI object with a certain or uncertain version.
#[derive(Debug)]
pub enum Guess<V, U>
where
    V: Versioned,
    U: fmt::Debug,
{
    /// The version of the object `V` is certain.
    Certain(V),

    /// The version of the object `U` is uncertain.
    Uncertain(U),
}

impl<V, U> Guess<V, U>
where
    V: Versioned,
    U: Unversioned<Versioned = V>,
{
    /// Convert the OCPI object into its [`Version`] if it's [`Versioned`].
    /// Otherwise, return `Uncertain(())`.
    pub fn into_version(self) -> Guess<Version, ()> {
        match self {
            Guess::Certain(v) => Guess::Certain(v.version()),
            Guess::Uncertain(_) => Guess::Uncertain(()),
        }
    }

    /// Convert a reference to the OCPI object into its [`Version`] if it's
    /// [`Versioned`]. Otherwise, return `Uncertain(())`.
    pub fn as_version(&self) -> Guess<Version, ()> {
        match self {
            Guess::Certain(v) => Guess::Certain(v.version()),
            Guess::Uncertain(_) => Guess::Uncertain(()),
        }
    }

    /// Return the contained OCPI object if it's [`Versioned`]. Otherwise, force convert the
    /// object to the given [`Version`].
    pub fn certain_or(self, fallback: Version) -> V {
        match self {
            Guess::Certain(v) => v,
            Guess::Uncertain(u) => u.force_into_versioned(fallback),
        }
    }

    /// Return `Some` OCPI object if it's [`Versioned`]. Otherwise, return None if the
    /// object's version is uncertain.
    pub fn certain_or_none(self) -> Option<V> {
        match self {
            Guess::Certain(v) => Some(v),
            Guess::Uncertain(_) => None,
        }
    }
}

/// Guess the `Version` of the given CDR [`json::Document`].
pub(crate) fn cdr_version(doc: json::Document<'_>) -> cdr::VersionGuess<'_> {
    guess_cdr_version(doc)
}

/// Try to guess a CDR's [`Version`] and return a [`cdr::VersionGuess`] with the outcome.
fn guess_cdr_version(doc: json::Document<'_>) -> cdr::VersionGuess<'_> {
    /// Fields present in `v2.1.1` CDR that do not exist in `v2.2.1`.
    /// `auth_id` and `location` were replaced by `cdr_token` and `cdr_location`.
    const V211_EXCLUSIVE_FIELDS: &[&str] = &["auth_id", "location", "stop_date_time"];

    /// Fields introduced in `v2.2.1` CDR that do not exist in `v2.1.1`.
    /// Sorted alphabetically; required fields marked for reference.
    const V221_EXCLUSIVE_FIELDS: &[&str] = &[
        "authorization_reference",
        "cdr_location", // Required in `v2.2.1`
        "cdr_token",    // Required in `v2.2.1`
        "country_code", // Required in `v2.2.1`
        "credit",
        "credit_reference_id",
        "end_date_time", // Required in `v2.2.1`
        "home_charging_compensation",
        "invoice_reference_id",
        "party_id", // Required in `v2.2.1`
        "session_id",
        "signed_data",
        "total_energy_cost",
        "total_fixed_cost",
        "total_parking_cost",
        "total_reservation_cost",
        "total_time_cost",
    ];

    // The `Document` is expected to be an object (see `json::parse_object`); if it is not,
    // there are no fields to inspect so the version stays uncertain.
    let Some(fields) = doc.root().as_object_fields() else {
        return Guess::Uncertain(cdr::Unversioned::new(doc));
    };

    for field in fields {
        let key = field.key();

        if key.eq_any_escape_aware(V211_EXCLUSIVE_FIELDS) {
            return Guess::Certain(cdr::VersionedJson::new(doc, Version::V211));
        } else if key.eq_any_escape_aware(V221_EXCLUSIVE_FIELDS) {
            return Guess::Certain(cdr::VersionedJson::new(doc, Version::V221));
        }
    }

    Guess::Uncertain(cdr::Unversioned::new(doc))
}

/// Guess the `Version` of the given tariff [`json::Document`].
pub(crate) fn tariff_version(doc: json::Document<'_>) -> tariff::VersionGuess<'_> {
    guess_tariff_version(doc)
}

/// The private impl for detecting a tariff's version.
fn guess_tariff_version(doc: json::Document<'_>) -> tariff::VersionGuess<'_> {
    /// Fields introduced in `v2.2.1` Tariff that do not exist in `v2.1.1.`.
    const V221_EXCLUSIVE_FIELDS: &[&str] = &[
        "country_code", // Required in `v2.2.1`
        "end_date_time",
        "max_price",
        "min_price",
        "party_id", // Required in `v2.2.1`
        "start_date_time",
        "type",
    ];

    /// Fields present in both `v2.1.1` and `v2.2.1` Tariff.
    /// Seeing any of these — without a `v2.2.1` exclusive field — confirms the object
    /// is a `v2.1.1` tariff rather than an unrecognized document.
    const V211_V221_SHARED_FIELDS: &[&str] = &[
        "currency",
        "elements",
        "energy_mix",
        "id",
        "last_updated",
        "tariff_alt_text",
        "tariff_alt_url",
    ];

    // The `Document` is expected to be an object (see `json::parse_object`); if it is not,
    // there are no fields to inspect so the version stays uncertain.
    let Some(fields) = doc.root().as_object_fields() else {
        return Guess::Uncertain(tariff::Unversioned::new(doc));
    };

    let mut seen_known_field = false;
    for field in fields {
        let key = field.key();
        if key.eq_any_escape_aware(V221_EXCLUSIVE_FIELDS) {
            debug!(
                "Tariff is v221 because of field: `{}`",
                key.as_unescaped_str()
            );
            return tariff::VersionGuess::Certain(tariff::VersionedJson::new(doc, Version::V221));
        }
        if key.eq_any_escape_aware(V211_V221_SHARED_FIELDS) {
            seen_known_field = true;
        }
    }

    if seen_known_field {
        return tariff::VersionGuess::Certain(tariff::VersionedJson::new(doc, Version::V211));
    }

    Guess::Uncertain(tariff::Unversioned::new(doc))
}