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

#[cfg(test)]
mod test_every_field_set;

#[cfg(test)]
mod test_tariffs;

use std::fmt;

use chrono_tz::Tz;

use crate::{
    generate, guess, json, price, schema, tariff,
    warning::{self, Caveat, GatherWarnings as _, IntoCaveat as _},
    FromSchema as _, Verdict,
};

/// Infer which OCPI [`Version`] a CDR [`json::Document`] is, without validating it.
///
/// Use this when the version of the CDR is not known up front. The [`json::Document`] is obtained
/// by calling [`json::parse_object`]. The returned [`guess::CdrVersion`] is either
/// [`Certain`](guess::Version::Certain) or [`Uncertain`](guess::Version::Uncertain) about the version.
///
/// To check the CDR against the OCPI schema for a known [`Version`], use [`from_json`].
///
/// # Example
///
/// ```rust
/// # use ocpi_tariffs::{cdr, json, Version};
/// #
/// # 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);
///
/// # Ok::<(), json::ParseError>(())
/// ```
pub fn infer_version(json: json::Document<'_>) -> guess::CdrVersion<'_> {
    guess::cdr_version(json)
}

/// Validate a [`json::Document`] against the OCPI CDR schema for the given [`Version`][^spec-v211][^spec-v221].
///
/// The [`json::Document`] is obtained by calling [`json::parse_object`]. Any unexpected, missing,
/// or wrongly typed fields are reported as a [`warning::Set`](crate::warning::Set) of
/// [`schema::Warning`]s carried by the returned [`Caveat`].
///
/// # Example
///
/// ```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::from_json(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/release-2.1.1-bugfixes/mod_cdrs.md>.
/// [^spec-v221]: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc>.
pub fn from_json(
    json: json::Document<'_>,
    version: crate::Version,
) -> Caveat<Versioned<'_>, schema::Warning> {
    let (version, warnings) = match version {
        crate::Version::V221 => {
            let (cdr, warnings) = schema::v221::build_cdr(&json).into_parts();
            (Version::V221(cdr), warnings)
        }
        crate::Version::V211 => {
            let (cdr, warnings) = schema::v211::build_cdr(&json).into_parts();
            (Version::V211(cdr), warnings)
        }
    };
    let versioned = Versioned { doc: json, version };
    versioned.into_caveat(warnings)
}

/// Validate a [`VersionedJson`] against the OCPI CDR schema for its known [`Version`].
///
/// Use this when the [`Version`] has already been resolved - for example a
/// [`VersionedJson`] obtained from [`infer_version`] via [`certain_or`](guess::Version::certain_or).
pub fn from_versioned_json(json: VersionedJson<'_>) -> Caveat<Versioned<'_>, schema::Warning> {
    let VersionedJson { doc, version } = json;
    from_json(doc, version)
}

/// Generate a [`PartialCdr`](generate::PartialCdr) that can be priced by the given tariff.
///
/// The CDR is partial as not all required fields are set as the `cdr_from_tariff` function
/// does not know anything about the EVSE location or the token used to authenticate the chargesession.
///
/// * See: [OCPI spec 2.2.1: CDR](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc>)
pub fn generate_from_tariff(
    tariff: &tariff::Versioned<'_>,
    config: &generate::Config,
) -> Verdict<generate::Report, generate::Warning> {
    generate::cdr_from_tariff(tariff, config)
}

/// Price a single `CDR` and return a [`Report`](price::Report).
///
/// The `CDR` is checked for internal consistency before being priced. As pricing a `CDR` with
/// contradictory data will lead to a difficult to debug [`Report`](price::Report).
/// An [`Error`](price::Warning) is returned if the `CDR` is deemed to be internally inconsistent.
///
/// > **_Note_** Pricing the CDR does not require a spec compliant CDR or tariff.
/// > A best effort is made to parse the given CDR and tariff JSON.
///
/// 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 [`Report`](price::Report) also contains
/// a list of unknown fields to help spot misspelled fields.
///
/// The source of the tariffs can be controlled using the [`TariffSource`](price::TariffSource).
/// The timezone can be found or inferred using the [`timezone::find_or_infer`](crate::timezone::find_or_infer) function.
///
/// # Example
///
/// ```rust
/// # use ocpi_tariffs::{cdr, json, price, warning, Version};
/// #
/// # const CDR_JSON: &str = include_str!("cdr.json");
///
/// let doc = json::parse_object(CDR_JSON)?;
/// let (cdr, _warnings) = cdr::from_json(doc, Version::V211).into_parts();
///
/// let report = cdr::price(&cdr, price::TariffSource::UseCdr, chrono_tz::Tz::Europe__Amsterdam).unwrap();
/// 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: &Versioned<'_>,
    tariff_source: price::TariffSource<'_>,
    timezone: Tz,
) -> Verdict<price::Report, price::Warning> {
    price::cdr(cdr, tariff_source, timezone)
}

/// A `json::Element` that has been processed by either the [`infer_version`] or [`from_json`]
/// functions and has been identified as being a certain [`Version`].
#[derive(Clone)]
pub struct Versioned<'buf> {
    /// The parsed JSON.
    doc: json::Document<'buf>,

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

impl fmt::Debug for Versioned<'_> {
    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 crate::Versioned for Versioned<'_> {
    fn version(&self) -> crate::Version {
        match self.version {
            Version::V211(_) => crate::Version::V211,
            Version::V221(_) => crate::Version::V221,
        }
    }
}

impl<'buf> Versioned<'buf> {
    /// Lower the schema IR into the "normalized" `v221` CDR.
    ///
    /// 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 lowering: both compare fields
    /// against each other, and only this layer has an element to anchor a warning to. A CDR
    /// with no charging periods is rejected, because there is nothing to price; the empty
    /// array itself is located by the schema walk's `Cardinality` warning.
    pub(crate) fn to_v221(&self) -> Verdict<price::v221::Cdr, price::Warning> {
        let mut warnings = warning::Set::new();

        let cdr = match &self.version {
            Version::V211(cdr) => {
                let cdr = price::v211::Cdr::from_schema(cdr)?.gather_warnings_into(&mut warnings);

                price::v221::Cdr::from(cdr)
            }
            Version::V221(cdr) => {
                price::v221::Cdr::from_schema(cdr)?.gather_warnings_into(&mut warnings)
            }
        };

        if cdr.charging_periods.is_empty() {
            return warnings.bail(self.as_element(), price::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(price::PeriodRange::Single(period.start_date_time)),
            [earliest, .., latest] => Some(price::PeriodRange::Many(
                earliest.start_date_time..latest.start_date_time,
            )),
        };

        let outside = match &period_range {
            None => false,
            Some(price::PeriodRange::Single(start)) => !cdr_range.contains(start),
            Some(price::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(),
                price::Warning::PeriodsOutsideStartEndDateTime {
                    cdr_range,
                    period_range,
                },
            );
        }

        Ok(cdr.into_caveat(warnings))
    }

    /// Lower the tariffs embedded in the CDR into "normalized" `v221` tariffs.
    ///
    /// The embedded tariffs are read as the version of the CDR that carries them. A CDR
    /// without a `tariffs` field yields no tariffs; whether that can be priced is up to the
    /// caller.
    /// Each tariff keeps its own warnings, because they are reported per tariff in the
    /// pricing report.
    pub(crate) fn tariffs_to_v221(
        &self,
    ) -> Verdict<Vec<Caveat<tariff::v221::Tariff<'buf>, tariff::Warning>>, tariff::Warning> {
        let mut warnings = warning::Set::new();
        let mut lowered = Vec::new();

        match &self.version {
            Version::V211(cdr) => {
                let tariffs = warnings.ok_or_bail(&cdr.tariffs)?;
                for tariff in tariffs.iter().flatten() {
                    let tariff = warnings.ok_or_bail(tariff)?;
                    let tariff = tariff::v211::Tariff::from_schema(tariff)?;

                    lowered.push(tariff.map(tariff::v221::Tariff::from));
                }
            }
            Version::V221(cdr) => {
                let tariffs = warnings.ok_or_bail(&cdr.tariffs)?;
                for tariff in tariffs.iter().flatten() {
                    let tariff = warnings.ok_or_bail(tariff)?;

                    lowered.push(tariff::v221::Tariff::from_schema(tariff)?);
                }
            }
        }

        // A tariff with no elements prices every session at zero, so it is rejected rather
        // than used; see `tariff::Versioned::to_v221`. The schema walk's `Cardinality`
        // warning locates which of the embedded tariffs is empty.
        if lowered.iter().any(|tariff| tariff.elements.is_empty()) {
            return warnings.bail(self.as_element(), tariff::Warning::NoElements);
        }

        Ok(lowered.into_caveat(warnings))
    }

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

    /// 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`].
#[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::Element`] 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 fn as_element(&self) -> &json::Element<'buf> {
        self.doc.root()
    }
}

impl<'buf> crate::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 }
    }
}