ocpi-tariffs 0.54.0

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

use super::{Consumed, Period};
use crate::{Kwh, Version, json, price, tariff, test};

#[test]
fn should_end_each_period_where_the_next_one_starts_when_given_out_of_order() {
    const TARIFF_JSON: &str = include_str!(
        "../../test_data/v211/real_world/time_and_parking_time_separate_tariff/tariff.json"
    );
    test::setup();

    let (tariff, warnings) =
        tariff::from_json(json::parse_object(TARIFF_JSON).unwrap(), Version::V211).into_parts();
    test::assert_schema_warnings(&warnings, &[]);
    let (tariff, warnings) = tariff.to_v221().unwrap().into_parts();
    assert!(warnings.is_empty(), "{:#?}", warnings.path_id_map());

    let first = test::datetime("2025-04-09", "16:00");
    let second = test::datetime("2025-04-09", "16:15");
    let third = test::datetime("2025-04-09", "16:30");
    let end = test::datetime("2025-04-09", "16:45");

    // The periods are listed latest first. `price::periods` takes each period's end from the
    // start of the period after it in the list, so a version that skipped the sort would end the
    // 16:30 period at 16:15 and report the periods in the order given. The totals cannot show that
    // fault, because each one is summed from the periods' `Consumed` volumes in any order, so the
    // test asserts the boundaries.
    let periods = [third, second, first]
        .into_iter()
        .map(|start_date_time| Period {
            start_date_time,
            consumed: Consumed {
                duration_charging: Some(TimeDelta::minutes(15)),
                energy: Some(Kwh::from(dec!(2))),
                ..Default::default()
            },
        })
        .collect();

    let report = price::periods(end, chrono_tz::Europe::Amsterdam, &tariff, periods).unwrap();

    let boundaries = report
        .periods
        .iter()
        .map(|period| (period.start_date_time, period.end_date_time))
        .collect::<Vec<_>>();

    assert_eq!(boundaries, [(first, second), (second, third), (third, end)]);
}