ocpi-tariffs 0.55.0

OCPI tariff calculations
Documentation
//! Tests that the caller holds the warnings of the tariffs when pricing a CDR fails, because the
//! caller builds the tariffs before pricing.
//!
//! The test gives a tariff a `country_code` of `nl`, for which building the tariff raises
//! `IncorrectCase`.

use std::assert_matches;

use serde_json::json;

use crate::{Version, cdr, country, json, price, tariff, test, warning};

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

    let mut tariff = tariff();
    tariff["country_code"] = json!("nl");
    tariff["start_date_time"] = json!("2026-01-01T00:00:00Z");
    let cdr_json = cdr_json(&[tariff]);
    let cdr = build_cdr(&cdr_json);

    let (tariffs, warnings) = cdr.tariffs().unwrap().into_parts();
    assert_incorrect_case(&warnings, "$.tariffs[0].country_code");

    let (error, _warnings) = cdr::price(&cdr, &tariffs, &jiff::tz::TimeZone::UTC)
        .unwrap_err()
        .into_parts();
    assert_matches!(error.warning(), price::Warning::NoValidTariff);
}

/// Return a `v2.2.1` tariff with the id `T1` that prices time.
fn tariff() -> serde_json::Value {
    json!({
        "id": "T1",
        "country_code": "NL",
        "party_id": "TDR",
        "currency": "EUR",
        "elements": [{ "price_components": [{ "type": "TIME", "price": 2.00, "step_size": 1 }] }],
        "last_updated": "2025-01-01T00:00:00Z"
    })
}

/// Return a `v2.2.1` CDR of a two-hour session that contains `tariffs`.
fn cdr_json(tariffs: &[serde_json::Value]) -> String {
    json!({
        "country_code": "NL",
        "party_id": "TDR",
        "start_date_time": "2025-07-21T06:00:00Z",
        "end_date_time": "2025-07-21T08:00:00Z",
        "currency": "EUR",
        "tariffs": tariffs,
        "cdr_location": { "country": "NLD" },
        "charging_periods": [
            {
                "start_date_time": "2025-07-21T06:00:00Z",
                "dimensions": [{ "type": "TIME", "volume": 2 }]
            }
        ],
        "total_cost": { "excl_vat": 4.00 },
        "total_energy": 0,
        "total_time": 2,
        "last_updated": "2025-07-21T08:00:00Z"
    })
    .to_string()
}

fn build_cdr(cdr_json: &str) -> cdr::Cdr<'_> {
    let doc = json::parse_object(cdr_json).unwrap();
    let cdr = cdr::check(doc, Version::V221).ignore_warnings();
    cdr::build(cdr).unwrap().ignore_warnings()
}

#[track_caller]
fn assert_incorrect_case(warnings: &warning::Set<tariff::Warning>, path: &str) {
    let (element, _warning) = warnings
        .find(|warning| {
            matches!(
                warning,
                tariff::Warning::Country(country::Warning::IncorrectCase)
            )
        })
        .expect("building the tariff should raise `IncorrectCase` for its `country_code`");
    assert_eq!(element.path.as_str(), path);
}