ocpi-tariffs 0.54.0

OCPI tariff calculations
Documentation
use std::assert_matches;

use crate::{
    cdr, json,
    price::{self, Warning},
    test::{self, datetime},
};

#[test]
fn should_not_warn_when_the_periods_lie_within_the_cdr_range() {
    test::setup();
    let json = cdr_json(
        "2022-01-13T16:00:00Z",
        "2022-01-13T19:12:00Z",
        &["2022-01-13T16:00:00Z", "2022-01-13T18:30:00Z"],
    );
    let doc = json::parse_object(&json).unwrap();
    let (cdr, mut warnings) = cdr::from_json(doc, crate::Version::V221).into_parts();
    // The CDR carries the fields the code under test reads and omits the rest, so the
    // spec's required fields are largely absent.
    warnings.remove_missing_fields();
    test::assert_schema_warnings(&warnings, &[]);

    let (_cdr, warnings) = cdr.to_v221().unwrap().into_parts();
    assert!(warnings.is_empty());
}

#[test]
fn should_fail_validation_start_end_range_doesnt_overlap_with_periods() {
    test::setup();

    let json = cdr_json(
        "2022-02-13T16:00:00Z",
        "2022-02-13T19:12:00Z",
        &["2022-01-13T16:00:00Z", "2022-01-13T18:30:00Z"],
    );
    let doc = json::parse_object(&json).unwrap();
    let (cdr, mut warnings) = cdr::from_json(doc, crate::Version::V221).into_parts();
    // The CDR carries the fields the code under test reads and omits the rest, so the
    // spec's required fields are largely absent.
    warnings.remove_missing_fields();
    test::assert_schema_warnings(&warnings, &[]);

    // The whole-CDR checks are made by `cdr::Versioned::to_v221`, not by the lowering.
    let (_cdr, warnings) = cdr.to_v221().unwrap().into_parts();
    let [warning] = warnings
        .into_path_as_str_map()
        .remove("$")
        .unwrap()
        .try_into()
        .unwrap();
    let Warning::PeriodsOutsideStartEndDateTime {
        cdr_range,
        period_range,
    } = warning
    else {
        panic!("expected PeriodsOutsideStartEndDateTime, got {warning:?}");
    };

    {
        assert_eq!(cdr_range.start, datetime("2022-02-13", "16:00"));
        assert_eq!(cdr_range.end, datetime("2022-02-13", "19:12"));
    }
    {
        let price::PeriodRange::Many(period_range) = period_range else {
            panic!("expected PeriodRange::Many, got {period_range:?}");
        };

        assert_eq!(period_range.start, datetime("2022-01-13", "16:00"));
        assert_eq!(period_range.end, datetime("2022-01-13", "18:30"));
    }
}

#[test]
fn should_warn_when_the_last_period_starts_after_the_cdr_ends() {
    test::setup();

    // Only the last period starts outside the CDR's range, so checking only the first period's
    // start would raise no `PeriodsOutsideStartEndDateTime` here.
    let json = cdr_json(
        "2022-01-13T16:00:00Z",
        "2022-01-13T18:00:00Z",
        &["2022-01-13T16:00:00Z", "2022-01-13T18:30:00Z"],
    );
    let doc = json::parse_object(&json).unwrap();
    let (cdr, mut warnings) = cdr::from_json(doc, crate::Version::V221).into_parts();
    // The CDR carries the fields the code under test reads and omits the rest, so the
    // spec's required fields are largely absent.
    warnings.remove_missing_fields();
    test::assert_schema_warnings(&warnings, &[]);

    let (_cdr, warnings) = cdr.to_v221().unwrap().into_parts();
    let warnings = warnings.into_path_as_str_map();
    let root_warnings = warnings.get("$").map(Vec::as_slice).unwrap_or_default();

    assert_matches!(
        root_warnings,
        [Warning::PeriodsOutsideStartEndDateTime {
            period_range: price::PeriodRange::Many(_),
            cdr_range: _
        }],
        "expected one `PeriodsOutsideStartEndDateTime` on `$`, got {warnings:#?}"
    );
}

#[test]
fn should_warn_when_the_only_period_starts_after_the_cdr_ends() {
    test::setup();

    // `cdr::Versioned::to_v221` checks a lone period apart from the first and last of several
    // periods, so a test with several periods can't catch this check breaking.
    let json = cdr_json(
        "2022-01-13T16:00:00Z",
        "2022-01-13T19:12:00Z",
        &["2022-01-13T20:00:00Z"],
    );
    let doc = json::parse_object(&json).unwrap();
    let (cdr, mut warnings) = cdr::from_json(doc, crate::Version::V221).into_parts();
    // The CDR carries the fields the code under test reads and omits the rest, so the
    // spec's required fields are largely absent.
    warnings.remove_missing_fields();
    test::assert_schema_warnings(&warnings, &[]);

    let (_cdr, warnings) = cdr.to_v221().unwrap().into_parts();
    let warnings = warnings.into_path_as_str_map();
    let root_warnings = warnings.get("$").map(Vec::as_slice).unwrap_or_default();

    assert_matches!(
        root_warnings,
        [Warning::PeriodsOutsideStartEndDateTime {
            period_range: price::PeriodRange::Single(_),
            cdr_range: _
        }],
        "expected one `PeriodsOutsideStartEndDateTime` on `$`, got {warnings:#?}"
    );
}

#[test]
fn should_fail_validation_without_charging_periods() {
    test::setup();

    let json = cdr_json("2022-01-13T16:00:00Z", "2022-01-13T19:12:00Z", &[]);
    let doc = json::parse_object(&json).unwrap();
    let cdr = cdr::from_json(doc, crate::Version::V221).ignore_warnings();

    // There is nothing to price. The empty array itself is located by the schema walk's
    // `Cardinality` warning.
    let err = cdr.to_v221().unwrap_err();
    let error = err.unwrap();

    assert_matches!(error.into_warning(), Warning::NoPeriods);
}

#[test]
fn should_fail_when_dimension_volume_is_missing() {
    test::setup();

    let json = serde_json::json!({
        "country_code": "NL",
        "party_id": "ENE",
        "start_date_time": "2022-01-13T16:00:00Z",
        "end_date_time": "2022-01-13T19:12:00Z",
        "currency": "EUR",
        "tariffs": [],
        "cdr_location": { "country": "NLD" },
        "charging_periods": [
            {
                "start_date_time": "2022-01-13T16:00:00Z",
                "dimensions": [{ "type": "TIME" }]
            }
        ],
        "total_cost": { "excl_vat": 4.00, "incl_vat": 4.40 },
        "total_time": 3.2,
        "total_energy": 0,
        "last_updated": "2022-01-13T00:00:00Z"
    })
    .to_string();

    let doc = json::parse_object(&json).unwrap();
    let (cdr, mut warnings) = cdr::from_json(doc, crate::Version::V221).into_parts();
    // The CDR carries the fields the code under test reads and omits the rest, so the
    // spec's required fields are largely absent.
    warnings.remove_missing_fields();
    test::assert_schema_warnings(&warnings, &[]);

    // The missing `volume` is located by the schema walk; the lowering only reports that it
    // rejected the dimension.
    let err = cdr.to_v221().unwrap_err();
    let error = err.unwrap();

    assert_matches!(error.into_warning(), Warning::Rejected);
}

/// The JSON of a CDR running from `start_date_time` to `end_date_time`, with one charging period
/// starting at each of `period_start_date_times`.
///
/// Each period has a `TIME` dimension with a `volume` of `1.0`, and every call gets the same
/// totals, so the totals don't add up to the periods. The checks in `cdr::Versioned::to_v221`
/// compare the CDR's start and end with the periods' starts, and read neither the volumes nor the
/// totals.
fn cdr_json(
    start_date_time: &str,
    end_date_time: &str,
    period_start_date_times: &[&str],
) -> String {
    let mut charging_periods = Vec::new();

    for period_start_date_time in period_start_date_times {
        charging_periods.push(serde_json::json!({
            "start_date_time": period_start_date_time,
            "dimensions": [{ "type": "TIME", "volume": 1.0 }]
        }));
    }

    let value = serde_json::json!({
        "country_code": "NL",
        "party_id": "ENE",
        "start_date_time": start_date_time,
        "end_date_time": end_date_time,
        "currency": "EUR",
        "tariffs": [],
        "cdr_location": {
            "country": "NLD"
        },
        "charging_periods": charging_periods,
        "total_cost": {
            "excl_vat": 11.25,
            "incl_vat": 12.75
        },
        "total_time_cost": {
            "excl_vat": 7.5,
            "incl_vat": 8.25
        },
        "total_parking_time": 0.7,
        "total_parking_cost": {
            "excl_vat": 3.75,
            "incl_vat": 4.5
        },
        "total_time": 3.2,
        "total_energy": 0,
        "last_updated": "2022-01-13T00:00:00Z"
    });

    value.to_string()
}