ocpi-tariffs 0.45.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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
#![allow(clippy::missing_panics_doc, reason = "tests are allowed to panic")]
#![allow(clippy::panic, reason = "tests are allowed panic")]

use std::collections::{BTreeMap, BTreeSet};

use chrono::TimeDelta;
use rust_decimal::Decimal;
use serde::Deserialize;
use tracing::debug;

use crate::{
    assert_approx_eq,
    duration::ToHoursDecimal,
    json,
    number::{self, IsZero as _},
    test::{self, ApproxEq, ExpectFile, Expectation},
    timezone,
    warning::{self, Warning as _},
    Caveat, Kwh, ObjectType, Price,
};

use super::{Report, TariffReport, Total, Warning};

// Decimal precision used when comparing the outcomes of the calculation with the CDR.
const PRECISION: u32 = 2;

#[test]
const fn warning_kind_should_be_send_and_sync() {
    const fn f<T: Send + Sync>() {}

    f::<Warning>();
}

pub trait UnwrapReport {
    #[track_caller]
    fn unwrap_report(self, json_source: &str) -> Caveat<Report, Warning>;
}

impl UnwrapReport for super::Verdict<Report> {
    fn unwrap_report(self, json_source: &str) -> Caveat<Report, Warning> {
        match self {
            Ok(v) => v,
            Err(set) => {
                let (error, _warnings) = set.into_parts();
                let warning::test::ErrorSourceContext {
                    context: _,
                    element_path,
                    element_position,
                    error,
                } = error.into_context(json_source).unwrap();
                let json_source = serde_json::from_str::<serde_json::Value>(json_source).unwrap();
                panic!(
                    "Unable to price the CDR due to an error at path `{element_path}`:\n{error}\n{}",
                    json::test::LineHighlighter::from_value(&json_source, element_position)
                );
            }
        }
    }
}

/// A `TimeDelta` wrapper used to serialize and deserialize to/from a `Decimal` representation of hours
#[derive(Debug, Default)]
pub(crate) struct HoursDecimal(Decimal);

impl ToHoursDecimal for HoursDecimal {
    fn to_hours_dec(&self) -> Decimal {
        self.0
    }
}

/// Deserialize bytes into a `Decimal` applying the scale defined in the OCPI spec.
///
/// Called from the `impl Deserialize` for a `Decimal` newtype.
fn decimal<'de, D>(deserializer: D) -> Result<Decimal, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::Deserialize;

    let mut d = <Decimal as Deserialize>::deserialize(deserializer)?;
    d.rescale(number::SCALE);
    Ok(d)
}

impl<'de> Deserialize<'de> for HoursDecimal {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        decimal(deserializer).map(Self)
    }
}

#[derive(serde::Deserialize)]
pub(crate) struct Expect {
    /// Expectations for the result of calling `timezone::find_or_infer`.
    pub timezone_find: Option<timezone::test::FindOrInferExpect>,

    /// Expectations for the result of calling `tariff::parse*`.
    pub tariff_parse: Option<ParseExpect>,

    /// Expectations for the result of calling `cdr::parse*`.
    pub cdr_parse: Option<ParseExpect>,

    /// Expectations for the result of calling `cdr::price*`.
    pub cdr_price: Option<PriceExpect>,
}

/// The `Expect` is used to parse the JSON but the tests use the individual fields in separate
/// asset functions. Each of those functions needs to know the `expect_file_name`.
#[expect(
    clippy::struct_field_names,
    reason = "When deconstructed these fields will always be called *_expect. This avoids having to rename them in-place."
)]
pub(crate) struct ExpectFields {
    /// Expectations for the result of calling `timezone::find_or_infer`.
    pub timezone_find_expect: ExpectFile<timezone::test::FindOrInferExpect>,

    /// Expectations for the result of calling `cdr::parse*`.
    pub tariff_parse_expect: ExpectFile<ParseExpect>,

    /// Expectations for the result of calling `cdr::parse*`.
    pub cdr_parse_expect: ExpectFile<ParseExpect>,

    /// Expectations for the result of calling `cdr::price*`.
    pub cdr_price_expect: ExpectFile<PriceExpect>,
}

impl test::IntoFields<ExpectFields> for ExpectFile<Expect> {
    /// Split the `ExpectFile<Expect>` into its constituent fields and repackage them as `ExpectFile`s.
    fn into_fields(self) -> ExpectFields {
        let ExpectFile {
            value,
            expect_file_name,
        } = self;

        match value {
            Some(expect) => {
                let Expect {
                    timezone_find,
                    tariff_parse,
                    cdr_parse,
                    cdr_price,
                } = expect;
                ExpectFields {
                    timezone_find_expect: ExpectFile::with_value(timezone_find, &expect_file_name),
                    tariff_parse_expect: ExpectFile::with_value(tariff_parse, &expect_file_name),
                    cdr_parse_expect: ExpectFile::with_value(cdr_parse, &expect_file_name),
                    cdr_price_expect: ExpectFile::with_value(cdr_price, &expect_file_name),
                }
            }
            None => ExpectFields {
                timezone_find_expect: ExpectFile::only_file_name(&expect_file_name),
                tariff_parse_expect: ExpectFile::only_file_name(&expect_file_name),
                cdr_parse_expect: ExpectFile::only_file_name(&expect_file_name),
                cdr_price_expect: ExpectFile::only_file_name(&expect_file_name),
            },
        }
    }
}

#[track_caller]
pub(crate) fn assert_parse_report(
    object_type: ObjectType,
    unexpected_fields: json::UnexpectedFields<'_>,
    expect: ExpectFile<ParseExpect>,
) {
    let ExpectFile {
        value,
        expect_file_name,
    } = expect;
    let unexpected_fields_expect = value
        .map(|exp| exp.unexpected_fields)
        .unwrap_or(Expectation::Absent);

    if let Expectation::Present(expectation) = unexpected_fields_expect {
        let unexpected_fields_expect = expectation.expect_value();

        for field in unexpected_fields {
            assert!(
                    unexpected_fields_expect.contains(&field.to_string()),
                    "The {object_type} has an unexpected field that's not expected in `{expect_file_name}`: `{field}`"
                );
        }
    } else {
        assert!(
                unexpected_fields.is_empty(),
                "The {object_type} has unexpected fields but the expect file doesn't `{expect_file_name}`; {unexpected_fields:#}",
            );
    }
}

#[track_caller]
pub(crate) fn assert_price_report(
    report: Caveat<Report, Warning>,
    expect: ExpectFile<PriceExpect>,
) {
    let (report, warnings) = report.into_parts();
    let Report {
        mut tariff_reports,
        periods: _,
        tariff_used,
        timezone: _,
        billed_energy: _,
        billed_parking_time: _,
        billed_charging_time: _,
        total_charging_time: _,
        total_cost,
        total_fixed_cost,
        total_time,
        total_time_cost,
        total_energy,
        total_energy_cost,
        total_parking_time,
        total_parking_cost,
        total_reservation_cost,
    } = report;

    let ExpectFile {
        value: expect,
        expect_file_name,
    } = expect;

    // This destructure isn't pretty but it's at least simple to maintain.
    // The alternative is getting involved with references of references when processing each borrowed field.
    let (
        warnings_expect,
        tariff_index_expect,
        tariff_id_expect,
        tariff_reports_expect,
        total_cost_expectation,
        total_fixed_cost_expectation,
        total_time_expectation,
        total_time_cost_expectation,
        total_energy_expectation,
        total_energy_cost_expectation,
        total_parking_time_expectation,
        total_parking_cost_expectation,
        total_reservation_cost_expectation,
    ) = expect
        .map(|exp| {
            let PriceExpect {
                warnings,
                tariff_index,
                tariff_id,
                tariff_reports,
                total_cost,
                total_fixed_cost,
                total_time,
                total_time_cost,
                total_energy,
                total_energy_cost,
                total_parking_time,
                total_parking_cost,
                total_reservation_cost,
            } = exp;

            (
                warnings,
                tariff_index,
                tariff_id,
                tariff_reports,
                total_cost,
                total_fixed_cost,
                total_time,
                total_time_cost,
                total_energy,
                total_energy_cost,
                total_parking_time,
                total_parking_cost,
                total_reservation_cost,
            )
        })
        .unwrap_or((
            Expectation::Absent,
            Expectation::Absent,
            Expectation::Absent,
            Expectation::Absent,
            Expectation::Absent,
            Expectation::Absent,
            Expectation::Absent,
            Expectation::Absent,
            Expectation::Absent,
            Expectation::Absent,
            Expectation::Absent,
            Expectation::Absent,
            Expectation::Absent,
        ));

    if let Expectation::Present(expectation) = warnings_expect {
        let warnings_expect = expectation.expect_value();

        debug!("{warnings_expect:?}");

        for group in &warnings {
            let (element, warnings) = group.to_parts();
            let Some(warnings_expect) = warnings_expect.get(element.path().as_str()) else {
                let warning_ids = warnings
                    .iter()
                    .map(|k| format!("  \"{}\",", k.id()))
                    .collect::<Vec<_>>()
                    .join("\n");

                panic!("No warnings expected `{expect_file_name}` for `Element` at `{}` but {} warnings were reported:\n[\n{}\n]", element.path(), warnings.len(), warning_ids);
            };

            let warnings_expect = warnings_expect
                .iter()
                .map(|s| &**s)
                .collect::<BTreeSet<_>>();

            for warning_kind in warnings {
                let id = warning_kind.id();
                assert!(
                    warnings_expect.contains(id.as_str()),
                    "Unexpected warning `{id}` for `Element` at `{}`",
                    element.path()
                );
            }
        }
    } else {
        assert!(
            warnings.is_empty(),
            "The expectation file at `{expect_file_name}` did not expect warnings, but the CDR has warnings:\n\
            {:#?}\n\
            These warnings have the messages:\n\
            {:#?}",
            warnings.path_id_map(),
            warnings.path_msg_map()
        );
    }

    if let Expectation::Present(expectation) = tariff_reports_expect {
        let tariff_reports_expect: BTreeMap<_, _> = expectation
            .expect_value()
            .into_iter()
            .map(|TariffReportExpect { id, warnings }| (id, warnings))
            .collect();

        for report in &mut tariff_reports {
            let TariffReport { origin, warnings } = report;
            let id = &origin.id;
            let Some(warnings_expect) = tariff_reports_expect.get(id) else {
                panic!("A tariff with {id} is not expected `{expect_file_name}`");
            };

            debug!("{warnings_expect:?}");

            for (elem_path, warnings) in warnings {
                let Some(warnings_expect) = warnings_expect.get(elem_path.as_str()) else {
                    let warning_ids = warnings
                        .iter()
                        .map(|k| format!("  \"{}\",", k.id()))
                        .collect::<Vec<_>>()
                        .join("\n");

                    panic!("No warnings expected for `Element` at `{elem_path}` but {} warnings were reported:\n[\n{}\n]", warnings.len(), warning_ids);
                };

                let warnings_expect = warnings_expect
                    .iter()
                    .map(|s| &**s)
                    .collect::<BTreeSet<_>>();

                for warning_kind in warnings {
                    let id = warning_kind.id();
                    assert!(
                        warnings_expect.contains(id.as_str()),
                        "Unexpected warning `{id}` for `Element` at `{elem_path}`"
                    );
                }
            }
        }
    } else {
        for report in &tariff_reports {
            let TariffReport { origin, warnings } = report;

            let id = &origin.id;

            assert!(
                warnings.is_empty(),
                "The tariff with id `{id}` has warnings but the expect file `{expect_file_name}` has none in the `tariff_reports` map.\n {warnings:#?}"
            );
        }
    }

    if let Expectation::Present(expectation) = tariff_id_expect {
        assert_eq!(tariff_used.id, expectation.expect_value());
    }

    if let Expectation::Present(expectation) = tariff_index_expect {
        assert_eq!(tariff_used.index, expectation.expect_value());
    }

    total_cost_expectation.expect_price("total_cost", &total_cost);
    total_fixed_cost_expectation.expect_opt_price("total_fixed_cost", &total_fixed_cost);
    total_time_expectation.expect_duration("total_time", &total_time);
    total_time_cost_expectation.expect_opt_price("total_time_cost", &total_time_cost);
    total_energy_expectation.expect_opt_kwh("total_energy", &total_energy);
    total_energy_cost_expectation.expect_opt_price("total_energy_cost", &total_energy_cost);
    total_parking_time_expectation.expect_opt_duration("total_parking_time", &total_parking_time);
    total_parking_cost_expectation.expect_opt_price("total_parking_cost", &total_parking_cost);
    total_reservation_cost_expectation
        .expect_opt_price("total_reservation_cost", &total_reservation_cost);
}

/// Expectations for the result of calling `cdr::parse*`.
#[derive(serde::Deserialize)]
pub struct ParseExpect {
    #[serde(default)]
    unexpected_fields: Expectation<Vec<String>>,
}

/// Expectations for the result of calling `cdr::price`.
#[derive(serde::Deserialize)]
pub struct PriceExpect {
    /// Expected Warnings from parsing a CDR.
    ///
    /// Each entry in the map is an element path and a list of associated warnings.
    #[serde(default)]
    warnings: Expectation<BTreeMap<String, Vec<String>>>,

    /// Index of the tariff that was found to be active.
    #[serde(default)]
    tariff_index: Expectation<usize>,

    /// Id of the tariff that was found to be active.
    #[serde(default)]
    tariff_id: Expectation<String>,

    /// A list of the tariff IDs found in the CDR or supplied to the [`cdr::price`](crate::cdr::price) function.
    ///
    /// Each tariff may have a set of unexpected fields encountered while parsing the tariff.
    #[serde(default)]
    tariff_reports: Expectation<Vec<TariffReportExpect>>,

    /// Total sum of all the costs of this transaction in the specified currency.
    #[serde(default)]
    total_cost: Expectation<Price>,

    /// Total sum of all the fixed costs in the specified currency, except fixed price components of parking and reservation. The cost not depending on amount of time/energy used etc. Can contain costs like a start tariff.
    #[serde(default)]
    total_fixed_cost: Expectation<Price>,

    /// Total duration of the charging session (including the duration of charging and not charging), in hours.
    #[serde(default)]
    total_time: Expectation<HoursDecimal>,

    /// Total sum of all the cost related to duration of charging during this transaction, in the specified currency.
    #[serde(default)]
    total_time_cost: Expectation<Price>,

    /// Total energy charged, in kWh.
    #[serde(default)]
    total_energy: Expectation<Kwh>,

    /// Total sum of all the cost of all the energy used, in the specified currency.
    #[serde(default)]
    total_energy_cost: Expectation<Price>,

    /// Total duration of the charging session where the EV was not charging (no energy was transferred between EVSE and EV), in hours.
    #[serde(default)]
    total_parking_time: Expectation<HoursDecimal>,

    /// Total sum of all the cost related to parking of this transaction, including fixed price components, in the specified currency.
    #[serde(default)]
    total_parking_cost: Expectation<Price>,

    /// Total sum of all the cost related to a reservation of a Charge Point, including fixed price components, in the specified currency.
    #[serde(default)]
    total_reservation_cost: Expectation<Price>,
}

#[derive(Debug, Deserialize)]
struct TariffReportExpect {
    /// The id of the tariff.
    id: String,

    /// Expected Warnings from parsing a tariff.
    ///
    /// Each entry in the map is an element path and a list of associated warnings.
    #[serde(default)]
    warnings: BTreeMap<String, Vec<String>>,
}

impl Expectation<Price> {
    #[track_caller]
    fn expect_opt_price(self, field_name: &str, total: &Total<Option<Price>>) {
        if let Expectation::Present(expect_value) = self {
            match (expect_value.into_option(), total.calculated) {
                (Some(a), Some(b)) => assert!(
                    a.approx_eq(&b),
                    "Expected `{a}` but `{b}` was calculated for `{field_name}`"
                ),
                (Some(a), None) => {
                    panic!("Expected `{a}`, but no price was calculated for `{field_name}`")
                }
                (None, Some(b)) => {
                    panic!("Expected no value, but `{b}` was calculated for `{field_name}`")
                }
                (None, None) => (),
            }
        } else {
            match (total.cdr, total.calculated) {
                (None, None) => (),
                (None, Some(calculated)) => {
                    assert!(calculated.is_zero(), "The CDR field `{field_name}` doesn't have a value but a value was calculated; calculated: {calculated}");
                }
                (Some(cdr), None) => {
                    assert!(
                            cdr.is_zero(),
                            "The CDR field `{field_name}` has a value but the calculated value is none; cdr: {cdr}"
                        );
                }
                (Some(cdr), Some(calculated)) => {
                    assert!(
                        cdr.approx_eq(&calculated),
                        "Comparing `{field_name}` field with CDR"
                    );
                }
            }
        }
    }

    #[track_caller]
    fn expect_price(self, field_name: &str, total: &Total<Price, Option<Price>>) {
        if let Expectation::Present(expect_value) = self {
            match (expect_value.into_option(), total.calculated) {
                (Some(a), Some(b)) => assert!(
                    a.approx_eq(&b),
                    "Expected `{a}` but `{b}` was calculated for `{field_name}`"
                ),
                (Some(a), None) => {
                    panic!("Expected `{a}`, but no price was calculated for `{field_name}`")
                }
                (None, Some(b)) => {
                    panic!("Expected no value, but `{b}` was calculated for `{field_name}`")
                }
                (None, None) => (),
            }
        } else if let Some(calculated) = total.calculated {
            assert!(
                total.cdr.approx_eq(&calculated),
                "CDR contains `{}` but `{}` was calculated for `{field_name}`",
                total.cdr,
                calculated
            );
        } else {
            assert!(
                    total.cdr.is_zero(),
                    "The CDR field `{field_name}` has a value but the calculated value is none; cdr: {:?}",
                    total.cdr
                );
        }
    }
}

impl Expectation<HoursDecimal> {
    #[track_caller]
    fn expect_duration(self, field_name: &str, total: &Total<TimeDelta>) {
        if let Expectation::Present(expect_value) = self {
            assert_approx_eq!(
                expect_value.expect_value().to_hours_dec(),
                total.calculated.to_hours_dec(),
                "Comparing `{field_name}` field with expectation"
            );
        } else {
            assert_approx_eq!(
                total.cdr.to_hours_dec(),
                total.calculated.to_hours_dec(),
                "Comparing `{field_name}` field with CDR"
            );
        }
    }

    #[track_caller]
    fn expect_opt_duration(
        self,
        field_name: &str,
        total: &Total<Option<TimeDelta>, Option<TimeDelta>>,
    ) {
        if let Expectation::Present(expect_value) = self {
            assert_approx_eq!(
                expect_value
                    .into_option()
                    .unwrap_or_default()
                    .to_hours_dec(),
                &total
                    .calculated
                    .as_ref()
                    .map(ToHoursDecimal::to_hours_dec)
                    .unwrap_or_default(),
                "Comparing `{field_name}` field with expectation"
            );
        } else {
            assert_approx_eq!(
                total.cdr.unwrap_or_default().to_hours_dec(),
                total.calculated.unwrap_or_default().to_hours_dec(),
                "Comparing `{field_name}` field with CDR"
            );
        }
    }
}

impl Expectation<Kwh> {
    #[track_caller]
    fn expect_opt_kwh(self, field_name: &str, total: &Total<Kwh, Option<Kwh>>) {
        if let Expectation::Present(expect_value) = self {
            assert_eq!(
                expect_value
                    .into_option()
                    .map(|kwh| kwh.round_dp(PRECISION)),
                total
                    .calculated
                    .map(|kwh| kwh.rescale().round_dp(PRECISION)),
                "Comparing `{field_name}` field with expectation"
            );
        } else {
            assert_eq!(
                total.cdr.round_dp(PRECISION),
                total
                    .calculated
                    .map(|kwh| kwh.rescale().round_dp(PRECISION))
                    .unwrap_or_default(),
                "Comparing `{field_name}` field with CDR"
            );
        }
    }
}