ocpi-tariffs 0.54.0

OCPI tariff calculations
Documentation
use chrono::TimeDelta;
use rust_decimal_macros::dec;
use std::assert_matches;

use crate::{
    Kwh, Money, Price, assert_approx_eq,
    generate::{self, PartialCdr},
    json, tariff, test,
    warning::test::VerdictTestExt as _,
};

const DATE: &str = "2025-11-10";
const TARIFF_JSON: &str = r#"{
    "country_code": "DE",
    "party_id": "ALL",
    "id": "1",
    "currency": "EUR",
    "type": "REGULAR",
    "elements": [
        {
            "price_components": [{
                  "type": "ENERGY",
                  "price": 0.50,
                  "vat": 20.0,
                  "step_size": 1
            }]
        }
    ],
    "last_updated": "2018-12-05T12:01:09Z"
}
"#;

fn generate_config() -> generate::Config {
    generate::Config {
        timezone: chrono_tz::Europe::Amsterdam,
        start_date_time: test::datetime(DATE, "15:02:12"),
        end_date_time: test::datetime(DATE, "15:12:12"),
        max_power_supply_kw: 12.into(),
        requested_kwh: 80.into(),
        max_current_supply_amp: 2.into(),
    }
}

#[track_caller]
fn generate(tariff_json: &str) -> generate::Caveat<generate::Report> {
    let tariff = tariff::from_versioned_json(
        tariff::infer_version(json::parse_object(tariff_json).unwrap()).unwrap_certain(),
    )
    .ignore_warnings();
    generate::cdr_from_tariff(&tariff, &generate_config()).unwrap()
}

#[test]
fn should_warn_duration_below_min() {
    let tariff = tariff::from_versioned_json(
        tariff::infer_version(json::parse_object(TARIFF_JSON).unwrap()).unwrap_certain(),
    )
    .ignore_warnings();
    let config = generate::Config {
        timezone: chrono_tz::Europe::Amsterdam,
        start_date_time: test::datetime(DATE, "15:02:12"),
        end_date_time: test::datetime(DATE, "15:03:12"),
        max_power_supply_kw: 12.into(),
        requested_kwh: 80.into(),
        max_current_supply_amp: 2.into(),
    };
    let failure = generate::cdr_from_tariff(&tariff, &config).unwrap_only_error();
    assert_matches!(
        failure.into_warning(),
        generate::Warning::DurationBelowMinimum
    );
}

#[test]
fn should_warn_end_before_start() {
    let tariff = tariff::from_versioned_json(
        tariff::infer_version(json::parse_object(TARIFF_JSON).unwrap()).unwrap_certain(),
    )
    .ignore_warnings();
    let config = generate::Config {
        timezone: chrono_tz::Europe::Amsterdam,
        start_date_time: test::datetime(DATE, "15:12:12"),
        end_date_time: test::datetime(DATE, "15:02:12"),
        max_power_supply_kw: 12.into(),
        requested_kwh: 80.into(),
        max_current_supply_amp: 2.into(),
    };
    let failure = generate::cdr_from_tariff(&tariff, &config).unwrap_only_error();
    assert_matches!(
        failure.into_warning(),
        generate::Warning::StartDateTimeIsAfterEndDateTime
    );
}

#[test]
fn should_warn_requested_kwh_is_zero() {
    let tariff = tariff::from_versioned_json(
        tariff::infer_version(json::parse_object(TARIFF_JSON).unwrap()).unwrap_certain(),
    )
    .ignore_warnings();
    let config = generate::Config {
        timezone: chrono_tz::Europe::Amsterdam,
        start_date_time: test::datetime(DATE, "15:02:12"),
        end_date_time: test::datetime(DATE, "15:12:12"),
        max_power_supply_kw: 12.into(),
        requested_kwh: 0.into(),
        max_current_supply_amp: 2.into(),
    };
    let failure = generate::cdr_from_tariff(&tariff, &config).unwrap_only_error();
    assert_matches!(
        failure.into_warning(),
        generate::Warning::RequestedKwhIsZero
    );
}

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

    let PartialCdr {
        party_id: _,
        start_date_time: _,
        end_date_time: _,
        currency_code: _,
        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: _,
    } = report.partial_cdr;

    assert_approx_eq!(
        total_cost,
        Some(Price {
            excl_vat: Money::from(dec!(1)),
            incl_vat: Some(Money::from(dec!(1.2)))
        })
    );
    assert_eq!(
        total_charging_duration,
        Some(TimeDelta::minutes(10)),
        "The charging session is 10 min and is stopped before the battery is fully charged."
    );
    assert_eq!(
        total_idle_duration, None,
        "There is no idle time since the battery never fully charged."
    );
    assert_approx_eq!(total_energy, Some(Kwh::from(dec!(2))));
    assert_approx_eq!(
        total_energy_cost,
        Some(Price {
            excl_vat: Money::from(dec!(1)),
            incl_vat: Some(Money::from(dec!(1.2)))
        }),
        "The cost per KwH is 50 cents and the VAT is 20%."
    );
    assert_eq!(total_fixed_cost, None, "There are no fixed costs.");
    assert_eq!(
        total_idle_duration_cost, None,
        "There is no idle cost as there is no parking time."
    );
    assert_eq!(
        total_charging_duration_cost, None,
        "There are no time costs defined in the tariff."
    );
}

#[test]
fn should_bill_the_energy_supplied_in_whole_steps_without_an_extra_step() {
    // 40 kWh at 24 kW takes 6000 seconds, which is 1.666...667 hours at the 28 significant digits
    // a `Decimal` holds. A generator that computed the energy as the power times those hours would
    // supply 40.000...001 kWh. The step size of 1000 Wh would bill that as 41 kWh, a total of
    // 28.70.
    const TARIFF_JSON: &str = r#"{
        "country_code": "NL",
        "party_id": "TDR",
        "id": "KWH_STEP",
        "currency": "EUR",
        "elements": [
            {
                "price_components": [{
                      "type": "ENERGY",
                      "price": 0.70,
                      "step_size": 1000
                }]
            }
        ],
        "last_updated": "2020-01-01T00:00:00Z"
    }"#;

    let tariff = tariff::from_versioned_json(
        tariff::infer_version(json::parse_object(TARIFF_JSON).unwrap()).unwrap_certain(),
    )
    .ignore_warnings();
    let config = generate::Config {
        timezone: chrono_tz::Europe::Amsterdam,
        start_date_time: test::datetime(DATE, "14:00:00"),
        end_date_time: test::datetime(DATE, "16:00:00"),
        max_power_supply_kw: 24.into(),
        requested_kwh: 40.into(),
        max_current_supply_amp: 4.into(),
    };
    let report = generate::cdr_from_tariff(&tariff, &config).unwrap();
    let (report, warnings) = report.into_parts();
    assert!(warnings.is_empty(), "{:#?}", warnings.path_id_map());

    let PartialCdr {
        party_id: _,
        start_date_time: _,
        end_date_time: _,
        currency_code: _,
        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: _,
    } = report.partial_cdr;

    assert_eq!(
        total_energy,
        Some(Kwh::from(dec!(40))),
        "The premise: the session supplies all 40 kWh requested, so 28 is 40 steps of 1000 Wh."
    );
    assert_eq!(
        total_energy_cost,
        Some(Price {
            excl_vat: Money::from(dec!(28)),
            incl_vat: Some(Money::from(dec!(28)))
        })
    );
}

#[test]
fn should_bill_the_energy_the_cdr_states_when_the_charging_time_is_not_a_whole_nanosecond() {
    // 1 kWh at 7 kW takes 514285714285.71 ns, and the generator charges for a whole number of
    // nanoseconds. The extra 0.29 ns supplies energy far below the four decimals OCPI allows. The
    // generator rounds that energy away, so the step size of 1000 Wh bills 1 kWh rather than 2.
    const TARIFF_JSON: &str = r#"{
        "country_code": "NL",
        "party_id": "TDR",
        "id": "KWH_STEP",
        "currency": "EUR",
        "elements": [
            {
                "price_components": [{
                      "type": "ENERGY",
                      "price": 0.80,
                      "step_size": 1000
                }]
            }
        ],
        "last_updated": "2020-01-01T00:00:00Z"
    }"#;

    let tariff = tariff::from_versioned_json(
        tariff::infer_version(json::parse_object(TARIFF_JSON).unwrap()).unwrap_certain(),
    )
    .ignore_warnings();
    let config = generate::Config {
        timezone: chrono_tz::Europe::Amsterdam,
        start_date_time: test::datetime(DATE, "14:00:00"),
        end_date_time: test::datetime(DATE, "15:00:00"),
        max_power_supply_kw: 7.into(),
        requested_kwh: 1.into(),
        max_current_supply_amp: 4.into(),
    };
    let report = generate::cdr_from_tariff(&tariff, &config).unwrap();
    let (report, warnings) = report.into_parts();
    assert!(warnings.is_empty(), "{:#?}", warnings.path_id_map());

    let PartialCdr {
        party_id: _,
        start_date_time: _,
        end_date_time: _,
        currency_code: _,
        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,
    } = report.partial_cdr;

    let energy_volumes: Vec<_> = charging_periods
        .iter()
        .flat_map(|period| &period.dimensions)
        .filter(|dimension| dimension.dimension_type == generate::DimensionType::Energy)
        .map(|dimension| dimension.volume)
        .collect();

    assert_eq!(energy_volumes, vec![dec!(1)]);
    assert_eq!(total_energy, Some(Kwh::from(dec!(1))));
    assert_eq!(
        total_energy_cost,
        Some(Price {
            excl_vat: Money::from(dec!(0.80)),
            incl_vat: Some(Money::from(dec!(0.80)))
        })
    );
}

#[test]
fn should_warn_no_element_prices_session_when_the_min_price_is_the_total_cost() {
    // A generator that checked for an unpriced session after applying the `min_price` would find a
    // total, and would raise only `total_cost_clamped_to_min`.
    const TARIFF_JSON: &str = r#"{
        "country_code": "NL",
        "party_id": "TDR",
        "id": "MIN_PRICE_ONLY",
        "currency": "EUR",
        "min_price": {
            "excl_vat": 3.00,
            "incl_vat": 3.60
        },
        "elements": [
            {
                "price_components": [{
                      "type": "ENERGY",
                      "price": 0.50,
                      "vat": 20.0,
                      "step_size": 1
                }],
                "restrictions": {
                    "start_date": "2025-11-11"
                }
            }
        ],
        "last_updated": "2020-01-01T00:00:00Z"
    }"#;

    let tariff = tariff::from_versioned_json(
        tariff::infer_version(json::parse_object(TARIFF_JSON).unwrap()).unwrap_certain(),
    )
    .ignore_warnings();
    let config = generate::Config {
        timezone: chrono_tz::Europe::Amsterdam,
        start_date_time: test::datetime("2025-11-10", "15:02:12"),
        end_date_time: test::datetime("2025-11-10", "15:12:12"),
        max_power_supply_kw: 12.into(),
        requested_kwh: 80.into(),
        max_current_supply_amp: 2.into(),
    };
    let report = generate::cdr_from_tariff(&tariff, &config).unwrap();
    let (report, warnings) = report.into_parts();
    let warning_ids: Vec<_> = warnings
        .path_id_map()
        .into_values()
        .flatten()
        .map(|id| id.to_string())
        .collect();
    assert_eq!(
        warning_ids,
        ["no_element_prices_session", "total_cost_clamped_to_min"]
    );

    assert_eq!(
        report.partial_cdr.total_cost,
        Some(Price {
            excl_vat: Money::from(dec!(3.00)),
            incl_vat: Some(Money::from(dec!(3.60)))
        })
    );
}

#[test]
fn should_price_a_session_under_an_empty_day_of_week() {
    // OCPI reads an empty `day_of_week` the same as an omitted one, so the element prices the
    // session. This test checks that the generated CDR states an energy cost and that the generator
    // raises no warning, such as `no_element_prices_session`.
    let tariff_json = TARIFF_JSON.replace(
        r#""price_components""#,
        r#""restrictions": { "day_of_week": [] }, "price_components""#,
    );
    let report = generate(&tariff_json);
    let (report, warnings) = report.into_parts();
    assert!(warnings.is_empty(), "{:#?}", warnings.path_id_map());

    assert!(
        report.partial_cdr.total_energy_cost.is_some(),
        "the element with an empty `day_of_week` prices the session's energy"
    );
}