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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! A fix that `lint --fix` makes by default must not change what a session costs.
//!
//! A case, read by [`Case`], is a directory holding the tariff to fix, the CDR to price against
//! it, and `tariff_fixed.json`, the exact text the fix is expected to leave behind. The cases
//! are split by what the fix does to the price:
//!
//! - `test_data/v221/fix/preserving` holds tariffs that price both before and after the fix,
//!   and have to price identically. This is the property the fix exists to keep.
//! - `test_data/v221/fix/repairing` holds tariffs that do not price at all until they are
//!   fixed. A `null` in `elements` is rejected when the tariff is lowered, so there is no price to
//!   preserve. The fix is what makes one exist.
//! - `test_data/v221/fix/changing` holds tariffs whose fixes change what the tariff means,
//!   such as renaming a misspelled field. `lint --fix` makes those fixes only when the caller
//!   allows changes. A case's own CDR states the total the author meant. The fixed tariff has to
//!   price the session at that total, while the tariff as written either doesn't price or prices
//!   the session at another total.
//!
//! `test_data/v211/fix/preserving` holds v2.1.1 cases, which are parsed and priced as v2.1.1.
//! There is no v2.1.1 `repairing` or `changing` directory.
//!
//! A preserving case is priced against its own `cdr.json` and against every CDR in the shared set
//! for its version, `test_data/v211/fix/cdr` or `test_data/v221/fix/cdr`. A case's own CDR was
//! chosen by whoever wrote the fix, so it can only show the fix working. The shared CDRs are what
//! can show it failing.
//!
//! The v2.1.1 shared set has no counterpart to `negative_power`. A v2.1.1 CDR has no power
//! dimension, so no v2.1.1 CDR can report the negative `MAX_POWER` that `negative_power` reports.
//!
//! A shared CDR is priced against every preserving tariff, so no total it declares can be right
//! for all of them, and `total_cost` is required so it cannot be left out. The disagreement
//! cannot change the comparison, because the declared total renders identically on both sides of
//! a fix.
//!
//! The reports are compared in full rather than only in the money total, because clearing a
//! dimension can turn a `Some(0.00)` total into `None` without changing what is owed. That
//! includes `tariff_reports`, which carries the warnings the tariff itself reported: a fix that
//! resolves one of those changes the report even when the money is identical, and this is meant
//! to notice.
//!
//! The warnings `price::cdr` raises are compared as well. A fix can make pricing start or stop
//! raising a warning while every field of the report stays as it was, so a comparison of the
//! fields alone would pass that fix.

#![allow(
    clippy::indexing_slicing,
    clippy::unwrap_in_result,
    clippy::panic,
    clippy::unwrap_used,
    reason = "test code with known-structure parsed data"
)]

use std::path::{Path, PathBuf};

use crate::{
    Version, cdr, json, lint, money,
    price::{self, test::UnwrapReport as _},
    tariff, test, warning,
};

use super::edits;

/// The zone the fixture CDR's `NLD` location sits in. Every pricing in this module uses it, so
/// the two sides of a comparison are always priced in the same zone.
const TIMEZONE: chrono_tz::Tz = chrono_tz::Tz::Europe__Amsterdam;

/// Fixing a v2.1.1 tariff that already prices leaves the price of a session untouched.
#[test_each::file(
    glob = "ocpi-tariffs/test_data/v211/fix/preserving/*/tariff.json",
    name(segments = 2)
)]
fn fixing_a_v211_tariff_does_not_change_what_a_session_costs(tariff_json: &str, path: &Path) {
    test::setup();

    assert_fix_preserves_price(Version::V211, tariff_json, path);
}

/// Fixing a v2.2.1 tariff that already prices leaves the price of a session untouched.
#[test_each::file(
    glob = "ocpi-tariffs/test_data/v221/fix/preserving/*/tariff.json",
    name(segments = 2)
)]
fn fixing_a_v221_tariff_does_not_change_what_a_session_costs(tariff_json: &str, path: &Path) {
    test::setup();

    assert_fix_preserves_price(Version::V221, tariff_json, path);
}

/// A tariff that does not price at all is made priceable by fixing it.
#[test_each::file(
    glob = "ocpi-tariffs/test_data/v221/fix/repairing/*/tariff.json",
    name(segments = 2)
)]
fn fixing_a_tariff_makes_an_unpriceable_session_priceable(tariff_json: &str, path: &Path) {
    test::setup();

    let version = Version::V221;
    let case = Case::at(path);
    let tariff_json_fixed = parse_validate_fix(version, tariff_json);

    case.assert_fixed_text(&tariff_json_fixed);

    // Whether the tariff priced beforehand is a property of the tariff, not of the CDR, so this
    // is not looped over the shared set the way the assertion below is.
    assert!(
        prices(version, &case.cdr_json, tariff_json).is_err(),
        "the tariff was expected not to price before it was fixed"
    );
    assert!(
        prices(version, &case.cdr_json, &tariff_json_fixed).is_ok(),
        "the fixed tariff was expected to price"
    );

    for (name, cdr_json) in shared_cdrs(&case.dir) {
        assert!(
            prices(version, &cdr_json, &tariff_json_fixed).is_ok(),
            "the fixed tariff was expected to price the `{name}` CDR"
        );
    }

    assert_no_more_fixes(version, &tariff_json_fixed);
}

/// `tariff::fix` makes a fix that changes what a tariff means only when the caller allows changes.
/// The fixed tariff then prices the case's CDR at the total that CDR states,
/// which is the total the author meant.
#[test_each::file(
    glob = "ocpi-tariffs/test_data/v221/fix/changing/*/tariff.json",
    name(segments = 2)
)]
fn fixing_a_tariff_with_changes_allowed_prices_a_session_as_its_author_meant(
    tariff_json: &str,
    path: &Path,
) {
    test::setup();

    let version = Version::V221;
    let case = Case::at(path);

    assert_eq!(
        parse_validate_fix(version, tariff_json),
        tariff_json,
        "fixing without allowing changes changed the tariff"
    );

    let changes_allowed = fix_options().allow_changes();
    let tariff_json_fixed = fix_with(version, tariff_json, changes_allowed);

    case.assert_fixed_text(&tariff_json_fixed);

    let fixed = total_cost(version, &case.cdr_json, &tariff_json_fixed)
        .expect("the fixed tariff was expected to price");
    assert_eq!(
        fixed.calculated,
        Some(fixed.cdr),
        "the fixed tariff does not price the session at the total its CDR states"
    );

    // The tariff as written may not price at all, as when a `day_of_week` is misspelled.
    if let Ok(as_written) = total_cost(version, &case.cdr_json, tariff_json) {
        assert_ne!(
            as_written.calculated,
            Some(as_written.cdr),
            "the premise: the tariff as written prices the session at another total"
        );
    }

    assert_no_more_fixes(version, &tariff_json_fixed);
}

/// The invariant tests judge whether a fix changed what pricing reports by comparing the text the
/// function `rendered` writes. This test checks that the text includes the warnings pricing raises
/// as well as the report's fields. Pricing this CDR raises a warning because the CDR ends at the
/// instant it starts.
#[test]
fn the_compared_text_changes_with_the_warnings_pricing_raises() {
    const CDR_JSON: &str = r#"{
        "start_date_time": "2022-01-13T14:30:00Z",
        "end_date_time": "2022-01-13T14:30:00Z",
        "currency": "EUR",
        "tariffs": [],
        "cdr_location": { "country": "NLD" },
        "charging_periods": [
            {
                "start_date_time": "2022-01-13T14:30:00Z",
                "dimensions": [{ "type": "ENERGY", "volume": 0 }]
            }
        ],
        "total_cost": { "excl_vat": 0.0, "incl_vat": 0.0 },
        "total_energy": 0,
        "total_time": 0,
        "last_updated": "2022-01-13T00:00:00Z"
    }"#;
    const TARIFF_JSON: &str = r#"{
        "country_code": "DE",
        "party_id": "ALL",
        "id": "1",
        "currency": "EUR",
        "elements": [
            { "price_components": [{ "type": "ENERGY", "price": 0.25, "step_size": 1 }] }
        ],
        "last_updated": "2018-12-17T11:36:01Z"
    }"#;

    test::setup();

    let (report, warnings) = price_report(Version::V221, CDR_JSON, TARIFF_JSON);
    assert!(
        !warnings.is_empty(),
        "the premise: pricing this CDR raises a warning"
    );

    assert_ne!(
        rendered(&report, warnings),
        rendered(&report, warning::Set::new()),
        "the compared text is the same with and without the pricing warnings"
    );
}

/// Fix `tariff_json`, parsed as `version`, and assert three things: the fix leaves the case's
/// expected text, every CDR the case is priced against gives the same report before and after, and
/// the fixed tariff needs no further fix. `path` locates the case's other files.
#[track_caller]
fn assert_fix_preserves_price(version: Version, tariff_json: &str, path: &Path) {
    let case = Case::at(path);
    let tariff_json_fixed = parse_validate_fix(version, tariff_json);

    case.assert_fixed_text(&tariff_json_fixed);

    // The same session, priced against the tariff as written and after fixing it.
    assert_eq!(
        priced(version, &case.cdr_json, tariff_json),
        priced(version, &case.cdr_json, &tariff_json_fixed),
        "fixing the tariff changed the report"
    );

    for (name, cdr_json) in shared_cdrs(&case.dir) {
        assert_eq!(
            priced(version, &cdr_json, tariff_json),
            priced(version, &cdr_json, &tariff_json_fixed),
            "fixing the tariff changed the report for the `{name}` CDR"
        );
    }

    assert_no_more_fixes(version, &tariff_json_fixed);
}

/// The files making up one case.
struct Case {
    cdr_json: String,
    expected: String,
    /// Used by `shared_cdrs` to locate the shared set.
    dir: PathBuf,
}

impl Case {
    fn at(tariff_path: &Path) -> Self {
        let dir = tariff_path
            .parent()
            .expect("a tariff lives in a case directory");

        Self {
            cdr_json: read(&dir.join("cdr.json")),
            expected: read(&dir.join("tariff_fixed.json")),
            dir: dir.to_path_buf(),
        }
    }

    #[track_caller]
    fn assert_fixed_text(&self, fixed: &str) {
        assert_eq!(
            fixed, self.expected,
            "the fix did not leave the expected text"
        );
    }
}

/// Assert that the given tariff JSON needs no more fixes.
///
/// Fixing is idempotent, and every warning the fixed tariff still raises is one nothing
/// mechanical resolves. A fixed tariff is not required to be warning-free: `EndTimeIsNearEndOfDay`
/// is left for the author to resolve.
#[track_caller]
fn assert_no_more_fixes(version: Version, tariff_fixed_json: &str) {
    assert_eq!(
        parse_validate_fix(version, tariff_fixed_json),
        tariff_fixed_json,
        "fixing is not idempotent"
    );
    assert_eq!(remaining_edits(version, tariff_fixed_json), Vec::new());
}

/// The CDRs every preserving case is priced against, beyond its own `cdr.json`.
///
/// Each is returned as its file stem and its text, so an assertion names the CDR that failed.
/// They are located from `case_dir` rather than from a literal path. The test process runs with
/// the package directory as its working directory, where the workspace-relative glob that
/// `test_each` takes does not resolve.
fn shared_cdrs(case_dir: &Path) -> Vec<(String, String)> {
    let dir = case_dir
        .parent()
        .and_then(Path::parent)
        .expect("a case directory has a grandparent")
        .join("cdr");

    let entries = std::fs::read_dir(&dir)
        .unwrap_or_else(|err| panic!("unable to read `{}`:\n{err}", dir.display()));

    let mut cdrs = Vec::new();

    for entry in entries {
        let path = entry.expect("a readable entry in the CDR directory").path();

        // `test_data/json` has a README, so one here is likely. Reading it as a CDR would panic
        // in every preserving case.
        if path.extension().is_none_or(|s| s != "json") {
            continue;
        }

        let name = path
            .file_stem()
            .expect("a CDR file is named")
            .to_string_lossy()
            .into_owned();

        cdrs.push((name, read(&path)));
    }

    // `read_dir` gives no order guarantee. Without the sort, a failure could name a different
    // CDR from one run to the next.
    cdrs.sort();

    // An empty set would leave the caller's loop with nothing to do, and every case would pass
    // on its own CDR alone. That is what this set exists to prevent.
    assert!(!cdrs.is_empty(), "no CDRs found in `{}`", dir.display());

    cdrs
}

fn read(path: &Path) -> String {
    std::fs::read_to_string(path)
        .unwrap_or_else(|err| panic!("unable to read `{}`:\n{err}", path.display()))
}

/// Fix `tariff_json` the way a caller of the library does, and return the fixed JSON.
///
/// This goes through the fixing loop rather than applying one pass, because a fix can raise even
/// more issues. Removing the last field of a `restrictions` object leaves an
/// object that restricts nothing, and only the following pass sees that and removes it, so a
/// single pass would leave a case like `null_fields` short of its fixed point.
fn parse_validate_fix(version: Version, tariff_json: &str) -> String {
    fix_with(version, tariff_json, fix_options())
}

/// The options `parse_validate_fix` fixes every case with. They remove unexpected fields
/// and allow only the edits that keep what the tariff means. The `changing` test adds
/// `allow_changes` to them.
fn fix_options() -> lint::fix::Options {
    lint::fix::Options::default().unexpected_fields(lint::fix::UnexpectedFields::Remove)
}

/// Runs `tariff::fix` on the tariff in `tariff_json` and returns the fixed JSON.
/// The caller chooses which fixes are made through `options`.
fn fix_with(version: Version, tariff_json: &str, options: lint::fix::Options) -> String {
    let doc = json::parse_object(tariff_json).unwrap();
    let tariff = tariff::from_json(doc, version).ignore_warnings();

    tariff::fix(&tariff, options).unwrap().source
}

/// The edits still proposed for `tariff_json`, from the schema walk and from linting alike.
fn remaining_edits(version: Version, tariff_json: &str) -> Vec<super::Edit> {
    let doc = json::parse_object(tariff_json).unwrap();
    let (tariff, schema_warnings) = tariff::from_json(doc, version).into_parts();
    let doc = tariff.as_doc();
    let lint_warnings = tariff::lint(&tariff).warnings;

    let mut proposed = edits(doc, &schema_warnings).unwrap();
    proposed.extend(edits(doc, &lint_warnings).unwrap());

    proposed
}

/// Price `cdr_json` against `tariff_json`, reporting whether it could be priced at all.
fn prices(version: Version, cdr_json: &str, tariff_json: &str) -> Result<(), String> {
    let doc = json::parse_object(tariff_json).unwrap();
    let tariff = tariff::from_json(doc, version).ignore_warnings();

    let doc = json::parse_object(cdr_json).unwrap();
    let cdr = cdr::from_json(doc, version).ignore_warnings();

    match price::cdr(&cdr, price::TariffSource::Override(vec![tariff]), TIMEZONE) {
        Ok(_report) => Ok(()),
        Err(errors) => Err(format!("{:?}", errors.into_parts().0)),
    }
}

/// Price `cdr_json` against `tariff_json` and return both totals, the one the CDR states
/// and the one pricing calculated.
/// When the CDR can't be priced, return the pricing errors as text.
fn total_cost(
    version: Version,
    cdr_json: &str,
    tariff_json: &str,
) -> Result<price::Total<money::Price, Option<money::Price>>, String> {
    let doc = json::parse_object(tariff_json).unwrap();
    let tariff = tariff::from_json(doc, version).ignore_warnings();

    let doc = json::parse_object(cdr_json).unwrap();
    let cdr = cdr::from_json(doc, version).ignore_warnings();

    match price::cdr(&cdr, price::TariffSource::Override(vec![tariff]), TIMEZONE) {
        Ok(report) => Ok(report.ignore_warnings().total_cost),
        Err(errors) => Err(format!("{:?}", errors.into_parts().0)),
    }
}

/// Price `cdr_json` against `tariff_json` and render the whole report, with the warnings pricing
/// raised, for comparison.
fn priced(version: Version, cdr_json: &str, tariff_json: &str) -> String {
    let (report, warnings) = price_report(version, cdr_json, tariff_json);

    rendered(&report, warnings)
}

/// Price `cdr_json` against `tariff_json` and return the report with the warnings pricing raised.
fn price_report(
    version: Version,
    cdr_json: &str,
    tariff_json: &str,
) -> (price::Report, warning::Set<price::Warning>) {
    let doc = json::parse_object(tariff_json).unwrap();
    let tariff = tariff::from_json(doc, version).ignore_warnings();

    let doc = json::parse_object(cdr_json).unwrap();
    let cdr = cdr::from_json(doc, version).ignore_warnings();

    price::cdr(&cdr, price::TariffSource::Override(vec![tariff]), TIMEZONE)
        .unwrap_report(cdr.as_json_str())
        .into_parts()
}

/// A whole [`price::Report`] and the warnings pricing raised, rendered for comparison.
///
/// `Report` has no `PartialEq`, and giving it one would mean deriving it for the nine warning
/// enums `tariff_reports` reaches, so the fields are compared as text instead.
///
/// The text is built from the fields bound here rather than from `Report`'s own `Debug`, which
/// is written by hand. A field missing from that impl would be left out of the comparison
/// silently. A field missing from the binding here fails to compile.
fn rendered(report: &price::Report, warnings: warning::Set<price::Warning>) -> String {
    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;

    format!(
        "periods: {periods:#?}\n\
         tariff_used: {tariff_used:#?}\n\
         tariff_reports: {tariff_reports:#?}\n\
         timezone: {timezone:#?}\n\
         billed_charging_time: {billed_charging_time:#?}\n\
         billed_energy: {billed_energy:#?}\n\
         billed_idle_time: {billed_idle_time:#?}\n\
         total_charging_time: {total_charging_time:#?}\n\
         total_energy: {total_energy:#?}\n\
         total_idle_time: {total_idle_time:#?}\n\
         total_time: {total_time:#?}\n\
         total_cost: {total_cost:#?}\n\
         total_energy_cost: {total_energy_cost:#?}\n\
         total_fixed_cost: {total_fixed_cost:#?}\n\
         total_idle_cost: {total_idle_cost:#?}\n\
         total_charging_time_cost: {total_charging_time_cost:#?}\n\
         warnings: {warnings:#?}\n",
        warnings = warnings.into_path_map(),
    )
}