ocpi-tariffs 0.20.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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
use std::{borrow::Cow, fmt};

use chrono_tz::Tz;
use tracing::{debug, instrument};

use crate::{
    cdr, country, from_warning_set_to, into_caveat,
    json::{self, FieldsAsExt as _, FromJson as _},
    warning::{self, GatherWarnings as _, OptionExt as _},
    Caveat, IntoCaveat, ParseError, Verdict, VerdictExt, Version, Versioned, Warning,
};

#[derive(Debug)]
pub enum WarningKind {
    /// A timezone can't be inferred from the `location`'s `country`.
    CantInferTimezoneFromCountry(&'static str),

    /// Neither the timezone or country field require char escape codes.
    ContainsEscapeCodes,

    /// The CDR location is not a valid ISO 3166-1 alpha-3 code.
    Country(country::WarningKind),

    /// The field at the path could not be decoded.
    Decode(json::decode::WarningKind),

    /// An error occurred while deserializing the `CDR`.
    Deserialize(ParseError),

    /// The CDR location is not a String.
    InvalidLocationType,

    /// The CDR location did not contain a valid IANA time-zone.
    ///
    /// See: <https://www.iana.org/time-zones>.
    InvalidTimezone,

    /// The CDR timezone is not a String.
    InvalidTimezoneType,

    /// The `location.country` field should be an alpha-3 country code.
    ///
    /// The alpha-2 code can be converted into an alpha-3 but the caller should be warned.
    LocationCountryShouldBeAlpha3,

    /// The CDR's `location` has no `country` element and so the timezone can't be inferred.
    NoLocationCountry,

    /// The CDR has no `location` element and so the timezone can't be found or inferred.
    NoLocation,

    /// An `Error` occurred while parsing the JSON or deferred JSON String decode.
    Parser(json::Error),

    /// Both the CDR and tariff JSON should be an Object.
    ShouldBeAnObject,

    /// A v221 CDR is given but it contains a `location` field instead of a `cdr_location` as defined in the spec.
    V221CdrHasLocationField,
}

from_warning_set_to!(country::WarningKind => WarningKind);

impl fmt::Display for WarningKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            WarningKind::CantInferTimezoneFromCountry(country_code) => write!(f, "Unable to infer timezone from the `location`'s `country`: `{country_code}`"),
            WarningKind::ContainsEscapeCodes => f.write_str("The CDR location contains needless escape codes."),
            WarningKind::Country(kind) => fmt::Display::fmt(kind, f),
            WarningKind::Decode(warning) => fmt::Display::fmt(warning, f),
            WarningKind::Deserialize(err) => fmt::Display::fmt(err, f),
            WarningKind::InvalidLocationType => f.write_str("The CDR location is not a String."),
            WarningKind::InvalidTimezone => f.write_str("The CDR location did not contain a valid IANA time-zone."),
            WarningKind::InvalidTimezoneType => f.write_str("The CDR timezone is not a String."),
            WarningKind::LocationCountryShouldBeAlpha3 => f.write_str("The `location.country` field should be an alpha-3 country code."),
            WarningKind::NoLocationCountry => {
                f.write_str("The CDR's `location` has no `country` element and so the timezone can't be inferred.")
            },
            WarningKind::NoLocation => {
                f.write_str("The CDR has no `location` element and so the timezone can't be found or inferred.")                   
            }
            WarningKind::Parser(err) => fmt::Display::fmt(err, f),
            WarningKind::ShouldBeAnObject => f.write_str("The CDR should be a JSON object"),
            WarningKind::V221CdrHasLocationField => f.write_str("the v2.2.1 CDR contains a `location` field but the v2.2.1 spec defines a `cdr_location` field."),

        }
    }
}

impl warning::Kind for WarningKind {
    fn id(&self) -> Cow<'static, str> {
        match self {
            WarningKind::CantInferTimezoneFromCountry(_) => {
                "cant_infer_timezone_from_country".into()
            }
            WarningKind::ContainsEscapeCodes => "contains_escape_codes".into(),
            WarningKind::Decode(warning) => format!("decode.{}", warning.id()).into(),
            WarningKind::Deserialize(err) => format!("deserialize.{err}").into(),
            WarningKind::Country(warning) => format!("country.{}", warning.id()).into(),
            WarningKind::InvalidLocationType => "invalid_location_type".into(),
            WarningKind::InvalidTimezone => "invalid_timezone".into(),
            WarningKind::InvalidTimezoneType => "invalid_timezone_type".into(),
            WarningKind::LocationCountryShouldBeAlpha3 => {
                "location_country_should_be_alpha3".into()
            }
            WarningKind::NoLocationCountry => "no_location_country".into(),
            WarningKind::NoLocation => "no_location".into(),
            WarningKind::Parser(err) => format!("parser.{err}").into(),
            WarningKind::ShouldBeAnObject => "should_be_an_object".into(),
            WarningKind::V221CdrHasLocationField => "v221_cdr_has_location_field".into(),
        }
    }
}

/// The source of the timezone
#[derive(Copy, Clone, Debug)]
pub enum Source {
    /// The timezone was found in the `location` element.
    Found(Tz),

    /// The timezone is inferred from the `location`'s `country`.
    Inferred(Tz),
}

into_caveat!(Source);
into_caveat!(Tz);

impl Source {
    /// Return the timezone and disregard where it came from.
    pub fn into_timezone(self) -> Tz {
        match self {
            Source::Found(tz) | Source::Inferred(tz) => tz,
        }
    }
}

/// Try find or infer the timezone from the `CDR` JSON.
///
/// Return `Some` if the timezone can be found or inferred.
/// Return `None` if the timezone is not found and can't be inferred.
///
/// Finding a timezone is an infallible operation. If invalid data is found a `None` is returned
/// with an appropriate warning.
///
/// If the `CDR` contains a `time_zone` in the location object then that is simply returned.
/// Only pre-v2.2.1 CDR's have a `time_zone` field in the `Location` ocject.
///
/// Inferring the timezone only works for `CDR`s from European countries.
///
pub fn find_or_infer(cdr: &cdr::Versioned<'_>) -> Caveat<Option<Source>, WarningKind> {
    const LOCATION_FIELD_V211: &str = "location";
    const LOCATION_FIELD_V221: &str = "cdr_location";
    const TIMEZONE_FIELD: &str = "time_zone";
    const COUNTRY_FIELD: &str = "country";

    let mut warnings = warning::Set::new();

    let cdr_root = cdr.as_element();
    let Some(fields) = cdr_root.as_object_fields() else {
        warnings.with_elem(WarningKind::ShouldBeAnObject, cdr_root);
        return None.into_caveat(warnings);
    };

    let cdr_fields = fields.as_raw_map();

    let v211_location = cdr_fields.get(LOCATION_FIELD_V211);

    // OCPI v221 changed the `location` field to `cdr_location`.
    //
    // * See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#131-cdr-object>
    // * See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_cdrs.md#3-object-description>
    if cdr.version() == Version::V221 && v211_location.is_some() {
        warnings.with_elem(WarningKind::V221CdrHasLocationField, cdr_root);
    }

    // Describes the location that the charge-session took place at.
    //
    // The v211 CDR has a `location` field, while the v221 CDR has a `cdr_location` field.
    //
    // * See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#131-cdr-object>
    // * See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_cdrs.md#3-object-description>
    let Some(location_elem) = v211_location.or_else(|| cdr_fields.get(LOCATION_FIELD_V221)) else {
        warnings.with_elem(WarningKind::NoLocation, cdr_root);
        return None.into_caveat(warnings);
    };

    let json::Value::Object(fields) = location_elem.as_value() else {
        warnings.with_elem(WarningKind::InvalidLocationType, cdr_root);
        return None.into_caveat(warnings);
    };

    let location_fields = fields.as_raw_map();

    debug!("Searching for time-zone in CDR");

    // The `location::time_zone` field is optional in v211 and not defined in the v221 spec.
    //
    // See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#mod_cdrs_cdr_location_class>
    // See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_locations.md#31-location-object>
    let tz = location_fields.get(TIMEZONE_FIELD).and_then(|elem| {
        let tz = try_parse_location_timezone(elem).ok_caveat();
        tz.gather_warnings_into(&mut warnings)
    });

    if let Some(tz) = tz {
        return Some(Source::Found(tz)).into_caveat(warnings);
    }

    debug!("No time-zone found in CDR; trying to infer time-zone from country");

    // ISO 3166-1 alpha-3 code for the country of this location.
    let Some(country_elem) = location_fields.get(COUNTRY_FIELD) else {
        // The `location::country` field is required.
        //
        // See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#mod_cdrs_cdr_location_class>
        // See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_locations.md#31-location-object>
        warnings.with_elem(WarningKind::NoLocationCountry, location_elem);
        return None.into_caveat(warnings);
    };

    let Some(timezone) = infer_timezone_from_location_country(country_elem)
        .ok_caveat()
        .gather_warnings_into(&mut warnings)
    else {
        return None.into_caveat(warnings);
    };

    Some(Source::Inferred(timezone)).into_caveat(warnings)
}

impl From<json::decode::WarningKind> for WarningKind {
    fn from(warn_kind: json::decode::WarningKind) -> Self {
        Self::Decode(warn_kind)
    }
}

impl From<country::WarningKind> for WarningKind {
    fn from(warn_kind: country::WarningKind) -> Self {
        Self::Country(warn_kind)
    }
}

/// Try parse the `location` element's timezone into a `Tz`.
fn try_parse_location_timezone(tz_elem: &json::Element<'_>) -> Verdict<Tz, WarningKind> {
    let tz = tz_elem.as_value();
    debug!(tz = %tz, "Raw time-zone found in CDR");

    let mut warnings = warning::Set::new();
    // IANA tzdata's TZ-values representing the time-zone of the location. Examples: "Europe/Oslo", "Europe/Zurich"
    let Some(tz) = tz.as_raw_str() else {
        warnings.with_elem(WarningKind::InvalidTimezoneType, tz_elem);
        return Err(warnings);
    };

    let tz = tz
        .decode_escapes(tz_elem)
        .gather_warnings_into(&mut warnings);

    if matches!(tz, Cow::Owned(_)) {
        warnings.with_elem(WarningKind::ContainsEscapeCodes, tz_elem);
    }

    debug!(%tz, "Escaped time-zone found in CDR");

    let Ok(tz) = tz.parse::<Tz>() else {
        warnings.with_elem(WarningKind::InvalidTimezone, tz_elem);
        return Err(warnings);
    };

    Ok(tz.into_caveat(warnings))
}

/// Try infer a timezone from the `location` elements `country` field.
#[instrument(skip_all)]
fn infer_timezone_from_location_country(
    country_elem: &json::Element<'_>,
) -> Verdict<Tz, WarningKind> {
    let mut warnings = warning::Set::new();
    let code_set = country::CodeSet::from_json(country_elem)?.gather_warnings_into(&mut warnings);

    // The `location.country` field should be an alpha-3 country code.
    //
    // The alpha-2 code can be converted into an alpha-3 but the caller should be warned.
    let country_code = match code_set {
        country::CodeSet::Alpha2(code) => {
            warnings.with_elem(WarningKind::LocationCountryShouldBeAlpha3, country_elem);
            code
        }
        country::CodeSet::Alpha3(code) => code,
    };
    let tz = try_detect_timezone(country_code).exit_with_warning(warnings, || {
        Warning::with_elem(
            WarningKind::CantInferTimezoneFromCountry(country_code.into_str()),
            country_elem,
        )
    })?;

    Ok(tz)
}

/// Mapping of European countries to time-zones with geographical naming
///
/// This is only possible for countries with a single time-zone and only for countries as they
/// currently exist (2024). It's a best effort approach to determine a time-zone from just a ALPHA-3
/// ISO 3166-1 country code.
///
/// In small edge cases (e.g. Gibraltar) this detection might generate the wrong time-zone.
#[instrument]
fn try_detect_timezone(country_code: country::Code) -> Option<Tz> {
    let tz = match country_code {
        country::Code::Ad => Tz::Europe__Andorra,
        country::Code::Al => Tz::Europe__Tirane,
        country::Code::At => Tz::Europe__Vienna,
        country::Code::Ba => Tz::Europe__Sarajevo,
        country::Code::Be => Tz::Europe__Brussels,
        country::Code::Bg => Tz::Europe__Sofia,
        country::Code::By => Tz::Europe__Minsk,
        country::Code::Ch => Tz::Europe__Zurich,
        country::Code::Cy => Tz::Europe__Nicosia,
        country::Code::Cz => Tz::Europe__Prague,
        country::Code::De => Tz::Europe__Berlin,
        country::Code::Dk => Tz::Europe__Copenhagen,
        country::Code::Ee => Tz::Europe__Tallinn,
        country::Code::Es => Tz::Europe__Madrid,
        country::Code::Fi => Tz::Europe__Helsinki,
        country::Code::Fr => Tz::Europe__Paris,
        country::Code::Gb => Tz::Europe__London,
        country::Code::Gr => Tz::Europe__Athens,
        country::Code::Hr => Tz::Europe__Zagreb,
        country::Code::Hu => Tz::Europe__Budapest,
        country::Code::Ie => Tz::Europe__Dublin,
        country::Code::Is => Tz::Iceland,
        country::Code::It => Tz::Europe__Rome,
        country::Code::Li => Tz::Europe__Vaduz,
        country::Code::Lt => Tz::Europe__Vilnius,
        country::Code::Lu => Tz::Europe__Luxembourg,
        country::Code::Lv => Tz::Europe__Riga,
        country::Code::Mc => Tz::Europe__Monaco,
        country::Code::Md => Tz::Europe__Chisinau,
        country::Code::Me => Tz::Europe__Podgorica,
        country::Code::Mk => Tz::Europe__Skopje,
        country::Code::Mt => Tz::Europe__Malta,
        country::Code::Nl => Tz::Europe__Amsterdam,
        country::Code::No => Tz::Europe__Oslo,
        country::Code::Pl => Tz::Europe__Warsaw,
        country::Code::Pt => Tz::Europe__Lisbon,
        country::Code::Ro => Tz::Europe__Bucharest,
        country::Code::Rs => Tz::Europe__Belgrade,
        country::Code::Ru => Tz::Europe__Moscow,
        country::Code::Se => Tz::Europe__Stockholm,
        country::Code::Si => Tz::Europe__Ljubljana,
        country::Code::Sk => Tz::Europe__Bratislava,
        country::Code::Sm => Tz::Europe__San_Marino,
        country::Code::Tr => Tz::Turkey,
        country::Code::Ua => Tz::Europe__Kiev,
        _ => return None,
    };

    debug!(%tz, "time-zone detected");

    Some(tz)
}

#[cfg(test)]
pub mod test {
    #![allow(clippy::missing_panics_doc, reason = "tests are allowed to panic")]
    #![allow(clippy::panic, reason = "tests are allowed panic")]

    use std::collections::BTreeMap;

    use crate::{cdr, json, warning};

    use super::{Source, WarningKind};

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

        /// A list of expected warnings by `Warning::id()`.
        pub warnings: BTreeMap<String, Vec<String>>,
    }

    #[track_caller]
    pub(crate) fn assert_find_or_infer_outcome(
        cdr: &cdr::Versioned<'_>,
        timezone: Source,
        expect: Option<&FindOrInferExpect>,
        warnings: &warning::Set<WarningKind>,
    ) {
        let elem_map = json::test::ElementMap::for_elem(cdr.as_element());

        let Some(expect) = expect else {
            return;
        };

        for warning in warnings {
            let path = elem_map.path(warning.elem_id().unwrap());
            let id = warning.id();
            let path_string = path.to_string();

            if let Some(timezone_expected) = &expect.timezone {
                assert_eq!(timezone_expected, &timezone.into_timezone().to_string());
            }

            let Some(expected_warnings) = expect.warnings.get(&*path_string) else {
                panic!(
                    "There are no warnings expected for path: `{path_string}`; warnings: {:?}",
                    warnings.iter().map(crate::Warning::id).collect::<Vec<_>>()
                );
            };

            assert!(
                expected_warnings.iter().any(|w| warning.id() == *w),
                "Warning `{id}` not expected for path: `{path_string}`",
            );
        }
    }
}

#[cfg(test)]
mod test_find_or_infer {
    use assert_matches::assert_matches;

    use crate::{cdr, json, test, timezone::WarningKind, warning, Version};

    use super::{find_or_infer, Source};

    #[test]
    fn should_find_timezone() {
        const JSON: &str = r#"{
    "country_code": "NL",
    "cdr_location": {
        "time_zone": "Europe/Amsterdam"
    }
}"#;

        test::setup();
        let (_cdr, timezone, warnings) = parse_expect_v221_and_time_zone_field(JSON);

        assert_matches!(timezone, Source::Found(chrono_tz::Tz::Europe__Amsterdam));
        assert_matches!(*warnings, []);
    }

    #[test]
    fn should_find_timezone_but_warn_about_use_of_location_for_v221_cdr() {
        const JSON: &str = r#"{
    "country_code": "NL",
    "location": {
        "time_zone": "Europe/Amsterdam"
    }
}"#;

        test::setup();
        // If you parse a CDR that has a `location` field as v221 you will get multiple warnings...
        let cdr::ParseReport {
            cdr,
            unexpected_fields,
        } = cdr::parse_with_version(JSON, Version::V221).unwrap();

        // The parse function will complain about unexpected fields
        test::assert_unexpected_fields(&unexpected_fields, &["$.location", "$.location.time_zone"]);

        let (timezone_source, warnings) = find_or_infer(&cdr).into_parts();
        let warnings = warnings.into_kind_vec();
        let timezone_source = timezone_source.unwrap();

        assert_matches!(
            timezone_source,
            Source::Found(chrono_tz::Tz::Europe__Amsterdam)
        );
        // And the `find_or_infer` fn will warn about a v221 CDR having a `location` field.
        assert_matches!(*warnings, [WarningKind::V221CdrHasLocationField]);
    }

    #[test]
    fn should_find_timezone_without_cdr_country() {
        const JSON: &str = r#"{
    "cdr_location": {
        "time_zone": "Europe/Amsterdam"
    }
}"#;

        test::setup();
        let (_cdr, timezone, warnings) = parse_expect_v221_and_time_zone_field(JSON);

        assert_matches!(timezone, Source::Found(chrono_tz::Tz::Europe__Amsterdam));
        assert_matches!(*warnings, []);
    }

    #[test]
    fn should_infer_timezone_and_warn_about_invalid_type() {
        const JSON: &str = r#"{
    "country_code": "NL",
    "cdr_location": {
        "time_zone": null,
        "country": "BEL"
    }
}"#;

        test::setup();
        let (_cdr, timezone, warnings) = parse_expect_v221_and_time_zone_field(JSON);
        let warnings = warnings.into_kind_vec();

        assert_matches!(timezone, Source::Inferred(chrono_tz::Tz::Europe__Brussels));
        assert_matches!(*warnings, [WarningKind::InvalidTimezoneType]);
    }

    #[test]
    fn should_find_timezone_and_warn_about_invalid_type() {
        const JSON: &str = r#"{
    "country_code": "NL",
    "cdr_location": {
        "time_zone": "Europe/Hamsterdam",
        "country": "BEL"
    }
}"#;

        test::setup();
        let (_cdr, timezone, warnings) = parse_expect_v221_and_time_zone_field(JSON);
        let warnings = warnings.into_kind_vec();

        assert_matches!(timezone, Source::Inferred(chrono_tz::Tz::Europe__Brussels));
        assert_matches!(*warnings, [WarningKind::InvalidTimezone]);
    }

    #[test]
    fn should_find_timezone_and_warn_about_escape_codes_and_invalid_type() {
        const JSON: &str = r#"{
    "country_code": "NL",
    "cdr_location": {
        "time_zone": "Europe\/Hamsterdam",
        "country": "BEL"
    }
}"#;

        test::setup();
        let (cdr, timezone, warnings) = parse_expect_v221_and_time_zone_field(JSON);
        let warnings = warnings.into_parts_vec();

        assert_matches!(timezone, Source::Inferred(chrono_tz::Tz::Europe__Brussels));
        let elem_id = assert_matches!(
            &*warnings,
            [
                (WarningKind::ContainsEscapeCodes, elem_id),
                (WarningKind::InvalidTimezone, _)
            ] => elem_id
        );

        let cdr_elem = cdr.into_element();
        let elem_map = json::test::ElementMap::for_elem(&cdr_elem);
        let elem = elem_map.get(elem_id.unwrap());
        assert_eq!(elem.path(), "$.cdr_location.time_zone");
    }

    #[test]
    fn should_find_timezone_and_warn_about_escape_codes() {
        const JSON: &str = r#"{
    "country_code": "NL",
    "cdr_location": {
        "time_zone": "Europe\/Amsterdam",
        "country": "BEL"
    }
}"#;

        test::setup();
        let (cdr, timezone, warnings) = parse_expect_v221_and_time_zone_field(JSON);
        let warnings = warnings.into_parts_vec();

        assert_matches!(timezone, Source::Found(chrono_tz::Tz::Europe__Amsterdam));
        let elem_id = assert_matches!(
            &*warnings,
            [( WarningKind::ContainsEscapeCodes, elem_id )] => elem_id
        );
        assert_elem_path(
            cdr.as_element(),
            elem_id.unwrap(),
            "$.cdr_location.time_zone",
        );
    }

    #[test]
    fn should_infer_timezone_from_location_country() {
        const JSON: &str = r#"{
    "country_code": "NL",
    "cdr_location": {
        "country": "BEL"
    }
}"#;

        test::setup();
        let (_cdr, timezone, warnings) = parse_expect_v221(JSON);

        assert_matches!(
            timezone,
            Some(Source::Inferred(chrono_tz::Tz::Europe__Brussels))
        );
        assert_matches!(*warnings, []);
    }

    #[test]
    fn should_find_timezone_but_report_alpha2_location_country_code() {
        const JSON: &str = r#"{
    "country_code": "NL",
    "cdr_location": {
        "country": "BE"
    }
}"#;

        test::setup();
        let (cdr, timezone, warnings) = parse_expect_v221(JSON);
        let warnings = warnings.into_parts_vec();

        assert_matches!(
            timezone,
            Some(Source::Inferred(chrono_tz::Tz::Europe__Brussels))
        );
        let elem_id = assert_matches!(
            &*warnings,
            [(
                WarningKind::LocationCountryShouldBeAlpha3,
                elem_id
            )] => elem_id
        );

        assert_elem_path(cdr.as_element(), elem_id.unwrap(), "$.cdr_location.country");
    }

    #[test]
    fn should_not_find_timezone_due_to_no_location() {
        const JSON: &str = r#"{ "country_code": "BE" }"#;

        test::setup();
        let (cdr, source, warnings) = parse_expect_v221(JSON);
        let warnings = warnings.into_parts_vec();
        assert_matches!(source, None);

        let elem_id = assert_matches!(&*warnings, [( WarningKind::NoLocation, elem_id)] => elem_id);

        assert_elem_path(cdr.as_element(), elem_id.unwrap(), "$");
    }

    #[test]
    fn should_not_find_timezone_due_to_no_country() {
        // The `$.country_code` field is not used at all when inferring the timezone.
        const JSON: &str = r#"{
    "country_code": "BELGIUM",
    "cdr_location": {}
}"#;

        test::setup();
        let (cdr, source, warnings) = parse_expect_v221(JSON);
        let warnings = warnings.into_parts_vec();

        assert_matches!(source, None);
        let elem_id =
            assert_matches!(&*warnings, [(WarningKind::NoLocationCountry, elem_id)] => elem_id);
        assert_elem_path(cdr.as_element(), elem_id.unwrap(), "$.cdr_location");
    }

    #[test]
    fn should_not_find_timezone_due_to_country_having_many_timezones() {
        const JSON: &str = r#"{
    "country_code": "BE",
    "cdr_location": {
        "country": "CHN"
    }
}"#;

        test::setup();
        let (cdr, source, warnings) = parse_expect_v221(JSON);
        let warnings = warnings.into_parts_vec();
        assert_matches!(source, None);

        let elem_id = assert_matches!(
            &*warnings,
            [(WarningKind::CantInferTimezoneFromCountry("CN"), elem_id)] => elem_id
        );

        assert_elem_path(cdr.as_element(), elem_id.unwrap(), "$.cdr_location.country");
    }

    #[test]
    fn should_fail_due_to_json_not_being_object() {
        const JSON: &str = r#"["not_a_cdr"]"#;

        test::setup();
        let (cdr, source, warnings) = parse_expect_v221(JSON);
        let warnings = warnings.into_parts_vec();
        assert_matches!(source, None);

        let elem_id = assert_matches!(
            &*warnings,
            [(WarningKind::ShouldBeAnObject, elem_id)] => elem_id
        );
        assert_elem_path(cdr.as_element(), elem_id.unwrap(), "$");
    }

    /// Parse CDR and infer the timezone and assert that there are no unexpected fields.
    #[track_caller]
    fn parse_expect_v221(
        json: &str,
    ) -> (
        cdr::Versioned<'_>,
        Option<Source>,
        warning::Set<WarningKind>,
    ) {
        let cdr::ParseReport {
            cdr,
            unexpected_fields,
        } = cdr::parse_with_version(json, Version::V221).unwrap();
        test::assert_no_unexpected_fields(&unexpected_fields);

        let (timezone_source, warnings) = find_or_infer(&cdr).into_parts();
        (cdr, timezone_source, warnings)
    }

    /// Parse CDR and infer the timezone and assert that the `$.cdr_location.time_zone` fields .
    #[track_caller]
    fn parse_expect_v221_and_time_zone_field(
        json: &str,
    ) -> (cdr::Versioned<'_>, Source, warning::Set<WarningKind>) {
        let cdr::ParseReport {
            cdr,
            unexpected_fields,
        } = cdr::parse_with_version(json, Version::V221).unwrap();
        test::assert_unexpected_fields(&unexpected_fields, &["$.cdr_location.time_zone"]);

        let (timezone_source, warnings) = find_or_infer(&cdr).into_parts();
        (cdr, timezone_source.unwrap(), warnings)
    }

    /// Assert that the `Element` has a path.
    #[track_caller]
    fn assert_elem_path(elem: &json::Element<'_>, elem_id: json::ElemId, path: &str) {
        let elem_map = json::test::ElementMap::for_elem(elem);
        let elem = elem_map.get(elem_id);

        assert_eq!(elem.path(), path);
    }
}