ocpi-tariffs 0.54.0

OCPI tariff calculations
Documentation
use std::assert_matches;

use rust_decimal_macros::dec;

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

// 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 doc = json::parse_object(TARIFF_WITH_RESERVATION_AND_MAX_DURATION).unwrap();
    let tariff =
        tariff::from_versioned_json(tariff::infer_version(doc).unwrap_certain()).ignore_warnings();
    let config = generate::Config {
        timezone: chrono_tz::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 = generate::cdr_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_warn_no_elements() {
    const TARIFF_JSON: &str = r#"{
    "country_code": "DE",
    "party_id": "ALL",
    "id": "1",
    "currency": "EUR",
    "type": "REGULAR",
    "elements": [],
    "last_updated": "2018-12-05T12:01:09Z"
}
"#;

    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: 80.into(),
        max_current_supply_amp: 2.into(),
    };
    let failure = generate::cdr_from_tariff(&tariff, &config).unwrap_only_error();
    let generate::Warning::Tariff(warning) = failure.into_warning() else {
        panic!("expected a generate::Warning::Tariff");
    };
    assert_matches!(warning, tariff::Warning::NoElements);
}

#[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 doc = json::parse_object(TARIFF_JSON).unwrap();
    let tariff =
        tariff::from_versioned_json(tariff::infer_version(doc).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: 2.into(),
        requested_kwh: 2.into(),
        max_current_supply_amp: 16.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 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 doc = json::parse_object(TARIFF_WITH_TIME_FROM_START_DATE).unwrap();
    let tariff =
        tariff::from_versioned_json(tariff::infer_version(doc).unwrap_certain()).ignore_warnings();
    let config = generate::Config {
        timezone: chrono_tz::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) = generate::cdr_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)));
}