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
//! Parse a tariff.

#[cfg(test)]
pub(crate) mod test;

#[cfg(test)]
mod test_build;

#[cfg(test)]
mod test_real_world;

pub(crate) mod v211;
pub(crate) mod v221;
pub(crate) mod v2x;

use std::{borrow::Cow, fmt};

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

#[derive(Debug)]
/// The warnings that happen when reading a tariff.
pub enum Warning {
    /// Raised while reading the tariff's `country_code`.
    Country(country::Warning),
    /// Raised while reading the tariff's 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),

    /// A field in the tariff doesn't have the expected value.
    FieldInvalidValue {
        /// The value encountered.
        value: String,

        /// A message about what values are expected for this field.
        message: Cow<'static, str>,
    },

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

    /// The tariff has no `Element`s.
    NoElements,

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

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

    /// Raised when [`build`] rejects a tariff object because a field the object must have is
    /// missing, is `null` or has a value [`check`] can't read. The warning sits at the
    /// field, or at the object when the field is missing. A [`schema::Warning`] that
    /// [`check`] returns says what is wrong with the field (see [`warning::Rejected`]).
    Rejected,
}

impl Warning {
    /// Create a new `Warning::FieldInvalidValue` where the field is built from the given `json::Element`.
    fn field_invalid_value(
        value: impl Into<String>,
        message: impl Into<Cow<'static, str>>,
    ) -> Self {
        Warning::FieldInvalidValue {
            value: value.into(),
            message: message.into(),
        }
    }
}

impl fmt::Display for Warning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::String(warning_kind) => write!(f, "{warning_kind}"),
            Self::Country(warning_kind) => write!(f, "{warning_kind}"),
            Self::Currency(warning_kind) => write!(f, "{warning_kind}"),
            Self::DateTime(warning_kind) => write!(f, "{warning_kind}"),
            Self::Decode(warning_kind) => write!(f, "{warning_kind}"),
            Self::Duration(warning_kind) => write!(f, "{warning_kind}"),
            Self::FieldInvalidValue { value, message } => {
                write!(f, "Field has invalid value `{value}`: {message}")
            }
            Self::Money(warning_kind) => write!(f, "{warning_kind}"),
            Self::NoElements => f.write_str("The tariff has no `elements`"),
            Self::Number(warning_kind) => write!(f, "{warning_kind}"),
            Self::Rejected => f.write_str(
                "The schema IR for a tariff object was rejected; see the schema \
                 validation warnings.",
            ),
        }
    }
}

impl crate::Warning for Warning {
    fn id(&self) -> warning::Id {
        match self {
            Self::String(warning) => warning.id(),
            Self::Country(warning) => warning.id(),
            Self::Currency(warning) => warning.id(),
            Self::DateTime(warning) => warning.id(),
            Self::Decode(warning) => warning.id(),
            Self::Duration(warning) => warning.id(),
            Self::FieldInvalidValue { value, message: _ } => {
                warning::Id::from_string(format!("field_invalid_value({value})"))
            }
            Self::Money(warning) => warning.id(),
            Self::NoElements => warning::Id::from_static("no_elements"),
            Self::Number(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
);

/// The five character ID of the CPO.
///
/// The first two characters are the ISO-3166 alpha-2 country code of the CPO.
/// The remaining three characters are the ISO-15118 ID of the CPO.
#[derive(Clone, Debug)]
pub(crate) struct CpoId<'buf> {
    /// The ISO-3166 alpha-2 country code.
    pub country_code: country::Code,

    /// The ISO-15118 ID.
    pub id: string::AsciiExactLen<'buf, 3>,
}

/// Infer which OCPI [`Version`](crate::Version) a tariff [`json::Document`] is, without checking
/// the document against the schema.
///
/// Use this when the version of the tariff 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 tariff's
/// fields settle which version it is, and [`Uncertain`](version::Guess::Uncertain) otherwise.
///
/// To check the tariff against the OCPI schema, pass the guessed document and version to [`check`].
///
/// # Examples
///
/// ```rust
/// use ocpi_tariffs::{json, tariff, Version, version::Versioned as _};
/// #
/// # const TARIFF_JSON: &str = include_str!("tariff.json");
///
/// let doc = json::parse_object(TARIFF_JSON)?;
/// let tariff = tariff::infer_version(doc).certain_or(Version::V221);
/// let version = tariff.version();
/// let (tariff, warnings) = tariff::check(tariff.into_doc(), version).into_parts();
///
/// # Ok::<(), json::ParseError>(())
/// ```
pub fn infer_version(json: json::Document<'_>) -> VersionGuess<'_> {
    version::tariff_version(json)
}

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

/// Check a [`json::Document`] against the OCPI tariff 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 tariff into the [`Tariff`] that
/// [`explain`](explain()) and [`cdr::generate_from_tariff`](crate::cdr::generate_from_tariff)
/// take. The features [`lint`](lint()) and [`fix`](fix()) take the checked tariff itself.
///
/// # Examples
///
/// ```rust
/// # use ocpi_tariffs::{json, tariff, Version};
/// #
/// # const TARIFF_JSON: &str = include_str!("tariff.json");
///
/// let doc = json::parse_object(TARIFF_JSON)?;
/// let (tariff, warnings) = tariff::check(doc, Version::V211).into_parts();
///
/// if !warnings.is_empty() {
///     eprintln!("The tariff has `{}` schema warnings.", warnings.len_warnings());
/// }
///
/// # Ok::<(), json::ParseError>(())
/// ```
///
/// [^spec-v211]: <https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_tariffs.md>
/// [^spec-v221]: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.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_tariff(&json, &mut warnings)),
        crate::Version::V211 => Version::V211(schema::v211::build_tariff(&json, &mut warnings)),
    };
    let checked = Checked { doc: json, version };
    Caveat::new(checked, warnings.into_set())
}

/// Build a [`Tariff`] from a checked tariff, the [`Checked`] that [`check`]
/// returns[^spec-v211][^spec-v221].
///
/// [`json::parse_object`] parses a tariff document and [`check`] checks it against the
/// OCPI tariff schema. The features [`lint`](lint()) and [`fix`](fix()) take the checked
/// tariff. The features [`explain`](explain()) and
/// [`cdr::generate_from_tariff`](crate::cdr::generate_from_tariff) take the [`Tariff`] that
/// `build` makes from it.
///
/// The check and the build judge different things:
///
/// - The check judges the document's shape: which fields it has, their JSON types and the form
///   of their values, such as a string's length or a number's precision. It reports each fault
///   as a [`schema::Warning`], and returns a [`Checked`] however many faults it found.
/// - `build` reads each field's value into the type a [`Tariff`] holds, such as a timestamp, a
///   price or a country code, and judges the tariff as a whole. It reports each fault as a
///   [`Warning`], and fails if it can't make a [`Tariff`].
///
/// `build` fails if a field the tariff must have is missing or can't be read, or if the tariff
/// has no elements. The [`Failure`](warning::Failure) then holds every warning `build` raises
/// before it fails. A required field that is missing, is `null` or has a value [`check`]
/// can't read makes `build` fail with [`Warning::Rejected`]. The error sits at the field, or
/// at the object that contains it when the field is missing. A [`schema::Warning`] that
/// [`check`] returns says what is wrong with the field.
///
/// # Examples
///
/// ```rust
/// # use ocpi_tariffs::{json, tariff, Language, Version};
/// #
/// # const TARIFF_JSON: &str = include_str!("tariff.json");
///
/// let doc = json::parse_object(TARIFF_JSON)?;
/// let (tariff, schema_warnings) = tariff::check(doc, Version::V211).into_parts();
///
/// if !schema_warnings.is_empty() {
///     eprintln!("The tariff has `{}` schema warnings.", schema_warnings.len_warnings());
/// }
///
/// let Ok(tariff) = tariff::build(tariff) else {
///     return Err("The tariff could not be read well enough to use.".into());
/// };
/// let (tariff, warnings) = tariff.into_parts();
///
/// if !warnings.is_empty() {
///     eprintln!("The tariff has `{}` warnings.", warnings.len_warnings());
/// }
///
/// println!("{}", tariff::explain(&tariff, Language::EnUS));
///
/// # Ok::<(), Box<dyn std::error::Error + Send + Sync + 'static>>(())
/// ```
///
/// [^spec-v211]: <https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_tariffs.md>
/// [^spec-v221]: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc>
pub fn build(tariff: Checked<'_>) -> Verdict<Tariff<'_>, Warning> {
    let mut warnings = warning::Gatherer::new();
    let v221 = tariff.lower_to_v221(&mut warnings);
    let element = tariff.into_doc().into_root();
    let tariff = v221.map(|tariff| Tariff { tariff, element });
    warnings.into_verdict(tariff)
}

/// A tariff that [`build`] makes from a checked tariff. A feature such as
/// [`explain`](explain()) or [`cdr::generate_from_tariff`](crate::cdr::generate_from_tariff)
/// takes it.
///
/// A `v2.1.1` tariff is held as its `v2.2.1` equivalent.
pub struct Tariff<'buf> {
    tariff: v221::Tariff<'buf>,

    /// The JSON element of the tariff,
    /// which a feature uses to report a warning about the tariff as a whole.
    element: json::Element<'buf>,
}

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

impl<'buf> Tariff<'buf> {
    pub(crate) fn new(tariff: v221::Tariff<'buf>, element: json::Element<'buf>) -> Self {
        Self { tariff, element }
    }

    pub(crate) fn as_v221(&self) -> &v221::Tariff<'buf> {
        &self.tariff
    }

    pub(crate) fn as_element(&self) -> &json::Element<'buf> {
        &self.element
    }
}

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

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

/// A tariff 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(tariff) => fmt::Debug::fmt(&tariff, f),
                Version::V221(tariff) => fmt::Debug::fmt(&tariff, 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` tariff,
    /// gathering its warnings into `warnings`.
    ///
    /// A `v211` tariff is parsed as `v211` and then converted, because the two versions
    /// differ in more than field names.
    ///
    /// A tariff with no elements is rejected, because it prices every session at zero, so no
    /// feature can use it. The check lives here rather than in the `LowerSchema` impls, because
    /// only this layer has an element to anchor the error to: the tariff itself. The located
    /// cause is the schema walk's `Cardinality` warning on the `elements` array.
    pub(crate) fn lower_to_v221(
        &self,
        warnings: &mut dyn warning::Gather<Warning>,
    ) -> Result<v221::Tariff<'buf>, warning::Error<Warning>> {
        let tariff = match &self.version {
            Version::V211(tariff) => {
                let tariff = v211::Tariff::from_schema(tariff, warnings)?;

                v221::Tariff::from(tariff)
            }
            Version::V221(tariff) => v221::Tariff::from_schema(tariff, warnings)?,
        };

        if tariff.elements.is_empty() {
            return Err(warning::Error::new(self.as_element(), Warning::NoElements));
        }

        Ok(tariff)
    }

    /// Borrow the schema intermediate representation this tariff was built into.
    ///
    /// The linter reads this to inspect the document field by field without re-walking the
    /// JSON; see [`lint::tariff`](mod@crate::lint::tariff).
    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::Element`] 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 tariff IRs differ in size; this short-lived versioned \
              value is not worth boxing"
)]
#[derive(Clone)]
pub(crate) enum Version<'buf> {
    V211(schema::v211::Tariff<'buf>),
    V221(schema::v221::Tariff<'buf>),
}

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(doc: json::Document<'buf>, version: crate::Version) -> Self {
        Self { doc, 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 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 was determined to not be one of the supported [`Version`](crate::Version)s.
#[derive(Debug)]
pub struct Unversioned<'buf> {
    doc: json::Document<'buf>,
}

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

    /// 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 }
    }
}

/// Lint the given tariff and return a [`lint::tariff::Report`] of any `Warning`s found.
///
/// A caller reaches `lint` by passing the tariff through [`json::parse_object`] and [`check`].
/// `lint` takes the checked tariff rather than a built one, so it can report on a tariff that
/// [`build`] would refuse. It reports only what linting adds, because [`check`] returns the
/// schema warnings.
///
/// # Examples
///
/// ```rust
/// # use ocpi_tariffs::{json, tariff, warning, version::Versioned as _};
/// #
/// # const TARIFF_JSON: &str = include_str!("tariff.json");
///
/// let doc = json::parse_object(TARIFF_JSON)?;
/// let tariff::VersionGuess::Certain(tariff) = tariff::infer_version(doc) else {
///     return Err("Unable to guess the version of given tariff JSON.".into());
/// };
/// let version = tariff.version();
/// let (tariff, schema_warnings) = tariff::check(tariff.into_doc(), version).into_parts();
///
/// let report = tariff::lint(&tariff);
///
/// eprintln!("`{}` schema warnings found", schema_warnings.len_warnings());
/// eprintln!("`{}` lint warnings found", report.warnings.len_warnings());
///
/// for group in report.warnings {
///     let (element, warnings) = group.to_parts();
///     eprintln!(
///         "Warnings reported for `json::Element` at path: `{}`",
///         element.path
///     );
///
///     for warning in warnings {
///         eprintln!("  * {warning}");
///     }
///
///     eprintln!();
/// }
///
/// # Ok::<(), Box<dyn std::error::Error + Send + Sync + 'static>>(())
/// ```
pub fn lint(tariff: &Checked<'_>) -> lint::tariff::Report {
    lint::tariff(tariff)
}

/// Fix the warnings raised from linting the given `tariff` and return the fixed JSON.
///
/// A caller reaches `fix` by passing the tariff through [`json::parse_object`] and [`check`],
/// as for [`lint`](lint()).
///
/// Both the schema warnings and the lint warnings are fixed, and the document is walked again
/// after each round of edits, because one fix can raise more warnings. The fixing stops when a
/// walk doesn't propose any edit that `options` allows. See [`lint::fix::Outcome`].
///
/// `options` says which fixes to apply. By default the fixing leaves out every edit that changes
/// what the tariff means under OCPI, and [`lint::fix::Fixed::changes_held_back`] counts the
/// edits it left out.
///
/// Whatever the options, the fixing refuses a rename whose new name would clash with the
/// name of another field in the same object, and [`lint::fix::Fixed::refused`] lists it.
///
/// Nothing is written: the fixed JSON is returned as [`lint::fix::Fixed::source`], and a tariff
/// with nothing to fix returns its own source unchanged.
///
/// # Examples
///
/// ```rust
/// # use ocpi_tariffs::{json, lint, tariff, Version};
/// #
/// # const TARIFF_JSON: &str = include_str!("tariff.json");
///
/// let doc = json::parse_object(TARIFF_JSON)?;
/// let tariff = tariff::check(doc, Version::V221).ignore_warnings();
///
/// let options =
///     lint::fix::Options::default().unexpected_fields(lint::fix::UnexpectedFields::Remove);
/// let fixed = tariff::fix(&tariff, options)?;
///
/// eprintln!(
///     "Applied {} edit(s) over {} pass(es), held back {}",
///     fixed.edits, fixed.passes, fixed.changes_held_back
/// );
///
/// println!("{}", fixed.source);
///
/// # Ok::<(), Box<dyn std::error::Error + Send + Sync + 'static>>(())
/// ```
pub fn fix(
    tariff: &Checked<'_>,
    options: lint::fix::Options,
) -> Result<lint::fix::Fixed, crate::fix::Error> {
    lint::fix::tariff(tariff, options)
}

/// Explain the given tariff in the given language, returning the explanation as Markdown.
///
/// A caller reaches `explain` by passing the tariff through [`json::parse_object`], [`check`]
/// and [`build`].
///
/// A `v2.1.1` tariff is explained as its `v2.2.1` equivalent, because [`build`] converts a
/// `v2.1.1` tariff to `v2.2.1`.
///
/// `explain` describes the tariff as given. It finds no fault in the tariff and proposes no edit to
/// it, so an element whose restrictions exclude every session is described like any other.
/// Reporting that such an element is pointless belongs to [`tariff::lint`](lint()), and repairing
/// the tariff belongs to [`tariff::fix`](fix()). The [`explain`](mod@crate::explain) module
/// documentation lists what the explanation does leave out.
///
/// # Examples
///
/// ```rust
/// # use ocpi_tariffs::{json, tariff, Language, Version};
/// #
/// # const TARIFF_JSON: &str = include_str!("tariff.json");
///
/// let doc = json::parse_object(TARIFF_JSON)?;
/// let tariff = tariff::check(doc, Version::V211).ignore_warnings();
/// let Ok(tariff) = tariff::build(tariff) else {
///     return Err("The tariff could not be read well enough to explain.".into());
/// };
///
/// println!("{}", tariff::explain(&tariff.ignore_warnings(), Language::EnUS));
///
/// # Ok::<(), Box<dyn std::error::Error + Send + Sync + 'static>>(())
/// ```
pub fn explain(tariff: &Tariff<'_>, language: crate::Language) -> String {
    explain::tariff(tariff.as_v221(), language)
}