Skip to main content

ocpi_tariffs/
lib.rs

1//! # OCPI Tariffs library
2//!
3//! Calculate the (sub)totals of a [charge session](https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc)
4//! using the [`cdr::price`] function and use the generated [`price::Report`] to review and compare the calculated
5//! totals versus the sources from the `CDR`.
6//!
7//! - Use the [`cdr::parse`] and [`tariff::parse`] function to parse and guess which OCPI version of a CDR or tariff you have.
8//! - Use the [`cdr::parse_with_version`] and [`tariff::parse_with_version`] functions to parse a CDR of tariff as the given version.
9//! - Use the [`tariff::lint`] to lint a tariff: flag common errors, bugs, dangerous constructs and stylistic flaws in the tariff.
10//!
11//! # Examples
12//!
13//! ## Price a CDR with embedded tariff
14//!
15//! If you have a CDR JSON with an embedded tariff you can price the CDR with the following code:
16//!
17//! ```rust
18//! # use ocpi_tariffs::{cdr, price, warning, Version};
19//! #
20//! # const CDR_JSON: &str = include_str!("../test_data/v211/real_world/time_and_parking_time/cdr.json");
21//!
22//! let report = cdr::parse_with_version(CDR_JSON, Version::V211)?;
23//! let cdr::ParseReport {
24//!     cdr,
25//!     unexpected_fields,
26//! } = report;
27//!
28//! # if !unexpected_fields.is_empty() {
29//! #     eprintln!("Strange... there are fields in the CDR that are not defined in the spec.");
30//! #
31//! #     for path in &unexpected_fields {
32//! #         eprintln!("{path}");
33//! #     }
34//! # }
35//!
36//! let report = cdr::price(&cdr, price::TariffSource::UseCdr, chrono_tz::Tz::Europe__Amsterdam).unwrap();
37//! let (report, warnings) = report.into_parts();
38//!
39//! if !warnings.is_empty() {
40//!     eprintln!("Pricing the CDR resulted in `{}` warnings", warnings.len_warnings());
41//!
42//!     for group in warnings {
43//!         let (element, warnings) = group.to_parts();
44//!         eprintln!("  {}", element.path());
45//!
46//!         for warning in warnings {
47//!             eprintln!("    - {warning}");
48//!         }
49//!     }
50//! }
51//!
52//! # Ok::<(), Box<dyn std::error::Error + Send + Sync + 'static>>(())
53//! ```
54//!
55//! ## Price a CDR using tariff in separate JSON file
56//!
57//! If you have a CDR JSON with a tariff in a separate JSON file you can price the CDR with the
58//! following code:
59//!
60//! ```rust
61//! # use ocpi_tariffs::{cdr, price, tariff, warning, Version};
62//! #
63//! # const CDR_JSON: &str = include_str!("../test_data/v211/real_world/time_and_parking_time_separate_tariff/cdr.json");
64//! # const TARIFF_JSON: &str = include_str!("../test_data/v211/real_world/time_and_parking_time_separate_tariff/tariff.json");
65//!
66//! let report = cdr::parse_with_version(CDR_JSON, Version::V211)?;
67//! let cdr::ParseReport {
68//!     cdr,
69//!     unexpected_fields,
70//! } = report;
71//!
72//! # if !unexpected_fields.is_empty() {
73//! #     eprintln!("Strange... there are fields in the CDR that are not defined in the spec.");
74//! #
75//! #     for path in &unexpected_fields {
76//! #         eprintln!("{path}");
77//! #     }
78//! # }
79//!
80//! let tariff::ParseReport {
81//!     tariff,
82//!     unexpected_fields,
83//! } = tariff::parse_with_version(TARIFF_JSON, Version::V211).unwrap();
84//! let report = cdr::price(&cdr, price::TariffSource::Override(vec![tariff]), chrono_tz::Tz::Europe__Amsterdam).unwrap();
85//! let (report, warnings) = report.into_parts();
86//!
87//! if !warnings.is_empty() {
88//!     eprintln!("Pricing the CDR resulted in `{}` warnings", warnings.len_warnings());
89//!
90//!     for group in warnings {
91//!         let (element, warnings) = group.to_parts();
92//!         eprintln!("  {}", element.path());
93//!
94//!         for warning in warnings {
95//!             eprintln!("    - {warning}");
96//!         }
97//!     }
98//! }
99//!
100//! # Ok::<(), Box<dyn std::error::Error + Send + Sync + 'static>>(())
101//! ```
102//!
103//! ## Lint a tariff
104//!
105//! ```rust
106//! # use ocpi_tariffs::{guess, tariff, warning};
107//! #
108//! # const TARIFF_JSON: &str = include_str!("../test_data/v211/real_world/time_and_parking_time_separate_tariff/tariff.json");
109//!
110//! let report = tariff::parse_and_report(TARIFF_JSON)?;
111//! let guess::Report {
112//!     unexpected_fields,
113//!     version,
114//! } = report;
115//!
116//! if !unexpected_fields.is_empty() {
117//!     eprintln!("Strange... there are fields in the tariff that are not defined in the spec.");
118//!
119//!     for path in &unexpected_fields {
120//!         eprintln!("  * {path}");
121//!     }
122//!
123//!     eprintln!();
124//! }
125//!
126//! let guess::Version::Certain(tariff) = version else {
127//!     return Err("Unable to guess the version of given CDR JSON.".into());
128//! };
129//!
130//! let report = tariff::lint(&tariff);
131//!
132//! eprintln!("`{}` lint warnings found", report.warnings.len_warnings());
133//!
134//! for group in report.warnings {
135//!     let (element, warnings) = group.to_parts();
136//!     eprintln!(
137//!         "Warnings reported for `json::Element` at path: `{}`",
138//!         element.path()
139//!     );
140//!
141//!     for warning in warnings {
142//!         eprintln!("  * {warning}");
143//!     }
144//!
145//!     eprintln!();
146//! }
147//!
148//! # Ok::<(), Box<dyn std::error::Error + Send + Sync + 'static>>(())
149//! ```
150
151#[cfg(test)]
152mod test;
153
154#[cfg(test)]
155mod test_reasonable_str;
156
157#[cfg(test)]
158mod test_rust_decimal_arbitrary_precision;
159
160pub mod cdr;
161pub mod country;
162pub mod currency;
163pub mod datetime;
164pub mod duration;
165mod energy;
166pub mod enumeration;
167pub mod generate;
168pub mod guess;
169pub mod json;
170pub mod lint;
171pub mod money;
172pub mod number;
173pub mod price;
174pub mod string;
175pub mod tariff;
176pub mod timezone;
177mod v211;
178mod v221;
179pub mod warning;
180pub mod weekday;
181
182use std::{collections::BTreeSet, fmt};
183
184use warning::IntoCaveat;
185use weekday::Weekday;
186
187#[doc(inline)]
188pub use duration::{ToDuration, ToHoursDecimal};
189
190#[doc(inline)]
191pub use energy::{Ampere, Kw, Kwh};
192
193#[doc(inline)]
194use enumeration::{Enum, IntoEnum};
195
196#[doc(inline)]
197pub use money::{Cost, Money, Price, Vat, VatApplicable};
198
199#[doc(inline)]
200pub use warning::{Caveat, Verdict, VerdictExt, Warning};
201
202/// Set of unexpected fields encountered while parsing a CDR or tariff.
203pub type UnexpectedFields = BTreeSet<String>;
204
205/// The Id for a tariff used in the pricing of a CDR.
206pub type TariffId = String;
207
208/// The OCPI versions supported by this crate
209#[derive(Clone, Copy, Debug, PartialEq)]
210pub enum Version {
211    V221,
212    V211,
213}
214
215impl Versioned for Version {
216    fn version(&self) -> Version {
217        *self
218    }
219}
220
221impl fmt::Display for Version {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        match self {
224            Version::V221 => f.write_str("v221"),
225            Version::V211 => f.write_str("v211"),
226        }
227    }
228}
229
230/// An object for a specific OCPI [`Version`].
231pub trait Versioned: fmt::Debug {
232    /// Return the OCPI `Version` of this object.
233    fn version(&self) -> Version;
234}
235
236/// An object with an uncertain [`Version`].
237pub trait Unversioned: fmt::Debug {
238    /// The concrete [`Versioned`] type.
239    type Versioned: Versioned;
240
241    /// Forced an [`Unversioned`] object to be the given [`Version`].
242    ///
243    /// This does not change the structure of the OCPI object.
244    /// It simply relabels the object as a different OCPI Version.
245    ///
246    /// Use this with care.
247    fn force_into_versioned(self, version: Version) -> Self::Versioned;
248}
249
250/// Errors that can happen if a JSON str is parsed.
251pub struct ParseError {
252    /// The type of object we were trying to deserialize.
253    object: ObjectType,
254
255    /// The error that occurred while deserializing.
256    kind: ParseErrorKind,
257}
258
259/// The kind of Error that occurred.
260#[derive(Debug)]
261pub enum ParseErrorKind {
262    /// Some Error types are erased to avoid leaking dependencies.
263    Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
264
265    /// The integrated JSON parser was unable to parse a JSON str.
266    Json(json::Error),
267
268    /// The OCPI object should be a JSON object.
269    ShouldBeAnObject,
270
271    /// The size of the input `str` exceeds the maximum deemed reasonable.
272    SizeExceedsMax,
273}
274
275impl fmt::Display for ParseErrorKind {
276    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277        match self {
278            Self::Internal(_) => f.write_str("internal"),
279            Self::Json(error) => write!(f, "{error}"),
280            Self::ShouldBeAnObject => f.write_str("The element should be an object."),
281            Self::SizeExceedsMax => write!(
282                f,
283                "The input `&str` exceeds the max reasonable bytes `{}`.",
284                ReasonableStr::MAX_STR_INPUT_LEN
285            ),
286        }
287    }
288}
289
290impl Warning for ParseErrorKind {
291    fn id(&self) -> warning::Id {
292        match self {
293            Self::Internal(_) => warning::Id::from_static("internal"),
294            Self::Json(error) => error.id(),
295            Self::ShouldBeAnObject => warning::Id::from_static("should_be_an_object"),
296            Self::SizeExceedsMax => warning::Id::from_static("size_exceeds_max"),
297        }
298    }
299}
300
301impl std::error::Error for ParseError {
302    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
303        match &self.kind {
304            ParseErrorKind::Internal(err) => Some(&**err),
305            ParseErrorKind::Json(err) => Some(err),
306            ParseErrorKind::ShouldBeAnObject | ParseErrorKind::SizeExceedsMax => None,
307        }
308    }
309}
310
311impl fmt::Debug for ParseError {
312    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313        fmt::Display::fmt(self, f)
314    }
315}
316
317impl fmt::Display for ParseError {
318    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319        write!(f, "while deserializing {:?}: ", self.object)?;
320
321        match &self.kind {
322            ParseErrorKind::Internal(err) => write!(f, "{err}"),
323            ParseErrorKind::Json(err) => write!(f, "{err}"),
324            ParseErrorKind::ShouldBeAnObject => f.write_str("The root element should be an object"),
325            ParseErrorKind::SizeExceedsMax => write!(
326                f,
327                "The input `&str` exceeds the max reasonable bytes `{}`.",
328                ReasonableStr::MAX_STR_INPUT_LEN
329            ),
330        }
331    }
332}
333
334impl ParseError {
335    /// Create a [`ParseError`] from a generic std Error for a CDR object.
336    fn from_cdr_err(err: json::Error) -> Self {
337        Self {
338            object: ObjectType::Cdr,
339            kind: ParseErrorKind::Json(err),
340        }
341    }
342
343    /// Create a [`ParseError`] from a generic std Error for a tariff object.
344    fn from_tariff_err(err: json::Error) -> Self {
345        Self {
346            object: ObjectType::Tariff,
347            kind: ParseErrorKind::Json(err),
348        }
349    }
350
351    fn cdr_should_be_object() -> ParseError {
352        Self {
353            object: ObjectType::Cdr,
354            kind: ParseErrorKind::ShouldBeAnObject,
355        }
356    }
357
358    fn tariff_should_be_object() -> ParseError {
359        Self {
360            object: ObjectType::Tariff,
361            kind: ParseErrorKind::ShouldBeAnObject,
362        }
363    }
364
365    fn from_kind(object: ObjectType) -> impl FnOnce(ParseErrorKind) -> Self {
366        move |kind| Self { object, kind }
367    }
368
369    pub fn kind(&self) -> &ParseErrorKind {
370        &self.kind
371    }
372
373    /// Deconstruct the error.
374    pub fn into_parts(self) -> (ObjectType, ParseErrorKind) {
375        (self.object, self.kind)
376    }
377}
378
379#[derive(Copy, Clone)]
380struct ReasonableStr<'buf>(&'buf str);
381
382impl<'buf> ReasonableStr<'buf> {
383    const MEGA_BYTE: usize = 1024 * 1024;
384
385    /// The maximum allowed size for a `str` given to a parse function.
386    ///
387    /// If the input `str` exceeds this size, a [`ParseErrorKind::SizeExceedsMax`] is returned.
388    ///
389    /// NOTE: Currently the largest tariff at `NLENE` is ~440 KB and the largest CDR is ~1.1 MB.
390    ///
391    /// NOTE: The motivation for a limit is to avoid parsing unseasonably large JSON objects
392    /// whether supplied through incompetence or maliciousness. Large JSON objects can be constructed
393    /// to have many warnings. This could bog down the function processing the JSON object.
394    const MAX_STR_INPUT_LEN: usize = 5 * Self::MEGA_BYTE;
395
396    fn new(s: &'buf str) -> Result<ReasonableStr<'buf>, ParseErrorKind> {
397        if s.len() >= Self::MAX_STR_INPUT_LEN {
398            return Err(ParseErrorKind::SizeExceedsMax);
399        }
400
401        Ok(Self(s))
402    }
403
404    fn into_inner(self) -> &'buf str {
405        self.0
406    }
407}
408
409/// The type of OCPI objects that can be parsed.
410#[derive(Copy, Clone, Debug, Eq, PartialEq)]
411pub enum ObjectType {
412    /// An OCPI Charge Detail Record.
413    ///
414    /// * See: [OCPI spec 2.2.1: CDR](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc>)
415    Cdr,
416
417    /// An OCPI tariff.
418    ///
419    /// * See: [OCPI spec 2.2.1: Tariff](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc>)
420    Tariff,
421}
422
423impl fmt::Display for ObjectType {
424    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
425        match self {
426            ObjectType::Cdr => f.write_str("CDR"),
427            ObjectType::Tariff => f.write_str("tariff"),
428        }
429    }
430}
431
432/// Add two types together and saturate to max if the addition operation overflows.
433///
434/// This is private to the crate as `ocpi-tarifffs` does not want to provide numerical types for use by other crates.
435trait SaturatingAdd {
436    /// Add two types together and saturate to max if the addition operation overflows.
437    #[must_use]
438    fn saturating_add(self, other: Self) -> Self;
439}
440
441/// Subtract two types from each other and saturate to zero if the subtraction operation overflows.
442///
443/// This is private to the crate as `ocpi-tarifffs` does not want to provide numerical types for use by other crates.
444trait SaturatingSub {
445    /// Subtract two types from each other and saturate to zero if the subtraction operation overflows.
446    #[must_use]
447    fn saturating_sub(self, other: Self) -> Self;
448}
449
450/// A debug utility to `Display` an `Option<T>` as either `Display::fmt(T)` or the null set `∅`.
451struct DisplayOption<T>(Option<T>)
452where
453    T: fmt::Display;
454
455impl<T> fmt::Display for DisplayOption<T>
456where
457    T: fmt::Display,
458{
459    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460        match &self.0 {
461            Some(v) => fmt::Display::fmt(v, f),
462            None => f.write_str("∅"),
463        }
464    }
465}