Skip to main content

generate_cdr_from_tariff/
generate_cdr_from_tariff.rs

1#![expect(clippy::unwrap_used, reason = "examples can panic")]
2#![expect(clippy::print_stdout, reason = "examples can log to stdout")]
3#![expect(clippy::print_stderr, reason = "examples can log to stderr")]
4
5use std::str::FromStr as _;
6
7use chrono::{DateTime, Utc};
8use ocpi_tariffs::{cdr, generate, json, tariff, warning, Version};
9use rust_decimal::Decimal;
10
11fn main() {
12    const TARIFF_JSON: &str = include_str!("data/tariff_time_and_parking_time_separate.json");
13
14    // Parse the raw JSON into a `json::Document` and guess the OCPI version of the tariff, falling
15    // back to `v2.2.1` when the version is uncertain.
16    let doc = json::parse_object(TARIFF_JSON).unwrap();
17    let tariff = tariff::infer_version(doc).certain_or(Version::V221);
18    let tariff = tariff::build_versioned(tariff).ignore_warnings();
19
20    let config = generate::Config {
21        timezone: chrono_tz::Europe::Amsterdam,
22        start_date_time: DateTime::<Utc>::from_str("2025-06-12 18:22:33+00:00").unwrap(),
23        end_date_time: DateTime::<Utc>::from_str("2025-06-12 22:33:44+00:00").unwrap(),
24        max_current_supply_amp: Decimal::from(4),
25        requested_kwh: Decimal::from(24),
26        max_power_supply_kw: Decimal::from(80),
27    };
28    let report = match cdr::generate_from_tariff(&tariff, &config) {
29        Ok(r) => r,
30        Err(set) => {
31            let (error, warnings) = set.into_parts();
32            print_error(&error);
33            print_warnings(&warnings);
34            return;
35        }
36    };
37    let (report, warnings) = report.into_parts();
38
39    print_warnings(&warnings);
40
41    let generate::Report {
42        tariff_id,
43        tariff_currency_code,
44        partial_cdr,
45    } = report;
46
47    println!("CDR generated for tariff with id: `{tariff_id}` and currency code: `{tariff_currency_code}`");
48    println!("{partial_cdr:#?}");
49}
50
51/// Print `generate::Warning` that halted the example to `stderr`.
52fn print_error(error: &warning::Error<generate::Warning>) {
53    eprintln!(
54        "ERR: Unable to generate CDR due to error at path `{}`: {}",
55        error.element().path,
56        error.warning()
57    );
58}
59
60/// Print `generate::Warning`s to `stderr`.
61fn print_warnings(warnings: &warning::Set<generate::Warning>) {
62    if warnings.is_empty() {
63        return;
64    }
65
66    eprintln!(
67        "WARN: {} warnings from the linting:\n {}",
68        warnings.len_warnings(),
69        warning::SetWriter::new(warnings)
70    );
71}