price_cdr_with_known_version/
price_cdr_with_known_version.rs

1#![expect(clippy::expect_used, reason = "examples can panic")]
2#![expect(clippy::print_stderr, reason = "examples can log to stderr")]
3
4use chrono_tz::Tz;
5
6use ocpi_tariffs::{cdr, price, warning, Version};
7
8fn main() {
9    const CDR_JSON: &str =
10        include_str!("../test_data/v211/real_world/time_and_parking_time/cdr.json");
11
12    // If you know the version and timezone of a CDR you simply pass them into the `cdr::parse_with_version` fn.
13    let report = cdr::parse_with_version(CDR_JSON, Version::V211).expect("unable to parse CDR");
14    let cdr::ParseReport {
15        cdr,
16        unexpected_fields,
17    } = report;
18
19    if !unexpected_fields.is_empty() {
20        eprintln!("Strange... there are fields in the CDR that are not defined in the spec.");
21
22        for path in &unexpected_fields {
23            eprintln!("{path}");
24        }
25    }
26
27    let report = cdr::price(&cdr, price::TariffSource::UseCdr, Tz::Europe__Amsterdam)
28        .expect("unable to price CDR JSON");
29
30    let (report, warnings) = report.into_parts();
31    print_pricing_warnings(&cdr, &warnings);
32
33    // The various fields of the `price::Report` can be examined or converted to JSON.
34    let price::Report {
35        periods: _,
36        tariff_used: _,
37        tariff_reports: _,
38        timezone: _,
39        billed_energy: _,
40        billed_parking_time: _,
41        total_charging_time: _,
42        billed_charging_time: _,
43        total_cost: _,
44        total_fixed_cost: _,
45        total_time: _,
46        total_time_cost: _,
47        total_energy: _,
48        total_energy_cost: _,
49        total_parking_time: _,
50        total_parking_cost: _,
51        total_reservation_cost: _,
52    } = report;
53}
54
55fn print_pricing_warnings(cdr: &cdr::Versioned<'_>, warnings: &warning::Set<price::WarningKind>) {
56    if warnings.is_empty() {
57        return;
58    }
59
60    eprintln!(
61        "WARN: {} warnings from the linting:\n {}",
62        warnings.len(),
63        warning::SetWriter::new(cdr.as_element(), warnings)
64    );
65}