ocpi-tariffs 0.54.0

OCPI tariff calculations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#![allow(
    clippy::unwrap_in_result,
    reason = "unwraps are allowed anywhere in tests"
)]
#![allow(
    clippy::indexing_slicing,
    reason = "tests are allowed to index collections"
)]
#![allow(clippy::string_slice, reason = "tests are allowed to slice strings")]

use std::{path::Path, str::FromStr as _};

use chrono::{DateTime, TimeDelta, Utc};
use rust_decimal::Decimal;
use tracing::debug;

use super::test::partial_to_cdr;
use crate::{
    Kwh, Version, assert_approx_eq_tolerance, cdr, currency,
    duration::Hms,
    json,
    price::{self, Total, test::UnwrapReport as _},
    tariff,
    test::{self, Expectation},
    warning,
};

const TARIFF_FILE_NAME: &str = "tariff.json";

macro_rules! assert_req_total_field {
    ($expected:expr, $report:expr $(,)?) => {
        let field_name = stringify!($report);

        match $expected {
            Expectation::Present(expected) => match expected {
                test::ExpectValue::Some(expected) => {
                    let value = $report.calculated.unwrap_or_else(|| {
                        panic!("`{field_name}` is not calculated.");
                    });
                    assert_approx_eq_tolerance!(
                        value,
                        expected.value(),
                        expected.tolerance(),
                        "for `{field_name}`"
                    );
                }
                test::ExpectValue::Null => {
                    if let Some(v) = $report.calculated {
                        panic!(
                            "Expected `{field_name}` to not be calculated; but it has value `{v}`."
                        )
                    }
                }
            },
            Expectation::Absent => {
                panic!("The `{field_name}` field is required.")
            }
        }
    };
}

macro_rules! assert_req_optional_field {
    ($expected:expr, $report:expr $(,)?) => {
        let field_name = stringify!($report);

        match $expected {
            Expectation::Present(expected) => match expected {
                test::ExpectValue::Some(expected) => {
                    let value = $report.unwrap_or_else(|| {
                        panic!("`{field_name}` is not calculated.");
                    });
                    assert_approx_eq_tolerance!(
                        value,
                        expected.value(),
                        expected.tolerance(),
                        "for `{field_name}`"
                    );
                }
                test::ExpectValue::Null => assert!(
                    $report.is_none(),
                    "Expected `{field_name}` to not be calculated; but it is."
                ),
            },
            Expectation::Absent => {
                panic!("The `{field_name}` field is required.")
            }
        }
    };
}

/// Each `config.json` found in the tariff test directory results in a test run.
#[test_each::file(
    glob = "ocpi-tariffs/test_data/popular/*/test_run*.json",
    name(segments = 2)
)]
#[expect(clippy::cognitive_complexity, reason = "The test is simply complex")]
fn should_price_cdr_generated_from_tariff(test_run_json: &str, test_run_file_path: &Path) {
    const VERSION: Version = Version::V221;

    test::setup();

    let json_dir = test_run_file_path
        .parent()
        .expect("The given file should live in a dir");

    let tariff_path = json_dir.join(TARIFF_FILE_NAME);
    debug!("Try to read tariff file: `{TARIFF_FILE_NAME}`");
    let tariff_json = test::read_file_content(&tariff_path).unwrap_or_else(|err| {
        panic!("Unable to read `{TARIFF_FILE_NAME}` file:\n{err}");
    });

    let test_run_json = test::strip_comment_lines(test_run_json);
    let test_run = {
        serde_json::from_str::<TestRun>(&test_run_json).unwrap_or_else(|err| {
            panic!(
                "Unable to parse {}:\n{:#?}",
                test_run_file_path.display(),
                err
            );
        })
    };
    let TestRun { input, expect } = test_run;
    let Expect {
        currency: expected_currency,
        total_cost: expected_total_cost,
        total_energy_cost: expected_total_energy_cost,
        total_idle_cost: expected_total_idle_cost,
        total_charging_time: expected_total_charging_time,
        total_idle_time: expected_total_idle_time,
        total_energy: expected_total_energy,
        warnings: expected_warnings,
        generate_warnings: expected_generate_warnings,
    } = expect;

    let tariff = {
        debug!("Successfully read tariff file: `{TARIFF_FILE_NAME}`");

        let tariff = json::parse_object(&tariff_json).unwrap();
        let (tariff, warnings) = tariff::from_json(tariff, VERSION).into_parts();
        warning::test::assert_warnings(
            &format!("`warnings` in the `{}` file", test_run_file_path.display()),
            &warnings,
            expected_warnings,
        );
        tariff
    };

    let config = super::Config::from(input);
    let timezone = config.timezone;

    let (cdr_json, generated_total_cost) = {
        let report = super::cdr_from_tariff(&tariff, &config).unwrap_or_else(|err| {
            panic!("Unable to generate a CDR:\n{err:#?}");
        });
        let (report, warnings) = report.into_parts();
        warning::test::assert_warnings(
            &format!(
                "`generate_warnings` in the `{}` file",
                test_run_file_path.display()
            ),
            &warnings,
            expected_generate_warnings,
        );

        // The test reads the generator's total from the `PartialCdr` rather than from the CDR,
        // because `partial_to_cdr` writes 0.00 where the generator calculated no total.
        let generated_total_cost = report.partial_cdr.total_cost;
        let cdr_json = partial_to_cdr(report.partial_cdr);
        let cdr_json = serde_json::to_string_pretty(&cdr_json).unwrap();
        (cdr_json, generated_total_cost)
    };

    let tariff_source = price::TariffSource::Override(vec![tariff]);

    let cdr = json::parse_object(&cdr_json).unwrap();
    let (cdr, warnings) = cdr::from_json(cdr, VERSION).into_parts();
    test::assert_schema_warnings(&warnings, &[]);
    debug!("The CDR generated is:\n{}", cdr.as_json_str());

    let report = price::cdr(&cdr, tariff_source, timezone).unwrap_report(cdr.as_json_str());
    let (report, warnings) = report.into_parts();

    assert!(
        warnings.is_empty(),
        "Generating the CDR from a tariff has warnings;\n{:?}",
        warnings.path_id_map()
    );

    debug!("The CDR's report is:\n{:#?}", report);

    let price::Report {
        periods: _,
        tariff_used,
        tariff_reports: _,
        timezone: _,
        billed_charging_time: _,
        billed_energy: _,
        billed_idle_time: _,
        total_charging_time,
        total_energy,
        total_idle_time,
        total_time: _,
        total_cost,
        total_energy_cost,
        total_fixed_cost: _,
        total_idle_cost,
        total_charging_time_cost: _,
    } = report;

    {
        let expected_currency = match expected_currency {
            Expectation::Present(value) => {
                let code = value.expect_value();
                currency::Code::from_alpha_3_str(&code)
            }
            // Default to `Eur` if the `currency` field is not defined.
            Expectation::Absent => currency::Code::Eur,
        };

        assert_eq!(
            tariff_used.currency,
            expected_currency,
            "Expected `{expected_currency}` currency for tariff test_run `{}`",
            test_run_file_path.display()
        );
    }

    // The generator prices the periods it builds. The pricer prices the CDR the generator writes
    // from those periods, so the two totals should agree exactly. A tolerance would hide a drift
    // such as a volume the CDR cannot state as the generator computed it.
    assert_eq!(
        total_cost.calculated, generated_total_cost,
        "Pricing the generated CDR should repeat the generator's `total_cost`."
    );
    assert_req_total_field!(expected_total_cost, total_cost);
    assert_req_total_field!(expected_total_energy_cost, total_energy_cost);
    assert_req_total_field!(expected_total_idle_cost, total_idle_cost);
    assert_req_total_field!(expected_total_energy, total_energy);

    {
        let total_charging_time = total_charging_time.map(Hms);
        assert_req_optional_field!(expected_total_charging_time, total_charging_time);
    }

    {
        let Total { cdr, calculated } = total_idle_time;
        let total_idle_time = Total {
            cdr: cdr.map(Hms),
            calculated: calculated.map(Hms),
        };
        assert_req_total_field!(expected_total_idle_time, total_idle_time);
    }
}

/// Each `test_run.json` file in the `test_data/popular` directories results in a test run of
/// the `should_price_cdr_generated_from_tariff` function.
#[derive(serde::Deserialize)]
struct TestRun {
    /// The input config for this test run.
    /// This is converted into a `generate::Config` and given to the `cdr::generate_from_tariff` function.
    input: Input,

    /// The expectation for the priced CDR generated from the tariff.
    expect: Expect,
}

/// The config for generating a CDR from a tariff.
///
/// This is read in from a `config.json` file in the `test_data/popular` directories.
/// Each config file triggers a test run on the `should_price_cdr_generated_from_tariff` function.
///
/// The fields mirror [`super::Config`], which is what they are converted into. What each
/// one means is documented there, so this struct does not repeat it.
#[derive(serde::Deserialize)]
struct Input {
    timezone: String,

    end_date_time: String,

    max_current_supply_amp: Decimal,

    requested_kwh: Decimal,

    max_power_supply_kw: Decimal,

    start_date_time: String,
}

#[derive(serde::Deserialize)]
struct Expect {
    /// The currency used in the tariff.
    #[serde(default)]
    currency: Expectation<String>,

    /// The expected `total_cost`.
    #[serde(default)]
    total_cost: Expectation<TolerancePrice>,

    /// The expected `total_energy_cost`.
    #[serde(default)]
    total_energy_cost: Expectation<TolerancePrice>,

    /// The expected `total_idle_cost`.
    #[serde(default)]
    total_idle_cost: Expectation<TolerancePrice>,

    /// The expected `total_charging_time`.
    #[serde(default)]
    total_charging_time: Expectation<ToleranceHms>,

    /// The expected `total_idle_time`.
    #[serde(default)]
    total_idle_time: Expectation<ToleranceHms>,

    /// The expected `total_energy`.
    #[serde(default)]
    total_energy: Expectation<ToleranceKwh>,

    /// The expected schema warnings, reported by `tariff::from_json`.
    #[serde(default)]
    warnings: Expectation<test::WarningMap>,

    /// The expected warnings raised while generating the CDR.
    ///
    /// These are the decisions the generator made, not the structural findings of the schema
    /// walk, so a tariff can have `warnings` and no `generate_warnings`.
    #[serde(default)]
    generate_warnings: Expectation<test::WarningMap>,
}

/// An expected value with a given tolerance.
trait Tolerance<V, T> {
    /// Return the value.
    fn value(&self) -> V;

    /// Return the tolerance.
    fn tolerance(&self) -> T;
}

/// An expected `Price` with a given tolerance.
#[derive(Debug, serde::Deserialize)]
struct TolerancePrice {
    value: crate::Price,
    tolerance: Decimal,
}

impl Tolerance<crate::Price, Decimal> for TolerancePrice {
    fn value(&self) -> crate::Price {
        self.value
    }

    fn tolerance(&self) -> Decimal {
        self.tolerance
    }
}

/// An expected kWh amount with a given tolerance.
#[derive(Debug, serde::Deserialize)]
struct ToleranceKwh {
    /// The value in kWh.
    value: Decimal,

    /// The tolerance in kWh.
    tolerance_kwh: Decimal,
}

impl Tolerance<Kwh, Decimal> for ToleranceKwh {
    fn value(&self) -> Kwh {
        self.value.into()
    }

    fn tolerance(&self) -> Decimal {
        self.tolerance_kwh
    }
}

/// An expected duration in `HH:MM::SS` with a given tolerance.
#[derive(Debug, serde::Deserialize)]
struct ToleranceHms {
    value: Hms,
    tolerance_sec: u32,
}

impl Tolerance<Hms, TimeDelta> for ToleranceHms {
    fn value(&self) -> Hms {
        self.value
    }

    fn tolerance(&self) -> TimeDelta {
        TimeDelta::seconds(self.tolerance_sec.into())
    }
}

impl From<Input> for super::Config {
    fn from(config: Input) -> Self {
        let Input {
            timezone,
            end_date_time,
            max_current_supply_amp,
            requested_kwh,
            max_power_supply_kw,
            start_date_time,
        } = config;

        super::Config {
            timezone: chrono_tz::Tz::from_str(&timezone).unwrap(),
            end_date_time: DateTime::<Utc>::from_str(&end_date_time).unwrap(),
            max_current_supply_amp,
            requested_kwh,
            max_power_supply_kw,
            start_date_time: DateTime::<Utc>::from_str(&start_date_time).unwrap(),
        }
    }
}