ocpi-tariffs 0.54.0

OCPI tariff calculations
Documentation
//! Generation against a tariff whose elements restrict on power.
//!
//! The supply is constant, so an element restricting power either admits it or excludes it. What
//! the generated CDR has to do in both cases is state the power, because a CDR that omits the
//! quantity has the pricer read the restriction as satisfied and apply an element the supply
//! excludes.

use rust_decimal_macros::dec;

use super::test;
use crate::{
    Money, Price, Version, assert_approx_eq, cdr,
    generate::{self, Dimension, DimensionType},
    json,
    price::{self, test::UnwrapReport as _},
    tariff,
};

const DATE: &str = "2025-11-10";

/// EUR 1.00/kWh up to 16 kW, and EUR 0.10/kWh otherwise. A 24 kW supply is outside the first
/// element's window, so the catch-all prices the session.
const EXCLUDED_BY_MAX_POWER: &str = r#"{
    "country_code": "DE",
    "party_id": "ALL",
    "id": "1",
    "currency": "EUR",
    "type": "REGULAR",
    "elements": [
        {
            "price_components": [{ "type": "ENERGY", "price": 1.00, "step_size": 1 }],
            "restrictions": { "max_power": 16.0 }
        },
        {
            "price_components": [{ "type": "ENERGY", "price": 0.10, "step_size": 1 }]
        }
    ],
    "last_updated": "2018-12-05T12:01:09Z"
}
"#;

/// EUR 5.00/kWh up to 16 kW, EUR 1.00/kWh from 10 kW, and EUR 0.10/kWh otherwise. A 24 kW supply
/// is admitted by the second element only.
const ADMITTED_BY_MIN_POWER: &str = r#"{
    "country_code": "DE",
    "party_id": "ALL",
    "id": "1",
    "currency": "EUR",
    "type": "REGULAR",
    "elements": [
        {
            "price_components": [{ "type": "ENERGY", "price": 5.00, "step_size": 1 }],
            "restrictions": { "max_power": 16.0 }
        },
        {
            "price_components": [{ "type": "ENERGY", "price": 1.00, "step_size": 1 }],
            "restrictions": { "min_power": 10.0 }
        },
        {
            "price_components": [{ "type": "ENERGY", "price": 0.10, "step_size": 1 }]
        }
    ],
    "last_updated": "2018-12-05T12:01:09Z"
}
"#;

/// EUR 0.60/kWh up to 16 kW, EUR 0.70/kWh up to 32 kW, and EUR 0.50/kWh otherwise. A
/// 24 kW supply is admitted by the second element only, so a CDR that states no power lets the
/// first element price the session at EUR 0.60 and the round trip diverges.
const BRACKETED_BY_MAX_POWER: &str = r#"{
    "country_code": "DE",
    "party_id": "ALL",
    "id": "1",
    "currency": "EUR",
    "type": "REGULAR",
    "elements": [
        {
            "price_components": [{ "type": "ENERGY", "price": 0.60, "step_size": 1 }],
            "restrictions": { "max_power": 16.0 }
        },
        {
            "price_components": [{ "type": "ENERGY", "price": 0.70, "step_size": 1 }],
            "restrictions": { "max_power": 32.0 }
        },
        {
            "price_components": [{ "type": "ENERGY", "price": 0.50, "step_size": 1 }]
        }
    ],
    "last_updated": "2018-12-05T12:01:09Z"
}
"#;

/// One hour at 24 kW, which draws exactly the 24 kWh requested, so the session never idles.
fn config() -> generate::Config {
    generate::Config {
        timezone: chrono_tz::Europe::Amsterdam,
        start_date_time: crate::test::datetime(DATE, "10:00:00"),
        end_date_time: crate::test::datetime(DATE, "11:00:00"),
        max_power_supply_kw: 24.into(),
        requested_kwh: 24.into(),
        max_current_supply_amp: 40.into(),
    }
}

#[track_caller]
fn parse_tariff(tariff_json: &str) -> tariff::Versioned<'_> {
    tariff::from_versioned_json(
        tariff::infer_version(json::parse_object(tariff_json).unwrap()).unwrap_certain(),
    )
    .ignore_warnings()
}

#[track_caller]
fn generate(tariff_json: &str) -> generate::Caveat<generate::Report> {
    generate::cdr_from_tariff(&parse_tariff(tariff_json), &config()).unwrap()
}

fn volume_of(dimensions: &[Dimension], wanted: &DimensionType) -> Option<rust_decimal::Decimal> {
    dimensions
        .iter()
        .find(|dim| &dim.dimension_type == wanted)
        .map(|dim| dim.volume)
}

#[test]
fn an_element_the_supply_excludes_does_not_price_the_session() {
    let (report, warnings) = generate(EXCLUDED_BY_MAX_POWER).into_parts();
    assert!(warnings.is_empty(), "{:#?}", warnings.path_id_map());

    // 24 kWh at the catch-all's EUR 0.10, not at the EUR 1.00 of an element restricted to 16 kW.
    assert_approx_eq!(
        report.partial_cdr.total_cost,
        Some(Price {
            excl_vat: Money::from(dec!(2.40)),
            incl_vat: Some(Money::from(dec!(2.40))),
        })
    );
}

#[test]
fn a_charging_period_states_the_power_an_element_restricts_on() {
    let (report, _warnings) = generate(EXCLUDED_BY_MAX_POWER).into_parts();
    let periods = report.partial_cdr.charging_periods;

    assert_eq!(periods.len(), 1);
    assert_eq!(
        volume_of(&periods[0].dimensions, &DimensionType::MaxPower),
        Some(24.into())
    );
    assert_eq!(
        volume_of(&periods[0].dimensions, &DimensionType::MinPower),
        Some(24.into())
    );
}

#[test]
fn a_lower_bound_the_supply_satisfies_prices_the_session() {
    let (report, warnings) = generate(ADMITTED_BY_MIN_POWER).into_parts();
    assert!(warnings.is_empty(), "{:#?}", warnings.path_id_map());

    // 24 kWh at the EUR 1.00 of the `min_power: 10` element, which 24 kW satisfies. Reading the
    // bounds as an `Option` range made this element unreachable, and the EUR 5.00 element won.
    assert_approx_eq!(
        report.partial_cdr.total_cost,
        Some(Price {
            excl_vat: Money::from(dec!(24.00)),
            incl_vat: Some(Money::from(dec!(24.00))),
        })
    );
}

/// Generate a CDR, price the CDR that was generated, and require the two totals to
/// agree at `expected_excl_vat`.
///
/// A round trip is what a charging period omitting a restricted-on quantity breaks: the
/// generator prices the element whose window the supply falls in, while the pricer reads the
/// absent quantity as satisfying every bound and applies an earlier element instead.
#[track_caller]
fn assert_round_trip(tariff_json: &str, expected_excl_vat: Money) {
    let tariff = parse_tariff(tariff_json);

    let (report, warnings) = generate::cdr_from_tariff(&tariff, &config())
        .unwrap()
        .into_parts();
    assert!(warnings.is_empty(), "{:#?}", warnings.path_id_map());

    assert_approx_eq!(
        report.partial_cdr.total_cost,
        Some(Price {
            excl_vat: expected_excl_vat,
            incl_vat: Some(expected_excl_vat),
        })
    );

    let cdr_json = serde_json::to_string(&test::partial_to_cdr(report.partial_cdr)).unwrap();
    let (cdr, warnings) =
        cdr::from_json(json::parse_object(&cdr_json).unwrap(), Version::V221).into_parts();
    crate::test::assert_schema_warnings(&warnings, &[]);

    let tariff_source = price::TariffSource::Override(vec![tariff]);
    let (priced, warnings) = price::cdr(&cdr, tariff_source, config().timezone)
        .unwrap_report(cdr.as_json_str())
        .into_parts();
    assert!(warnings.is_empty(), "{:#?}", warnings.path_id_map());

    let total_cost = priced.total_cost.calculated.unwrap();
    assert_approx_eq!(total_cost.excl_vat, expected_excl_vat);
}

/// 24 kWh at the EUR 0.70 of the element whose 32 kW bound a 24 kW supply satisfies,
/// both as the generator reports it and as the emitted CDR reprices.
///
/// A CDR stating no power reprices at the EUR 0.60 of the element restricted to 16 kW, for
/// EUR 14.40.
#[test]
fn repricing_a_bracketed_tariff_gives_the_total_the_generator_reported() {
    assert_round_trip(BRACKETED_BY_MAX_POWER, Money::from(dec!(16.80)));
}

/// 24 kWh at the catch-all's EUR 0.10, both as the generator reports it and as the
/// emitted CDR reprices.
///
/// No element admits a 24 kW supply, which is the case that also needs the power stated
/// whenever an element restricts on it rather than only when the supply falls in its window. A
/// CDR stating no power reprices at the EUR 1.00 of the element restricted to 16 kW, for
/// EUR 24.00.
#[test]
fn repricing_an_excluding_tariff_gives_the_total_the_generator_reported() {
    assert_round_trip(EXCLUDED_BY_MAX_POWER, Money::from(dec!(2.40)));
}