Skip to main content

ocpi_tariffs/
cdr.rs

1//! Parse a CDR and price the result with a tariff.
2
3#[cfg(test)]
4mod test;
5#[cfg(test)]
6mod test_every_field_set;
7
8#[cfg(test)]
9mod test_tariffs;
10
11use std::{fmt, ops::Range};
12
13use jiff::{Timestamp, tz::TimeZone};
14
15use crate::{
16    FromSchema as _, Verdict, country, currency, datetime, duration, from_warning_all, generate,
17    json, money, number, price,
18    schema::{self, HasElement as _},
19    string, tariff, version,
20    warning::{self, Caveat},
21};
22
23/// Infer which OCPI [`Version`](crate::Version) a CDR [`json::Document`] is, without checking
24/// the document against the schema.
25///
26/// Use this when the version of the CDR is not known up front.
27/// A caller gets the [`json::Document`] from [`json::parse_object`].
28/// The returned [`VersionGuess`] is [`Certain`](version::Guess::Certain) when the CDR's fields
29/// settle which version it is, and [`Uncertain`](version::Guess::Uncertain) otherwise.
30///
31/// To check the CDR against the OCPI schema, pass the guessed document and version to [`check`].
32///
33/// # Examples
34///
35/// ```rust
36/// use ocpi_tariffs::{cdr, json, Version, version::Versioned as _};
37/// #
38/// # const CDR_JSON: &str = include_str!("cdr.json");
39///
40/// let doc = json::parse_object(CDR_JSON)?;
41/// let cdr = cdr::infer_version(doc).certain_or(Version::V211);
42/// let version = cdr.version();
43/// let (cdr, warnings) = cdr::check(cdr.into_doc(), version).into_parts();
44///
45/// # Ok::<(), json::ParseError>(())
46/// ```
47pub fn infer_version(json: json::Document<'_>) -> VersionGuess<'_> {
48    version::cdr_version(json)
49}
50
51/// What [`infer_version`] returns: the CDR document, paired with its version when the CDR's
52/// fields settle which version it is.
53pub type VersionGuess<'buf> = version::Guess<VersionedJson<'buf>, Unversioned<'buf>>;
54
55/// Check a [`json::Document`] against the OCPI CDR schema for the given
56/// [`Version`](crate::Version)[^spec-v211][^spec-v221].
57///
58/// `check` is the second step, after [`json::parse_object`] parses the document.
59/// It reports each fault in the document's structure as a [`schema::Warning`]: a field that is
60/// unexpected, missing or of the wrong JSON type, or a value of the wrong form.
61/// `check` never fails, so the returned [`Caveat`] holds a [`Checked`]
62/// however many faults it found.
63///
64/// The next step is [`build`], which reads the checked CDR into the [`Cdr`] that
65/// [`price`](price()) takes.
66/// [`timezone::find_or_infer`](crate::timezone::find_or_infer) also takes the checked CDR.
67///
68/// # Examples
69///
70/// ```rust
71/// # use ocpi_tariffs::{cdr, json, Version};
72/// #
73/// # const CDR_JSON: &str = include_str!("cdr.json");
74///
75/// let doc = json::parse_object(CDR_JSON)?;
76/// let (cdr, warnings) = cdr::check(doc, Version::V211).into_parts();
77///
78/// if !warnings.is_empty() {
79///     eprintln!("The CDR has `{}` schema warnings.", warnings.len_warnings());
80/// }
81///
82/// # Ok::<(), json::ParseError>(())
83/// ```
84///
85/// [^spec-v211]: <https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_cdrs.md>.
86/// [^spec-v221]: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc>.
87pub fn check(
88    json: json::Document<'_>,
89    version: crate::Version,
90) -> Caveat<Checked<'_>, schema::Warning> {
91    let mut warnings = warning::Gatherer::new();
92    let version = match version {
93        crate::Version::V221 => Version::V221(schema::v221::build_cdr(&json, &mut warnings)),
94        crate::Version::V211 => Version::V211(schema::v211::build_cdr(&json, &mut warnings)),
95    };
96    let checked = Checked { doc: json, version };
97    Caveat::new(checked, warnings.into_set())
98}
99
100/// Build a [`Cdr`] from a checked CDR, the [`Checked`] that [`check`]
101/// returns[^spec-v211][^spec-v221].
102///
103/// `build` is the third step, after [`json::parse_object`] and [`check`]. It reads each field's
104/// value into the [`Cdr`] that [`price`](price()), the next step, takes.
105/// It leaves out the tariffs the CDR contains, which [`Cdr::tariffs`] builds. A caller who
106/// prices the CDR with tariffs of their own then gets no warning or failure for a fault in a
107/// tariff they don't use.
108///
109/// `build` returns the faults it finds in the values it reads as [`Warning`]s. The faults in the
110/// document's structure are the [`schema::Warning`]s that [`check`] returns.
111///
112/// `build` fails if a field the CDR must have is missing or can't be read, or if the CDR has no
113/// charging periods. The [`Failure`](warning::Failure) then holds every warning `build` raised
114/// before it failed. A required field that is missing or has the wrong JSON type makes `build`
115/// fail with [`Warning::Rejected`]. For a field of the wrong type, the error names the field. For
116/// a missing field, the error names the object that should hold it, and only the schema warnings
117/// from [`check`] name the field.
118///
119/// # Examples
120///
121/// ```rust
122/// # use ocpi_tariffs::{cdr, json, Version};
123/// #
124/// # const CDR_JSON: &str = include_str!("cdr.json");
125///
126/// let doc = json::parse_object(CDR_JSON)?;
127/// let (cdr, schema_warnings) = cdr::check(doc, Version::V211).into_parts();
128///
129/// if !schema_warnings.is_empty() {
130///     eprintln!("The CDR has `{}` schema warnings.", schema_warnings.len_warnings());
131/// }
132///
133/// let Ok(cdr) = cdr::build(cdr) else {
134///     return Err("The CDR could not be read well enough to use.".into());
135/// };
136/// let (cdr, warnings) = cdr.into_parts();
137///
138/// if !warnings.is_empty() {
139///     eprintln!("The CDR has `{}` warnings.", warnings.len_warnings());
140/// }
141///
142/// # Ok::<(), Box<dyn std::error::Error + Send + Sync + 'static>>(())
143/// ```
144///
145/// [^spec-v211]: <https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_cdrs.md>.
146/// [^spec-v221]: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc>.
147pub fn build(checked: Checked<'_>) -> Verdict<Cdr<'_>, Warning> {
148    let mut warnings = warning::Gatherer::new();
149    let cdr = checked.lower_to_v221(&mut warnings);
150    let cdr = cdr.map(|cdr| Cdr { checked, cdr });
151    warnings.into_verdict(cdr)
152}
153
154/// Generate a [`PartialCdr`](generate::PartialCdr) that can be priced by the given tariff.
155///
156/// The CDR is partial: see [`PartialCdr`](generate::PartialCdr) for the fields the caller
157/// has to supply.
158///
159/// A caller reaches `generate_from_tariff` by passing the tariff through
160/// [`json::parse_object`], [`tariff::check`] and [`tariff::build`].
161///
162/// * See: [OCPI spec 2.2.1: CDR](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc>)
163pub fn generate_from_tariff(
164    tariff: &tariff::Tariff<'_>,
165    config: &generate::Config,
166) -> Verdict<generate::Report, generate::Warning> {
167    let mut warnings = warning::Gatherer::new();
168    let report = generate::cdr_from_tariff(tariff, config, &mut warnings);
169    warnings.into_verdict(report)
170}
171
172/// Price a single `CDR` with the first of `tariffs` that is active at the session's start, and
173/// return a [`Report`](price::Report).
174///
175/// A caller reaches `price` by passing the CDR through [`json::parse_object`], [`check`] and
176/// [`build`]. [`check`] and [`build`] each report the faults they find.
177/// The tariffs are either the ones the CDR contains, which [`Cdr::tariffs`] builds,
178/// or tariffs the caller passes through [`json::parse_object`], [`tariff::check`] and
179/// [`tariff::build`]. `price` reports only the faults pricing finds.
180///
181/// `price` fails with [`price::Warning::NoValidTariff`] when none of `tariffs` is active at the
182/// session's start, which includes an empty `tariffs`.
183///
184/// > **_Note_** Pricing the CDR does not require a spec compliant CDR or tariff. `check` and
185/// > `build` read as much of the CDR or the tariff as they can.
186///
187/// The [`Report`](price::Report) contains the charge session priced according to the specified
188/// tariff and a selection of fields from the source `CDR` that can be used for comparing the
189/// source `CDR` totals with the calculated totals.
190///
191/// The timezone can be found or inferred using the [`timezone::find_or_infer`](crate::timezone::find_or_infer) function.
192///
193/// # Examples
194///
195/// ```rust
196/// # use ocpi_tariffs::{cdr, json, warning, Version};
197/// #
198/// # const CDR_JSON: &str = include_str!("cdr.json");
199///
200/// let doc = json::parse_object(CDR_JSON)?;
201/// let cdr = cdr::check(doc, Version::V211).ignore_warnings();
202/// let Ok(cdr) = cdr::build(cdr) else {
203///     return Err("The CDR could not be read well enough to price.".into());
204/// };
205/// let cdr = cdr.ignore_warnings();
206///
207/// let Ok(tariffs) = cdr.tariffs() else {
208///     return Err("The tariffs the CDR contains could not be read well enough to price.".into());
209/// };
210/// let tariffs = tariffs.ignore_warnings();
211///
212/// let Ok(report) = cdr::price(&cdr, &tariffs, &jiff::tz::get!("Europe/Amsterdam")) else {
213///     return Err("The CDR could not be priced.".into());
214/// };
215/// let (report, warnings) = report.into_parts();
216///
217/// if !warnings.is_empty() {
218///     eprintln!("Pricing the CDR resulted in `{}` warnings", warnings.len_warnings());
219///
220///     for group in warnings {
221///         let (element, warnings) = group.to_parts();
222///         eprintln!("  {}", element.path);
223///
224///         for warning in warnings {
225///             eprintln!("    - {warning}");
226///         }
227///     }
228/// }
229///
230/// # Ok::<(), Box<dyn std::error::Error + Send + Sync + 'static>>(())
231/// ```
232pub fn price(
233    cdr: &Cdr<'_>,
234    tariffs: &[tariff::Tariff<'_>],
235    timezone: &TimeZone,
236) -> Verdict<price::Report, price::Warning> {
237    price::cdr(cdr, tariffs, timezone)
238}
239
240/// A CDR that [`build`] made from a checked CDR. Features such as [`price`](price()) take it.
241///
242/// `Debug` prints a `v2.1.1` CDR as its `v2.2.1` equivalent.
243pub struct Cdr<'buf> {
244    /// The checked CDR that the field `cdr` was built from.
245    ///
246    /// [`Cdr::tariffs`] reads the tariffs the CDR contains from it. Pricing reads from it the
247    /// elements that pricing's warnings are anchored to.
248    checked: Checked<'buf>,
249
250    cdr: price::v221::Cdr,
251}
252
253impl fmt::Debug for Cdr<'_> {
254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255        fmt::Debug::fmt(&self.cdr, f)
256    }
257}
258
259impl<'buf> Cdr<'buf> {
260    /// Build the tariffs the CDR contains, in the order the CDR lists them.
261    ///
262    /// `tariffs` is the build step for those tariffs. It runs on the [`Cdr`] that [`build`]
263    /// makes, after [`json::parse_object`] and [`check`].
264    ///
265    /// Pass the result to [`price`](price()) to price the CDR with its own tariffs. A CDR
266    /// without a `tariffs` field contains no tariffs, and `price` fails on it with
267    /// [`price::Warning::NoValidTariff`].
268    ///
269    /// The tariffs are read as the version of the CDR that contains them. `tariffs` returns the
270    /// faults in their values as [`tariff::Warning`]s, located by their paths in the CDR. The
271    /// faults in their structure are among the [`schema::Warning`]s that [`check`] returns for
272    /// the CDR.
273    ///
274    /// `tariffs` fails on the first tariff it can't build, for the same reasons
275    /// [`tariff::build`] fails. It also fails with [`tariff::Warning::Rejected`] when the
276    /// `tariffs` field or one of its entries has the wrong JSON type. The
277    /// [`Failure`](warning::Failure) then holds the warnings of the tariffs built before it.
278    pub fn tariffs(&self) -> Verdict<Vec<tariff::Tariff<'buf>>, tariff::Warning> {
279        let mut warnings = warning::Gatherer::new();
280        let tariffs = self.checked.tariffs_to_v221(&mut warnings);
281        warnings.into_verdict(tariffs)
282    }
283
284    pub(crate) fn as_checked(&self) -> &Checked<'buf> {
285        &self.checked
286    }
287
288    pub(crate) fn as_v221(&self) -> &price::v221::Cdr {
289        &self.cdr
290    }
291}
292
293/// The faults [`build`] finds in a CDR's values, such as a malformed timestamp or a CDR
294/// without charging periods.
295///
296/// The faults in the CDR's structure are the [`schema::Warning`]s that [`check`] returns. A fault
297/// in the values of a tariff the CDR contains is a [`tariff::Warning`], which [`Cdr::tariffs`]
298/// returns.
299#[derive(Debug)]
300pub enum Warning {
301    /// Raised while reading a country code.
302    Country(country::Warning),
303
304    /// The `$.country_code` field names an alpha-3 code where OCPI defines it as alpha-2.
305    ///
306    /// The alpha-3 is read and converted to its alpha-2, so the CDR still prices. Only the CDR's
307    /// own `$.country_code` raises this. A `location.country` is alpha-3 by definition and reports
308    /// `timezone::Warning::LocationCountryShouldBeAlpha3` instead.
309    CountryShouldBeAlpha2,
310
311    /// Raised while reading a currency code.
312    Currency(currency::Warning),
313
314    /// Raised while reading a timestamp.
315    DateTime(datetime::Warning),
316
317    /// Raised while decoding a JSON string's escape sequences.
318    Decode(json::decode::Warning),
319
320    /// Raised while reading a duration.
321    Duration(duration::Warning),
322
323    /// Raised while reading a price.
324    Money(money::Warning),
325
326    /// The CDR has no charging periods.
327    NoPeriods,
328
329    /// Raised while reading a number.
330    Number(number::Warning),
331
332    /// The `start_date_time` of at least one of the `charging_periods` is outside of the
333    /// CDR's `start_date_time`-`end_date_time` range.
334    PeriodsOutsideStartEndDateTime {
335        /// The session's own start and end, taken from the CDR.
336        cdr_range: Range<Timestamp>,
337        /// The range the charging periods actually span.
338        period_range: PeriodRange,
339    },
340
341    /// Raised while reading a string.
342    String(string::Warning),
343
344    /// A required field of a CDR object was missing or invalid, so the object couldn't be read.
345    /// The schema warnings locate the cause (see [`warning::Rejected`]).
346    Rejected,
347}
348
349/// The range of time the CDR periods span.
350#[derive(Debug)]
351pub enum PeriodRange {
352    /// There are many periods in the CDR and so the range is from the `start_date_time` of the first to
353    /// the `start_date_time` of the last.
354    Many(Range<Timestamp>),
355
356    /// There is one period in the CDR and so one `start_date_time`.
357    Single(Timestamp),
358}
359
360impl fmt::Display for PeriodRange {
361    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362        match self {
363            PeriodRange::Many(Range { start, end }) => write!(f, "[start: {start}, end: {end}]"),
364            PeriodRange::Single(date_time) => write!(f, "{date_time}"),
365        }
366    }
367}
368
369impl fmt::Display for Warning {
370    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371        match self {
372            Self::Country(warning) => write!(f, "{warning}"),
373            Self::CountryShouldBeAlpha2 => {
374                f.write_str("The `$.country_code` field should be an alpha-2 country code.")
375            }
376            Self::Currency(warning) => write!(f, "{warning}"),
377            Self::DateTime(warning) => write!(f, "{warning}"),
378            Self::Decode(warning) => write!(f, "{warning}"),
379            Self::Duration(warning) => write!(f, "{warning}"),
380            Self::Money(warning) => write!(f, "{warning}"),
381            Self::NoPeriods => f.write_str("The CDR has no charging periods"),
382            Self::Number(warning) => write!(f, "{warning}"),
383            Self::PeriodsOutsideStartEndDateTime {
384                cdr_range: Range { start, end },
385                period_range,
386            } => {
387                write!(
388                    f,
389                    "The CDR's charging period time range is not contained within the `start_date_time` \
390                    and `end_date_time`; cdr: [start: {start}, end: {end}], period: {period_range}",
391                )
392            }
393            Self::String(warning) => write!(f, "{warning}"),
394            Self::Rejected => f.write_str(
395                "The schema IR for a CDR object was rejected; see the schema validation warnings.",
396            ),
397        }
398    }
399}
400
401impl crate::Warning for Warning {
402    fn id(&self) -> warning::Id {
403        match self {
404            Self::Country(warning) => warning.id(),
405            Self::CountryShouldBeAlpha2 => warning::Id::from_static("country_should_be_alpha_2"),
406            Self::Currency(warning) => warning.id(),
407            Self::DateTime(warning) => warning.id(),
408            Self::Decode(warning) => warning.id(),
409            Self::Duration(warning) => warning.id(),
410            Self::Money(warning) => warning.id(),
411            Self::NoPeriods => warning::Id::from_static("no_periods"),
412            Self::Number(warning) => warning.id(),
413            Self::PeriodsOutsideStartEndDateTime {
414                cdr_range: _,
415                period_range: _,
416            } => warning::Id::from_static("periods_outside_start_end_date_time"),
417            Self::String(warning) => warning.id(),
418            Self::Rejected => warning::Id::from_static("rejected"),
419        }
420    }
421
422    fn is_rejected(&self) -> bool {
423        matches!(self, Self::Rejected)
424    }
425}
426
427impl From<warning::Rejected> for Warning {
428    fn from(_: warning::Rejected) -> Self {
429        Self::Rejected
430    }
431}
432
433from_warning_all!(
434    country::Warning => Warning::Country,
435    currency::Warning => Warning::Currency,
436    datetime::Warning => Warning::DateTime,
437    duration::Warning => Warning::Duration,
438    json::decode::Warning => Warning::Decode,
439    money::Warning => Warning::Money,
440    number::Warning => Warning::Number,
441    string::Warning => Warning::String
442);
443
444/// A CDR document checked against the OCPI schema, as [`check`] returns it.
445#[derive(Clone)]
446pub struct Checked<'buf> {
447    /// The parsed JSON.
448    doc: json::Document<'buf>,
449
450    /// The `Version` of the tariff, determined during parsing.
451    version: Version<'buf>,
452}
453
454impl fmt::Debug for Checked<'_> {
455    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
456        if f.alternate() {
457            match &self.version {
458                Version::V211(cdr) => fmt::Debug::fmt(&cdr, f),
459                Version::V221(cdr) => fmt::Debug::fmt(&cdr, f),
460            }
461        } else {
462            match &self.version {
463                Version::V211(_) => f.write_str("V211"),
464                Version::V221(_) => f.write_str("V221"),
465            }
466        }
467    }
468}
469
470impl version::Versioned for Checked<'_> {
471    fn version(&self) -> crate::Version {
472        match self.version {
473            Version::V211(_) => crate::Version::V211,
474            Version::V221(_) => crate::Version::V221,
475        }
476    }
477}
478
479impl<'buf> Checked<'buf> {
480    /// Lower the schema IR into the "normalized" `v221` CDR,
481    /// gathering its warnings into `warnings`.
482    ///
483    /// A `v211` CDR is parsed as `v211` and then converted, because the two versions differ
484    /// in more than field names.
485    ///
486    /// The two whole-CDR checks live here rather than in the `LowerSchema` impls, because only
487    /// this layer has an element to anchor their warnings to: the CDR itself. A CDR with no
488    /// charging periods is rejected, because there is nothing to price. The schema walk's
489    /// `Cardinality` warning locates the empty array itself. A CDR whose charging periods start
490    /// outside its `start_date_time` and `end_date_time` raises `PeriodsOutsideStartEndDateTime`.
491    pub(crate) fn lower_to_v221(
492        &self,
493        warnings: &mut dyn warning::Gather<Warning>,
494    ) -> Result<price::v221::Cdr, warning::Error<Warning>> {
495        let cdr = match &self.version {
496            Version::V211(cdr) => {
497                let cdr = price::v211::Cdr::from_schema(cdr, warnings)?;
498
499                price::v221::Cdr::from(cdr)
500            }
501            Version::V221(cdr) => price::v221::Cdr::from_schema(cdr, warnings)?,
502        };
503
504        if cdr.charging_periods.is_empty() {
505            return Err(warning::Error::new(self.as_element(), Warning::NoPeriods));
506        }
507
508        let cdr_range = cdr.start_date_time..cdr.end_date_time;
509
510        // The periods are sorted by the lowering above, so the first and last periods bound the range.
511        let period_range = match cdr.charging_periods.as_slice() {
512            [] => None,
513            [period] => Some(PeriodRange::Single(period.start_date_time)),
514            [earliest, .., latest] => Some(PeriodRange::Many(
515                earliest.start_date_time..latest.start_date_time,
516            )),
517        };
518
519        let outside = match &period_range {
520            None => false,
521            Some(PeriodRange::Single(start)) => !cdr_range.contains(start),
522            Some(PeriodRange::Many(range)) => {
523                !(cdr_range.contains(&range.start) && cdr_range.contains(&range.end))
524            }
525        };
526
527        if let (true, Some(period_range)) = (outside, period_range) {
528            warnings.insert(
529                self.as_element(),
530                Warning::PeriodsOutsideStartEndDateTime {
531                    cdr_range,
532                    period_range,
533                },
534            );
535        }
536
537        Ok(cdr)
538    }
539
540    /// Build the tariffs the CDR contains, stopping at the first that fails.
541    ///
542    /// Every tariff's warnings go into the one set `warnings`. The tariffs are elements of the
543    /// CDR's document, so the path of each warning says which tariff raised it.
544    pub(crate) fn tariffs_to_v221(
545        &self,
546        warnings: &mut dyn warning::Gather<tariff::Warning>,
547    ) -> Result<Vec<tariff::Tariff<'buf>>, warning::Error<tariff::Warning>> {
548        let mut built = Vec::new();
549
550        // Each built tariff holds the JSON element of its entry in the `tariffs` array, which
551        // this function looks up by the entry's index. Keeping the element in the IR with
552        // `ir_object!(@keep_element ...)` would copy every tariff's whole JSON subtree on every
553        // check, including a standalone tariff's, which never reads it.
554        match &self.version {
555            Version::V211(cdr) => {
556                let Some(tariffs) = warnings.ok_or_reject(&cdr.tariffs)? else {
557                    return Ok(built);
558                };
559                let items = tariffs.element().value().as_array().unwrap_or(&[]);
560                for (index, tariff) in tariffs.into_iter().enumerate() {
561                    let tariff = warnings.ok_or_reject(tariff)?;
562                    let lowered = tariff::v211::Tariff::from_schema(tariff, warnings)?;
563                    let lowered = tariff::v221::Tariff::from(lowered);
564                    let element = items.get(index).unwrap_or(tariffs.element());
565                    let tariff = with_element(lowered, element)?;
566                    built.push(tariff);
567                }
568            }
569            Version::V221(cdr) => {
570                let Some(tariffs) = warnings.ok_or_reject(&cdr.tariffs)? else {
571                    return Ok(built);
572                };
573                let items = tariffs.element().value().as_array().unwrap_or(&[]);
574                for (index, tariff) in tariffs.into_iter().enumerate() {
575                    let tariff = warnings.ok_or_reject(tariff)?;
576                    let lowered = tariff::v221::Tariff::from_schema(tariff, warnings)?;
577                    let element = items.get(index).unwrap_or(tariffs.element());
578                    let tariff = with_element(lowered, element)?;
579                    built.push(tariff);
580                }
581            }
582        }
583
584        Ok(built)
585    }
586
587    /// Borrow the schema IR this CDR was built into.
588    ///
589    /// A feature that needs a field the schema models reads it from here rather than
590    /// walking the JSON, so the version differences stay in one match.
591    pub(crate) fn schema(&self) -> &Version<'buf> {
592        &self.version
593    }
594
595    /// Return the inner [`json::Document`] and discard the version info.
596    pub fn into_doc(self) -> json::Document<'buf> {
597        self.doc
598    }
599
600    /// Return the inner [`json::Document`] and discard the version info.
601    pub(crate) fn as_element(&self) -> &json::Element<'buf> {
602        self.doc.root()
603    }
604
605    /// Return the inner [`json::Document`] and discard the version info.
606    pub fn as_doc(&self) -> &json::Document<'buf> {
607        &self.doc
608    }
609
610    /// Return the inner JSON `str` and discard the version info.
611    pub fn as_json_str(&self) -> &'buf str {
612        self.doc.source()
613    }
614}
615
616#[expect(
617    clippy::large_enum_variant,
618    reason = "the v2.1.1 and v2.2.1 CDR IRs differ in size; this short-lived versioned \
619              value is not worth boxing"
620)]
621#[derive(Clone)]
622pub(crate) enum Version<'buf> {
623    V211(schema::v211::Cdr<'buf>),
624    V221(schema::v221::Cdr<'buf>),
625}
626
627/// A `json::Document` that has been processed by [`infer_version`] and has been identified
628/// as being a concrete [`Version`](crate::Version).
629pub struct VersionedJson<'buf> {
630    /// The parsed JSON.
631    doc: json::Document<'buf>,
632
633    /// The `Version` of the CDR, determined during parsing.
634    version: crate::Version,
635}
636
637impl fmt::Debug for VersionedJson<'_> {
638    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
639        if f.alternate() {
640            fmt::Debug::fmt(&self.doc, f)
641        } else {
642            match self.version {
643                crate::Version::V211 => f.write_str("V211"),
644                crate::Version::V221 => f.write_str("V221"),
645            }
646        }
647    }
648}
649
650impl version::Versioned for VersionedJson<'_> {
651    fn version(&self) -> crate::Version {
652        self.version
653    }
654}
655
656impl<'buf> VersionedJson<'buf> {
657    /// Create a new `Versioned` object.
658    pub(crate) fn new(element: json::Document<'buf>, version: crate::Version) -> Self {
659        Self {
660            doc: element,
661            version,
662        }
663    }
664
665    /// Return the inner [`json::Document`] and discard the version info.
666    pub fn into_doc(self) -> json::Document<'buf> {
667        self.doc
668    }
669
670    /// Return a reference to the inner [`json::Document`].
671    pub fn as_doc(&self) -> &json::Document<'buf> {
672        &self.doc
673    }
674
675    /// Return the inner JSON `str` and discard the version info.
676    pub fn as_json_str(&self) -> &'buf str {
677        self.doc.source()
678    }
679}
680
681/// A `json::Document` that has been processed by [`infer_version`] and has been identified
682/// as being a concrete [`Version`](crate::Version).
683#[derive(Debug)]
684pub struct Unversioned<'buf> {
685    /// The root `Element` of the parsed source.
686    doc: json::Document<'buf>,
687}
688
689impl<'buf> Unversioned<'buf> {
690    /// Create an unversioned [`json::Element`].
691    pub(crate) fn new(doc: json::Document<'buf>) -> Self {
692        Self { doc }
693    }
694
695    /// Return the inner [`json::Document`] and discard the version info.
696    pub fn into_doc(self) -> json::Document<'buf> {
697        self.doc
698    }
699}
700
701impl<'buf> version::Unversioned for Unversioned<'buf> {
702    type Versioned = VersionedJson<'buf>;
703
704    fn force_into_versioned(self, version: crate::Version) -> VersionedJson<'buf> {
705        let Self { doc } = self;
706        VersionedJson { doc, version }
707    }
708}
709
710/// Pair a tariff the CDR contains with its element, failing on a tariff with no elements.
711///
712/// A tariff with no elements prices every session at zero, so no feature can use it.
713/// `tariff::Checked::lower_to_v221` applies the same rule to a tariff of its own document. The
714/// schema walk's `Cardinality` warning locates the empty `elements` array.
715fn with_element<'buf>(
716    tariff: tariff::v221::Tariff<'buf>,
717    element: &json::Element<'buf>,
718) -> Result<tariff::Tariff<'buf>, warning::Error<tariff::Warning>> {
719    if tariff.elements.is_empty() {
720        return Err(warning::Error::new(element, tariff::Warning::NoElements));
721    }
722
723    Ok(tariff::Tariff::new(tariff, element.clone()))
724}