ocpi-tariffs 0.55.0

OCPI tariff calculations
Documentation
use std::assert_matches;

use rust_decimal_macros::dec;

use crate::{Kwh, cdr, duration, generate, price, tariff, test};

// Tariff with two elements:
// - element 0: 1.00 EUR/kWh, restricted to RESERVATION sessions only + max_duration: 3600
// - element 1: 0.30 EUR/kWh, no restriction (fallback)
//
// Without ignoring elements that have a `reservation` restriction, the `max_duration`
// from element 0 would inject a spurious period boundary at 3600 s into the timeline.
// Splitting a 2-hour session into two charging periods.
const TARIFF_WITH_RESERVATION_AND_MAX_DURATION: &str = r#"{
    "country_code": "DE",
    "party_id": "ALL",
    "id": "T_RES",
    "currency": "EUR",
    "elements": [
        {
            "price_components": [
                { "type": "ENERGY", "price": 1.00, "vat": 0.0, "step_size": 1 }
            ],
            "restrictions": {
                "reservation": "RESERVATION",
                "max_duration": 3600
            }
        },
        {
            "price_components": [
                { "type": "ENERGY", "price": 0.30, "vat": 0.0, "step_size": 1 }
            ]
        }
    ],
    "last_updated": "2025-01-01T00:00:00Z"
}"#;

#[test]
fn should_not_split_period_at_reservation_element_max_duration() {
    // 2-hour session - longer than the reservation element's max_duration of 3600 s.
    // The reservation element must be completely ignored during timeline construction,
    // so the generated CDR should have exactly one charging period.
    let tariff = tariff::test::build(TARIFF_WITH_RESERVATION_AND_MAX_DURATION);
    let config = generate::Config {
        timezone: jiff::tz::get!("Europe/Amsterdam"),
        start_date_time: test::datetime(DATE, "10:00:00"),
        end_date_time: test::datetime(DATE, "12:00:00"),
        max_power_supply_kw: 11.into(),
        requested_kwh: 100.into(),
        max_current_supply_amp: 16.into(),
    };

    let report = cdr::generate_from_tariff(&tariff, &config).unwrap();
    let (report, warnings) = report.into_parts();

    let id_map = warnings.path_id_map();
    let has_reservation_warning = id_map
        .values()
        .flatten()
        .any(|id| id.as_str() == "reservation_element_skipped");
    assert!(
        has_reservation_warning,
        "expected reservation_element_skipped warning, got: {id_map:#?}"
    );

    let periods = &report.partial_cdr.charging_periods;
    assert_eq!(
        periods.len(),
        1,
        "reservation element's max_duration must not create a period split; got {} periods",
        periods.len()
    );
}

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

#[test]
fn should_state_periods_that_sum_to_the_energy_supplied() {
    // Two `max_duration` bounds split one hour of charging into three periods of 1200 s. At 2 kW
    // each period supplies 0.666...7 kWh, which no four-decimal volume states exactly. Each period
    // states the difference between the rounded energy supplied by its end and by its start, so
    // the three sum to 2 kWh.
    const TARIFF_JSON: &str = r#"{
    "country_code": "DE",
    "party_id": "ALL",
    "id": "T_THIRDS",
    "currency": "EUR",
    "elements": [
        {
            "price_components": [
                { "type": "ENERGY", "price": 0.80, "vat": 0.0, "step_size": 1 }
            ],
            "restrictions": { "max_duration": 1200 }
        },
        {
            "price_components": [
                { "type": "ENERGY", "price": 0.80, "vat": 0.0, "step_size": 1 }
            ],
            "restrictions": { "max_duration": 2400 }
        },
        {
            "price_components": [
                { "type": "ENERGY", "price": 0.80, "vat": 0.0, "step_size": 1 }
            ]
        }
    ],
    "last_updated": "2025-01-01T00:00:00Z"
}"#;

    let tariff = tariff::test::build(TARIFF_JSON);
    let config = generate::Config {
        timezone: jiff::tz::get!("Europe/Amsterdam"),
        start_date_time: test::datetime(DATE, "14:00:00"),
        end_date_time: test::datetime(DATE, "15:00:00"),
        max_power_supply_kw: 2.into(),
        requested_kwh: 2.into(),
        max_current_supply_amp: 16.into(),
    };

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

    let energy_volumes: Vec<_> = report
        .partial_cdr
        .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!(0.6667), dec!(0.6666), dec!(0.6667)]
    );
    assert_eq!(report.partial_cdr.total_energy, Some(Kwh::from(dec!(2))));
}

// Charging time is billed only from 2025-11-11, so a session that crosses that midnight is
// billed for its time after midnight alone.
const TARIFF_WITH_TIME_FROM_START_DATE: &str = r#"{
    "country_code": "DE",
    "party_id": "ALL",
    "id": "T_DATE",
    "currency": "EUR",
    "elements": [
        {
            "price_components": [
                { "type": "TIME", "price": 2.00, "vat": 0.0, "step_size": 1 }
            ],
            "restrictions": { "start_date": "2025-11-11" }
        },
        {
            "price_components": [
                { "type": "ENERGY", "price": 0.30, "vat": 0.0, "step_size": 1 }
            ]
        }
    ],
    "last_updated": "2025-01-01T00:00:00Z"
}"#;

#[test]
fn should_bill_time_from_the_start_date_midnight_a_session_crosses() {
    // Amsterdam time (UTC+1), charging at 4 kW throughout. Energy is EUR 0.30/kWh throughout,
    // and charging time EUR 2.00/h from the `start_date`.
    //
    //                       2025-11-10              | 2025-11-11 (start_date)
    //   session             22:00 ----------------------------------------- 02:00
    //   date restriction                            [---------------------------->
    //   periods             [ 2 h, 8 kWh ----------][ 2 h, 8 kWh ----------]
    //   billed                EUR 2.40                EUR 2.40 + EUR 4.00
    let tariff = tariff::test::build(TARIFF_WITH_TIME_FROM_START_DATE);
    let config = generate::Config {
        timezone: jiff::tz::get!("Europe/Amsterdam"),
        start_date_time: test::datetime("2025-11-10", "21:00:00"),
        end_date_time: test::datetime("2025-11-11", "01:00:00"),
        max_power_supply_kw: 4.into(),
        requested_kwh: 16.into(),
        max_current_supply_amp: 16.into(),
    };

    let (report, _warnings) = cdr::generate_from_tariff(&tariff, &config)
        .unwrap()
        .into_parts();

    let periods = &report.partial_cdr.charging_periods;
    let [before_midnight, after_midnight] = periods.as_slice() else {
        panic!("expected two charging periods, got {periods:#?}");
    };
    assert_eq!(
        before_midnight.start_date_time,
        test::datetime("2025-11-10", "21:00:00")
    );
    assert_eq!(
        after_midnight.start_date_time,
        test::datetime("2025-11-10", "23:00:00")
    );
    let total_cost = report.partial_cdr.total_cost.unwrap();
    assert_eq!(total_cost.excl_vat, crate::Money::from(dec!(8.80)));
}

/// The `Failure` of a refused `generate` holds every warning raised before the failure, as
/// well as the error that stopped it.
#[test]
fn should_keep_the_warnings_raised_before_a_step_size_overflow_refuses_to_generate() {
    // The tariff's `end_date_time` is in 2020, before the session on `DATE` starts.
    // `generate` raises `NotActive` for that before it prices the generated periods.
    // A `step_size` of `10000000000000000` seconds is more milliseconds than an `i64` holds.
    // Rounding the charging time up to that step overflows, which refuses to generate.
    const TARIFF_JSON: &str = r#"{
    "country_code": "DE",
    "party_id": "ALL",
    "id": "1",
    "currency": "EUR",
    "type": "REGULAR",
    "end_date_time": "2020-01-01T00:00:00Z",
    "elements": [
        {
            "price_components": [
                { "type": "TIME", "price": 2.00, "vat": 0.0, "step_size": 10000000000000000 }
            ]
        }
    ],
    "last_updated": "2018-12-05T12:01:09Z"
}
"#;

    test::setup();

    let tariff = tariff::test::build(TARIFF_JSON);
    let config = generate::Config {
        timezone: jiff::tz::get!("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(),
    };

    let Err(failure) = cdr::generate_from_tariff(&tariff, &config) else {
        panic!("a step size that overflows should refuse to generate");
    };
    let (error, warnings) = failure.into_parts();
    let (error, _element) = error.into_parts();

    assert_matches!(
        error,
        generate::Warning::Price(price::Warning::Duration(duration::Warning::Overflow))
    );
    assert!(
        warnings.contains(|warning| matches!(warning, generate::Warning::NotActive)),
        "the refusal should keep the warning raised before pricing"
    );
}