ocpi-tariffs 0.55.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
//! Parse a CDR and price the result with a tariff.

#[cfg(test)]
mod test;
#[cfg(test)]
mod test_every_field_set;

#[cfg(test)]
mod test_tariffs;

use std::{fmt, ops::Range};

use jiff::{Timestamp, tz::TimeZone};

use crate::{
    FromSchema as _, Verdict, country, currency, datetime, duration, from_warning_all, generate,
    json, money, number, price,
    schema::{self, HasElement as _},
    string, tariff, version,
    warning::{self, Caveat},
};

/// Infer which OCPI [`Version`](crate::Version) a CDR [`json::Document`] is, without checking
/// the document against the schema.
///
/// Use this when the version of the CDR is not known up front.
/// A caller gets the [`json::Document`] from [`json::parse_object`].
/// The returned [`VersionGuess`] is [`Certain`](version::Guess::Certain) when the CDR's fields
/// settle which version it is, and [`Uncertain`](version::Guess::Uncertain) otherwise.
///
/// To check the CDR against the OCPI schema, pass the guessed document and version to [`check`].
///
/// # Examples
///
/// ```rust
/// use ocpi_tariffs::{cdr, json, Version, version::Versioned as _};
/// #
/// # const CDR_JSON: &str = include_str!("cdr.json");
///
/// let doc = json::parse_object(CDR_JSON)?;
/// let cdr = cdr::infer_version(doc).certain_or(Version::V211);
/// let version = cdr.version();
/// let (cdr, warnings) = cdr::check(cdr.into_doc(), version).into_parts();
///
/// # Ok::<(), json::ParseError>(())
/// ```
pub fn infer_version(json: json::Document<'_>) -> VersionGuess<'_> {
    version::cdr_version(json)
}

/// What [`infer_version`] returns: the CDR document, paired with its version when the CDR's
/// fields settle which version it is.
pub type VersionGuess<'buf> = version::Guess<VersionedJson<'buf>, Unversioned<'buf>>;

/// Check a [`json::Document`] against the OCPI CDR schema for the given
/// [`Version`](crate::Version)[^spec-v211][^spec-v221].
///
/// `check` is the second step, after [`json::parse_object`] parses the document.
/// It reports each fault in the document's structure as a [`schema::Warning`]: a field that is
/// unexpected, missing or of the wrong JSON type, or a value of the wrong form.
/// `check` never fails, so the returned [`Caveat`] holds a [`Checked`]
/// however many faults it found.
///
/// The next step is [`build`], which reads the checked CDR into the [`Cdr`] that
/// [`price`](price()) takes.
/// [`timezone::find_or_infer`](crate::timezone::find_or_infer) also takes the checked CDR.
///
/// # Examples
///
/// ```rust
/// # use ocpi_tariffs::{cdr, json, Version};
/// #
/// # const CDR_JSON: &str = include_str!("cdr.json");
///
/// let doc = json::parse_object(CDR_JSON)?;
/// let (cdr, warnings) = cdr::check(doc, Version::V211).into_parts();
///
/// if !warnings.is_empty() {
///     eprintln!("The CDR has `{}` schema warnings.", warnings.len_warnings());
/// }
///
/// # Ok::<(), json::ParseError>(())
/// ```
///
/// [^spec-v211]: <https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_cdrs.md>.
/// [^spec-v221]: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc>.
pub fn check(
    json: json::Document<'_>,
    version: crate::Version,
) -> Caveat<Checked<'_>, schema::Warning> {
    let mut warnings = warning::Gatherer::new();
    let version = match version {
        crate::Version::V221 => Version::V221(schema::v221::build_cdr(&json, &mut warnings)),
        crate::Version::V211 => Version::V211(schema::v211::build_cdr(&json, &mut warnings)),
    };
    let checked = Checked { doc: json, version };
    Caveat::new(checked, warnings.into_set())
}

/// Build a [`Cdr`] from a checked CDR, the [`Checked`] that [`check`]
/// returns[^spec-v211][^spec-v221].
///
/// `build` is the third step, after [`json::parse_object`] and [`check`]. It reads each field's
/// value into the [`Cdr`] that [`price`](price()), the next step, takes.
/// It leaves out the tariffs the CDR contains, which [`Cdr::tariffs`] builds. A caller who
/// prices the CDR with tariffs of their own then gets no warning or failure for a fault in a
/// tariff they don't use.
///
/// `build` returns the faults it finds in the values it reads as [`Warning`]s. The faults in the
/// document's structure are the [`schema::Warning`]s that [`check`] returns.
///
/// `build` fails if a field the CDR must have is missing or can't be read, or if the CDR has no
/// charging periods. The [`Failure`](warning::Failure) then holds every warning `build` raised
/// before it failed. A required field that is missing or has the wrong JSON type makes `build`
/// fail with [`Warning::Rejected`]. For a field of the wrong type, the error names the field. For
/// a missing field, the error names the object that should hold it, and only the schema warnings
/// from [`check`] name the field.
///
/// # Examples
///
/// ```rust
/// # use ocpi_tariffs::{cdr, json, Version};
/// #
/// # const CDR_JSON: &str = include_str!("cdr.json");
///
/// let doc = json::parse_object(CDR_JSON)?;
/// let (cdr, schema_warnings) = cdr::check(doc, Version::V211).into_parts();
///
/// if !schema_warnings.is_empty() {
///     eprintln!("The CDR has `{}` schema warnings.", schema_warnings.len_warnings());
/// }
///
/// let Ok(cdr) = cdr::build(cdr) else {
///     return Err("The CDR could not be read well enough to use.".into());
/// };
/// let (cdr, warnings) = cdr.into_parts();
///
/// if !warnings.is_empty() {
///     eprintln!("The CDR has `{}` warnings.", warnings.len_warnings());
/// }
///
/// # Ok::<(), Box<dyn std::error::Error + Send + Sync + 'static>>(())
/// ```
///
/// [^spec-v211]: <https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_cdrs.md>.
/// [^spec-v221]: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc>.
pub fn build(checked: Checked<'_>) -> Verdict<Cdr<'_>, Warning> {
    let mut warnings = warning::Gatherer::new();
    let cdr = checked.lower_to_v221(&mut warnings);
    let cdr = cdr.map(|cdr| Cdr { checked, cdr });
    warnings.into_verdict(cdr)
}

/// Generate a [`PartialCdr`](generate::PartialCdr) that can be priced by the given tariff.
///
/// The CDR is partial: see [`PartialCdr`](generate::PartialCdr) for the fields the caller
/// has to supply.
///
/// A caller reaches `generate_from_tariff` by passing the tariff through
/// [`json::parse_object`], [`tariff::check`] and [`tariff::build`].
///
/// * See: [OCPI spec 2.2.1: CDR](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc>)
pub fn generate_from_tariff(
    tariff: &tariff::Tariff<'_>,
    config: &generate::Config,
) -> Verdict<generate::Report, generate::Warning> {
    let mut warnings = warning::Gatherer::new();
    let report = generate::cdr_from_tariff(tariff, config, &mut warnings);
    warnings.into_verdict(report)
}

/// Price a single `CDR` with the first of `tariffs` that is active at the session's start, and
/// return a [`Report`](price::Report).
///
/// A caller reaches `price` by passing the CDR through [`json::parse_object`], [`check`] and
/// [`build`]. [`check`] and [`build`] each report the faults they find.
/// The tariffs are either the ones the CDR contains, which [`Cdr::tariffs`] builds,
/// or tariffs the caller passes through [`json::parse_object`], [`tariff::check`] and
/// [`tariff::build`]. `price` reports only the faults pricing finds.
///
/// `price` fails with [`price::Warning::NoValidTariff`] when none of `tariffs` is active at the
/// session's start, which includes an empty `tariffs`.
///
/// > **_Note_** Pricing the CDR does not require a spec compliant CDR or tariff. `check` and
/// > `build` read as much of the CDR or the tariff as they can.
///
/// The [`Report`](price::Report) contains the charge session priced according to the specified
/// tariff and a selection of fields from the source `CDR` that can be used for comparing the
/// source `CDR` totals with the calculated totals.
///
/// The timezone can be found or inferred using the [`timezone::find_or_infer`](crate::timezone::find_or_infer) function.
///
/// # Examples
///
/// ```rust
/// # use ocpi_tariffs::{cdr, json, warning, Version};
/// #
/// # const CDR_JSON: &str = include_str!("cdr.json");
///
/// let doc = json::parse_object(CDR_JSON)?;
/// let cdr = cdr::check(doc, Version::V211).ignore_warnings();
/// let Ok(cdr) = cdr::build(cdr) else {
///     return Err("The CDR could not be read well enough to price.".into());
/// };
/// let cdr = cdr.ignore_warnings();
///
/// let Ok(tariffs) = cdr.tariffs() else {
///     return Err("The tariffs the CDR contains could not be read well enough to price.".into());
/// };
/// let tariffs = tariffs.ignore_warnings();
///
/// let Ok(report) = cdr::price(&cdr, &tariffs, &jiff::tz::get!("Europe/Amsterdam")) else {
///     return Err("The CDR could not be priced.".into());
/// };
/// let (report, warnings) = report.into_parts();
///
/// if !warnings.is_empty() {
///     eprintln!("Pricing the CDR resulted in `{}` warnings", warnings.len_warnings());
///
///     for group in warnings {
///         let (element, warnings) = group.to_parts();
///         eprintln!("  {}", element.path);
///
///         for warning in warnings {
///             eprintln!("    - {warning}");
///         }
///     }
/// }
///
/// # Ok::<(), Box<dyn std::error::Error + Send + Sync + 'static>>(())
/// ```
pub fn price(
    cdr: &Cdr<'_>,
    tariffs: &[tariff::Tariff<'_>],
    timezone: &TimeZone,
) -> Verdict<price::Report, price::Warning> {
    price::cdr(cdr, tariffs, timezone)
}

/// A CDR that [`build`] made from a checked CDR. Features such as [`price`](price()) take it.
///
/// `Debug` prints a `v2.1.1` CDR as its `v2.2.1` equivalent.
pub struct Cdr<'buf> {
    /// The checked CDR that the field `cdr` was built from.
    ///
    /// [`Cdr::tariffs`] reads the tariffs the CDR contains from it. Pricing reads from it the
    /// elements that pricing's warnings are anchored to.
    checked: Checked<'buf>,

    cdr: price::v221::Cdr,
}

impl fmt::Debug for Cdr<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.cdr, f)
    }
}

impl<'buf> Cdr<'buf> {
    /// Build the tariffs the CDR contains, in the order the CDR lists them.
    ///
    /// `tariffs` is the build step for those tariffs. It runs on the [`Cdr`] that [`build`]
    /// makes, after [`json::parse_object`] and [`check`].
    ///
    /// Pass the result to [`price`](price()) to price the CDR with its own tariffs. A CDR
    /// without a `tariffs` field contains no tariffs, and `price` fails on it with
    /// [`price::Warning::NoValidTariff`].
    ///
    /// The tariffs are read as the version of the CDR that contains them. `tariffs` returns the
    /// faults in their values as [`tariff::Warning`]s, located by their paths in the CDR. The
    /// faults in their structure are among the [`schema::Warning`]s that [`check`] returns for
    /// the CDR.
    ///
    /// `tariffs` fails on the first tariff it can't build, for the same reasons
    /// [`tariff::build`] fails. It also fails with [`tariff::Warning::Rejected`] when the
    /// `tariffs` field or one of its entries has the wrong JSON type. The
    /// [`Failure`](warning::Failure) then holds the warnings of the tariffs built before it.
    pub fn tariffs(&self) -> Verdict<Vec<tariff::Tariff<'buf>>, tariff::Warning> {
        let mut warnings = warning::Gatherer::new();
        let tariffs = self.checked.tariffs_to_v221(&mut warnings);
        warnings.into_verdict(tariffs)
    }

    pub(crate) fn as_checked(&self) -> &Checked<'buf> {
        &self.checked
    }

    pub(crate) fn as_v221(&self) -> &price::v221::Cdr {
        &self.cdr
    }
}

/// The faults [`build`] finds in a CDR's values, such as a malformed timestamp or a CDR
/// without charging periods.
///
/// The faults in the CDR's structure are the [`schema::Warning`]s that [`check`] returns. A fault
/// in the values of a tariff the CDR contains is a [`tariff::Warning`], which [`Cdr::tariffs`]
/// returns.
#[derive(Debug)]
pub enum Warning {
    /// Raised while reading a country code.
    Country(country::Warning),

    /// The `$.country_code` field names an alpha-3 code where OCPI defines it as alpha-2.
    ///
    /// The alpha-3 is read and converted to its alpha-2, so the CDR still prices. Only the CDR's
    /// own `$.country_code` raises this. A `location.country` is alpha-3 by definition and reports
    /// `timezone::Warning::LocationCountryShouldBeAlpha3` instead.
    CountryShouldBeAlpha2,

    /// Raised while reading a currency code.
    Currency(currency::Warning),

    /// Raised while reading a timestamp.
    DateTime(datetime::Warning),

    /// Raised while decoding a JSON string's escape sequences.
    Decode(json::decode::Warning),

    /// Raised while reading a duration.
    Duration(duration::Warning),

    /// Raised while reading a price.
    Money(money::Warning),

    /// The CDR has no charging periods.
    NoPeriods,

    /// Raised while reading a number.
    Number(number::Warning),

    /// The `start_date_time` of at least one of the `charging_periods` is outside of the
    /// CDR's `start_date_time`-`end_date_time` range.
    PeriodsOutsideStartEndDateTime {
        /// The session's own start and end, taken from the CDR.
        cdr_range: Range<Timestamp>,
        /// The range the charging periods actually span.
        period_range: PeriodRange,
    },

    /// Raised while reading a string.
    String(string::Warning),

    /// A required field of a CDR object was missing or invalid, so the object couldn't be read.
    /// The schema warnings locate the cause (see [`warning::Rejected`]).
    Rejected,
}

/// The range of time the CDR periods span.
#[derive(Debug)]
pub enum PeriodRange {
    /// There are many periods in the CDR and so the range is from the `start_date_time` of the first to
    /// the `start_date_time` of the last.
    Many(Range<Timestamp>),

    /// There is one period in the CDR and so one `start_date_time`.
    Single(Timestamp),
}

impl fmt::Display for PeriodRange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PeriodRange::Many(Range { start, end }) => write!(f, "[start: {start}, end: {end}]"),
            PeriodRange::Single(date_time) => write!(f, "{date_time}"),
        }
    }
}

impl fmt::Display for Warning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Country(warning) => write!(f, "{warning}"),
            Self::CountryShouldBeAlpha2 => {
                f.write_str("The `$.country_code` field should be an alpha-2 country code.")
            }
            Self::Currency(warning) => write!(f, "{warning}"),
            Self::DateTime(warning) => write!(f, "{warning}"),
            Self::Decode(warning) => write!(f, "{warning}"),
            Self::Duration(warning) => write!(f, "{warning}"),
            Self::Money(warning) => write!(f, "{warning}"),
            Self::NoPeriods => f.write_str("The CDR has no charging periods"),
            Self::Number(warning) => write!(f, "{warning}"),
            Self::PeriodsOutsideStartEndDateTime {
                cdr_range: Range { start, end },
                period_range,
            } => {
                write!(
                    f,
                    "The CDR's charging period time range is not contained within the `start_date_time` \
                    and `end_date_time`; cdr: [start: {start}, end: {end}], period: {period_range}",
                )
            }
            Self::String(warning) => write!(f, "{warning}"),
            Self::Rejected => f.write_str(
                "The schema IR for a CDR object was rejected; see the schema validation warnings.",
            ),
        }
    }
}

impl crate::Warning for Warning {
    fn id(&self) -> warning::Id {
        match self {
            Self::Country(warning) => warning.id(),
            Self::CountryShouldBeAlpha2 => warning::Id::from_static("country_should_be_alpha_2"),
            Self::Currency(warning) => warning.id(),
            Self::DateTime(warning) => warning.id(),
            Self::Decode(warning) => warning.id(),
            Self::Duration(warning) => warning.id(),
            Self::Money(warning) => warning.id(),
            Self::NoPeriods => warning::Id::from_static("no_periods"),
            Self::Number(warning) => warning.id(),
            Self::PeriodsOutsideStartEndDateTime {
                cdr_range: _,
                period_range: _,
            } => warning::Id::from_static("periods_outside_start_end_date_time"),
            Self::String(warning) => warning.id(),
            Self::Rejected => warning::Id::from_static("rejected"),
        }
    }

    fn is_rejected(&self) -> bool {
        matches!(self, Self::Rejected)
    }
}

impl From<warning::Rejected> for Warning {
    fn from(_: warning::Rejected) -> Self {
        Self::Rejected
    }
}

from_warning_all!(
    country::Warning => Warning::Country,
    currency::Warning => Warning::Currency,
    datetime::Warning => Warning::DateTime,
    duration::Warning => Warning::Duration,
    json::decode::Warning => Warning::Decode,
    money::Warning => Warning::Money,
    number::Warning => Warning::Number,
    string::Warning => Warning::String
);

/// A CDR document checked against the OCPI schema, as [`check`] returns it.
#[derive(Clone)]
pub struct Checked<'buf> {
    /// The parsed JSON.
    doc: json::Document<'buf>,

    /// The `Version` of the tariff, determined during parsing.
    version: Version<'buf>,
}

impl fmt::Debug for Checked<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            match &self.version {
                Version::V211(cdr) => fmt::Debug::fmt(&cdr, f),
                Version::V221(cdr) => fmt::Debug::fmt(&cdr, f),
            }
        } else {
            match &self.version {
                Version::V211(_) => f.write_str("V211"),
                Version::V221(_) => f.write_str("V221"),
            }
        }
    }
}

impl version::Versioned for Checked<'_> {
    fn version(&self) -> crate::Version {
        match self.version {
            Version::V211(_) => crate::Version::V211,
            Version::V221(_) => crate::Version::V221,
        }
    }
}

impl<'buf> Checked<'buf> {
    /// Lower the schema IR into the "normalized" `v221` CDR,
    /// gathering its warnings into `warnings`.
    ///
    /// A `v211` CDR is parsed as `v211` and then converted, because the two versions differ
    /// in more than field names.
    ///
    /// The two whole-CDR checks live here rather than in the `LowerSchema` impls, because only
    /// this layer has an element to anchor their warnings to: the CDR itself. A CDR with no
    /// charging periods is rejected, because there is nothing to price. The schema walk's
    /// `Cardinality` warning locates the empty array itself. A CDR whose charging periods start
    /// outside its `start_date_time` and `end_date_time` raises `PeriodsOutsideStartEndDateTime`.
    pub(crate) fn lower_to_v221(
        &self,
        warnings: &mut dyn warning::Gather<Warning>,
    ) -> Result<price::v221::Cdr, warning::Error<Warning>> {
        let cdr = match &self.version {
            Version::V211(cdr) => {
                let cdr = price::v211::Cdr::from_schema(cdr, warnings)?;

                price::v221::Cdr::from(cdr)
            }
            Version::V221(cdr) => price::v221::Cdr::from_schema(cdr, warnings)?,
        };

        if cdr.charging_periods.is_empty() {
            return Err(warning::Error::new(self.as_element(), Warning::NoPeriods));
        }

        let cdr_range = cdr.start_date_time..cdr.end_date_time;

        // The periods are sorted by the lowering above, so the first and last periods bound the range.
        let period_range = match cdr.charging_periods.as_slice() {
            [] => None,
            [period] => Some(PeriodRange::Single(period.start_date_time)),
            [earliest, .., latest] => Some(PeriodRange::Many(
                earliest.start_date_time..latest.start_date_time,
            )),
        };

        let outside = match &period_range {
            None => false,
            Some(PeriodRange::Single(start)) => !cdr_range.contains(start),
            Some(PeriodRange::Many(range)) => {
                !(cdr_range.contains(&range.start) && cdr_range.contains(&range.end))
            }
        };

        if let (true, Some(period_range)) = (outside, period_range) {
            warnings.insert(
                self.as_element(),
                Warning::PeriodsOutsideStartEndDateTime {
                    cdr_range,
                    period_range,
                },
            );
        }

        Ok(cdr)
    }

    /// Build the tariffs the CDR contains, stopping at the first that fails.
    ///
    /// Every tariff's warnings go into the one set `warnings`. The tariffs are elements of the
    /// CDR's document, so the path of each warning says which tariff raised it.
    pub(crate) fn tariffs_to_v221(
        &self,
        warnings: &mut dyn warning::Gather<tariff::Warning>,
    ) -> Result<Vec<tariff::Tariff<'buf>>, warning::Error<tariff::Warning>> {
        let mut built = Vec::new();

        // Each built tariff holds the JSON element of its entry in the `tariffs` array, which
        // this function looks up by the entry's index. Keeping the element in the IR with
        // `ir_object!(@keep_element ...)` would copy every tariff's whole JSON subtree on every
        // check, including a standalone tariff's, which never reads it.
        match &self.version {
            Version::V211(cdr) => {
                let Some(tariffs) = warnings.ok_or_reject(&cdr.tariffs)? else {
                    return Ok(built);
                };
                let items = tariffs.element().value().as_array().unwrap_or(&[]);
                for (index, tariff) in tariffs.into_iter().enumerate() {
                    let tariff = warnings.ok_or_reject(tariff)?;
                    let lowered = tariff::v211::Tariff::from_schema(tariff, warnings)?;
                    let lowered = tariff::v221::Tariff::from(lowered);
                    let element = items.get(index).unwrap_or(tariffs.element());
                    let tariff = with_element(lowered, element)?;
                    built.push(tariff);
                }
            }
            Version::V221(cdr) => {
                let Some(tariffs) = warnings.ok_or_reject(&cdr.tariffs)? else {
                    return Ok(built);
                };
                let items = tariffs.element().value().as_array().unwrap_or(&[]);
                for (index, tariff) in tariffs.into_iter().enumerate() {
                    let tariff = warnings.ok_or_reject(tariff)?;
                    let lowered = tariff::v221::Tariff::from_schema(tariff, warnings)?;
                    let element = items.get(index).unwrap_or(tariffs.element());
                    let tariff = with_element(lowered, element)?;
                    built.push(tariff);
                }
            }
        }

        Ok(built)
    }

    /// Borrow the schema IR this CDR was built into.
    ///
    /// A feature that needs a field the schema models reads it from here rather than
    /// walking the JSON, so the version differences stay in one match.
    pub(crate) fn schema(&self) -> &Version<'buf> {
        &self.version
    }

    /// Return the inner [`json::Document`] and discard the version info.
    pub fn into_doc(self) -> json::Document<'buf> {
        self.doc
    }

    /// Return the inner [`json::Document`] and discard the version info.
    pub(crate) fn as_element(&self) -> &json::Element<'buf> {
        self.doc.root()
    }

    /// Return the inner [`json::Document`] and discard the version info.
    pub fn as_doc(&self) -> &json::Document<'buf> {
        &self.doc
    }

    /// Return the inner JSON `str` and discard the version info.
    pub fn as_json_str(&self) -> &'buf str {
        self.doc.source()
    }
}

#[expect(
    clippy::large_enum_variant,
    reason = "the v2.1.1 and v2.2.1 CDR IRs differ in size; this short-lived versioned \
              value is not worth boxing"
)]
#[derive(Clone)]
pub(crate) enum Version<'buf> {
    V211(schema::v211::Cdr<'buf>),
    V221(schema::v221::Cdr<'buf>),
}

/// A `json::Document` that has been processed by [`infer_version`] and has been identified
/// as being a concrete [`Version`](crate::Version).
pub struct VersionedJson<'buf> {
    /// The parsed JSON.
    doc: json::Document<'buf>,

    /// The `Version` of the CDR, determined during parsing.
    version: crate::Version,
}

impl fmt::Debug for VersionedJson<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            fmt::Debug::fmt(&self.doc, f)
        } else {
            match self.version {
                crate::Version::V211 => f.write_str("V211"),
                crate::Version::V221 => f.write_str("V221"),
            }
        }
    }
}

impl version::Versioned for VersionedJson<'_> {
    fn version(&self) -> crate::Version {
        self.version
    }
}

impl<'buf> VersionedJson<'buf> {
    /// Create a new `Versioned` object.
    pub(crate) fn new(element: json::Document<'buf>, version: crate::Version) -> Self {
        Self {
            doc: element,
            version,
        }
    }

    /// Return the inner [`json::Document`] and discard the version info.
    pub fn into_doc(self) -> json::Document<'buf> {
        self.doc
    }

    /// Return a reference to the inner [`json::Document`].
    pub fn as_doc(&self) -> &json::Document<'buf> {
        &self.doc
    }

    /// Return the inner JSON `str` and discard the version info.
    pub fn as_json_str(&self) -> &'buf str {
        self.doc.source()
    }
}

/// A `json::Document` that has been processed by [`infer_version`] and has been identified
/// as being a concrete [`Version`](crate::Version).
#[derive(Debug)]
pub struct Unversioned<'buf> {
    /// The root `Element` of the parsed source.
    doc: json::Document<'buf>,
}

impl<'buf> Unversioned<'buf> {
    /// Create an unversioned [`json::Element`].
    pub(crate) fn new(doc: json::Document<'buf>) -> Self {
        Self { doc }
    }

    /// Return the inner [`json::Document`] and discard the version info.
    pub fn into_doc(self) -> json::Document<'buf> {
        self.doc
    }
}

impl<'buf> version::Unversioned for Unversioned<'buf> {
    type Versioned = VersionedJson<'buf>;

    fn force_into_versioned(self, version: crate::Version) -> VersionedJson<'buf> {
        let Self { doc } = self;
        VersionedJson { doc, version }
    }
}

/// Pair a tariff the CDR contains with its element, failing on a tariff with no elements.
///
/// A tariff with no elements prices every session at zero, so no feature can use it.
/// `tariff::Checked::lower_to_v221` applies the same rule to a tariff of its own document. The
/// schema walk's `Cardinality` warning locates the empty `elements` array.
fn with_element<'buf>(
    tariff: tariff::v221::Tariff<'buf>,
    element: &json::Element<'buf>,
) -> Result<tariff::Tariff<'buf>, warning::Error<tariff::Warning>> {
    if tariff.elements.is_empty() {
        return Err(warning::Error::new(element, tariff::Warning::NoElements));
    }

    Ok(tariff::Tariff::new(tariff, element.clone()))
}