ocpi-tariffs 0.54.0

OCPI tariff calculations
Documentation
use std::{fmt, ops::Range, str::FromStr as _};

use chrono::{DateTime, NaiveDateTime, Utc};
use num_traits::Zero as _;
use rust_decimal::Decimal;

use super::{CpoId, DateTimeSpan, EventCollector};
use crate::{ToHoursDecimal, country, money, number::RoundDecimal as _};

#[track_caller]
pub(super) fn date_time_span(
    date_start: &str,
    time_start: &str,
    date_end: &str,
    time_end: &str,
) -> DateTimeSpan {
    DateTimeSpan {
        start: crate::test::datetime(date_start, time_start),
        end: crate::test::datetime(date_end, time_end),
    }
}

#[track_caller]
pub(super) fn datetime_naive(date: &str, time: &str) -> NaiveDateTime {
    let s = format!("{date}T{time}");
    NaiveDateTime::from_str(&s).unwrap()
}

/// Create a CDR from a the `PartialCdr` returned from the `generate` feature.
/// The CDR is then priced.
#[expect(
    clippy::similar_names,
    reason = "evse_id and evse_uid are well known terms"
)]
pub(super) fn partial_to_cdr(partial_cdr: super::PartialCdr) -> serde_json::Value {
    const DEFAULT_COUNTRY_CODE: country::Code = country::Code::Nl;
    const DEFAULT_PARTY_ID: &str = "ENE";

    // The bytes lengths of various fields.
    const CONNECTOR_ID_LEN: usize = 36;
    const EVSE_ID_LEN: usize = 48;
    const EVSE_UID_LEN: usize = 36;
    const ID_MAX_LEN: usize = 39;
    const LOCATION_ID_LEN: usize = 36;
    const TOKEN_CONTRACT_UID_LEN: usize = 36;
    const TOKEN_UID_LEN: usize = 36;

    let super::PartialCdr {
        currency_code,
        party_id,
        start_date_time,
        end_date_time,
        total_energy,
        total_charging_duration,
        total_idle_duration,
        total_cost,
        total_energy_cost,
        total_fixed_cost,
        total_idle_duration_cost,
        total_charging_duration_cost,
        charging_periods,
    } = partial_cdr;

    let (country_code, party_id): (country::Code, &str) = party_id
        .as_ref()
        .map(|CpoId { country_code, id }| (*country_code, id.as_str()))
        .unwrap_or_else(|| (DEFAULT_COUNTRY_CODE, DEFAULT_PARTY_ID));
    let id = padded_id("cdr-id", ID_MAX_LEN);
    let start_date_time = start_date_time.to_rfc3339();
    let end_date_time = end_date_time.to_rfc3339();
    let token_uid = padded_id("token-uid", TOKEN_UID_LEN);
    let token_contract_id = padded_id("token-contract-id", TOKEN_CONTRACT_UID_LEN);
    let location_id = padded_id("location-id", LOCATION_ID_LEN);
    let evse_uid = padded_id("evse-uid", EVSE_UID_LEN);
    let evse_id = padded_id("evse-id", EVSE_ID_LEN);
    let connector_id = padded_id("connector-id", CONNECTOR_ID_LEN);
    let total_energy = total_energy
        .map(Decimal::from)
        .unwrap_or_else(Decimal::zero);
    let total_parking_time = total_idle_duration
        .as_ref()
        .map(ToHoursDecimal::to_hours_dec_in_ocpi_precision)
        .unwrap_or_default();
    let total_time = total_charging_duration
        .and_then(|cd| {
            cd.checked_add(&total_idle_duration.unwrap_or_default())
                .map(|td| ToHoursDecimal::to_hours_dec_in_ocpi_precision(&td))
        })
        .unwrap();
    let total_cost = total_cost.map(Price::from).unwrap_or_default();
    let total_energy_cost = total_energy_cost.map(Price::from).unwrap_or_default();
    let total_fixed_cost = total_fixed_cost.map(Price::from).unwrap_or_default();
    let total_idle_duration_cost = total_idle_duration_cost
        .map(Price::from)
        .unwrap_or_default();
    let total_charging_duration_cost = total_charging_duration_cost
        .map(Price::from)
        .unwrap_or_default();
    let last_updated = Utc::now().to_rfc3339();
    let charging_periods = charging_periods
        .into_iter()
        .map(ChargingPeriod::from)
        .collect::<Vec<_>>();

    // See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc>
    serde_json::json!({
        "country_code": country_code.into_alpha_2_str(),
        "party_id": party_id,
        "id": id,
        "start_date_time": start_date_time,
        "end_date_time": end_date_time,
        "cdr_token": {
          "country_code": country_code.into_alpha_2_str(),
          "party_id": party_id,
          "uid": token_uid,
          "contract_id": token_contract_id,
          "type": "RFID"
        },
        "auth_method": "WHITELIST",
        "cdr_location": {
            "id": location_id,
            "address": "[address]",
            "city": "[city]",
            "country": country_code.into_alpha_3_str(),
            "coordinates": {
                "latitude": "50.770774",
                "longitude": "-126.104965"
            },
            "evse_uid": evse_uid,
            "evse_id": evse_id,
            "connector_id": connector_id,
            "connector_standard": "IEC_62196_T2",
            "connector_format": "SOCKET",
            "connector_power_type": "AC_1_PHASE"
        },
        "currency": currency_code.into_str(),
        "total_energy": total_energy,
        "total_time": total_time,
        "total_parking_time": total_parking_time,
        "total_cost": total_cost,
        "total_energy_cost": total_energy_cost,
        "total_fixed_cost": total_fixed_cost,
        "total_parking_cost": total_idle_duration_cost,
        "total_time_cost": total_charging_duration_cost,
        "last_updated": last_updated,
        "charging_periods": charging_periods
    })
}

impl EventCollector {
    /// Create an `EventCollector` from a CDR datetime range.
    pub fn from_time_range(cdr_time_range: &Range<DateTime<Utc>>) -> Self {
        let session_duration = cdr_time_range
            .end
            .signed_duration_since(cdr_time_range.start);
        Self::with_session_duration(session_duration)
    }
}

/// Pad a field's name out to `len` bytes, so the CDR gets a dummy id that names the
/// field it fills.
///
/// None of the ids in a generated CDR is asserted anywhere. They exist to satisfy the required
/// fields at their exact maximum length, so an id that shows up in a length warning or a
/// failure message says which field it filled.
fn padded_id(field: &str, len: usize) -> String {
    const PAD: char = '-';

    let pad_len = len
        .checked_sub(field.len())
        .unwrap_or_else(|| panic!("the `{field}` id does not fit in {len} bytes"));
    let padding: String = std::iter::repeat_n(PAD, pad_len).collect();
    format!("{field}{padding}")
}

// ***********************************************************************************************
// The Serializable structs below are specialized copies of the general purpose CDR implementation
// as we only use `serde` in tests.
// ***********************************************************************************************

/// A single charging period, containing a nonempty list of charge dimensions.
///
/// * See: [OCPI spec 2.2.1: CDR ChargingPeriod](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc#mod_cdrs_chargingperiod_class>)
#[derive(serde::Serialize)]
struct ChargingPeriod {
    /// Start timestamp of the charging period. This period ends when a next period starts, the
    /// last period ends when the session ends.
    start_date_time: String,

    /// List of relevant values for this charging period.
    dimensions: Vec<Dimension>,

    /// Unique identifier of the Tariff that is relevant for this Charging Period. If not provided, no Tariff is relevant during this period.
    tariff_id: Option<String>,
}

impl From<super::ChargingPeriod> for ChargingPeriod {
    fn from(value: super::ChargingPeriod) -> Self {
        let super::ChargingPeriod {
            start_date_time,
            dimensions,
            tariff_id,
        } = value;
        Self {
            start_date_time: start_date_time.to_rfc3339(),
            dimensions: dimensions.into_iter().map(Dimension::from).collect(),
            tariff_id,
        }
    }
}

/// The volume that has been consumed for a specific dimension during a charging period.
///
/// * See: [OCPI spec 2.2.1: CDR Dimension](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc#mod_cdrs_cdrdimension_class>)
#[derive(serde::Serialize)]
struct Dimension {
    #[serde(rename = "type")]
    /// The dimension type.
    dimension_type: String,

    /// Volume of the dimension consumed, measured according to the dimension type.
    volume: Decimal,
}

impl From<super::Dimension> for Dimension {
    fn from(value: super::Dimension) -> Self {
        let super::Dimension {
            dimension_type,
            volume,
        } = value;
        Self {
            dimension_type: dimension_type.to_string(),
            volume: volume.round_to_ocpi_scale(),
        }
    }
}

/// A price consisting of a value including VAT, and a value excluding VAT.
#[derive(serde::Serialize, Default)]
struct Price {
    /// The price excluding VAT.
    excl_vat: f64,

    /// The price including VAT.
    ///
    /// If no vat is applicable this value will be equal to the `excl_vat`.
    ///
    /// If no vat could be determined this value will be `None`.
    /// The v211 tariffs can't determine VAT.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    incl_vat: Option<f64>,
}

impl From<money::Price> for Price {
    fn from(value: money::Price) -> Self {
        use rust_decimal::prelude::ToPrimitive as _;

        let money::Price { excl_vat, incl_vat } = value;
        Self {
            excl_vat: Decimal::from(excl_vat).to_f64().unwrap(),
            incl_vat: incl_vat.map(|d| Decimal::from(d).to_f64().unwrap()),
        }
    }
}

impl fmt::Display for super::DimensionType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            super::DimensionType::Energy => f.write_str("ENERGY"),
            super::DimensionType::MaxCurrent => f.write_str("MAX_CURRENT"),
            super::DimensionType::MinCurrent => f.write_str("MIN_CURRENT"),
            super::DimensionType::MaxPower => f.write_str("MAX_POWER"),
            super::DimensionType::MinPower => f.write_str("MIN_POWER"),
            super::DimensionType::ParkingTime => f.write_str("PARKING_TIME"),
            super::DimensionType::ReservationTime => f.write_str("RESERVATION_TIME"),
            super::DimensionType::Time => f.write_str("TIME"),
        }
    }
}