ocpi_tariffs/lib.rs
1//! # OCPI Tariffs library
2//!
3//! Calculate the (sub)totals of a [charge session](https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/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//! A CDR or a tariff goes through four steps: parse, check, build and use.
8//! Each step after parsing returns its own warnings, so a caller can tell which step found a
9//! fault.
10//!
11//! ```text
12//! &str
13//! | json::parse_object
14//! v
15//! json::Document
16//! | cdr::check, tariff::check
17//! v
18//! cdr::Checked, tariff::Checked --> tariff::lint, tariff::fix, timezone::find_or_infer
19//! | cdr::build, tariff::build
20//! v
21//! cdr::Cdr, tariff::Tariff --> cdr::price, tariff::explain, cdr::generate_from_tariff
22//! ```
23//!
24//! The check takes the OCPI version as well as the document.
25//! When the version isn't known, [`cdr::infer_version`] or [`tariff::infer_version`] guesses it
26//! from the document first.
27//! A built [`cdr::Cdr`] builds the tariffs it contains with [`cdr::Cdr::tariffs`].
28//!
29//! - Use [`json::parse_object`] to parse a CDR or tariff `&str` into a [`json::Document`].
30//! - Use the [`cdr::check`] and [`tariff::check`] functions to check a [`json::Document`]
31//! against the schema for a given version.
32//! - Use [`cdr::build`] to read a CDR into the [`cdr::Cdr`] that [`cdr::price`] takes.
33//! - Use [`tariff::build`] to read a tariff into the [`tariff::Tariff`] that
34//! [`tariff::explain`] and [`cdr::generate_from_tariff`] take.
35//! - Use [`tariff::lint`] to lint a tariff: flag the constructs a schema-valid tariff can still
36//! get wrong.
37//! - Use [`tariff::fix`] to apply the fixes for the schema and lint warnings, and get the fixed
38//! JSON back.
39//! - Use [`timezone::find_or_infer`] to find the timezone that [`cdr::price`] needs,
40//! from a checked CDR.
41//! - Use [`tariff::explain`] to describe a tariff in human language. Finding fault with a tariff
42//! is [`tariff::lint`]'s job.
43//!
44//! # Examples
45//!
46//! ## Price a CDR with embedded tariff
47//!
48//! If you have a CDR JSON with an embedded tariff you can price the CDR with the following code:
49//!
50//! ```rust
51//! # use ocpi_tariffs::{cdr, json, warning, Version};
52//! #
53//! # const CDR_JSON: &str = include_str!("cdr.json");
54//!
55//! let doc = json::parse_object(CDR_JSON)?;
56//! let cdr = cdr::check(doc, Version::V211).ignore_warnings();
57//! let Ok(cdr) = cdr::build(cdr) else {
58//! return Err("The CDR could not be read well enough to price.".into());
59//! };
60//! let cdr = cdr.ignore_warnings();
61//!
62//! let Ok(tariffs) = cdr.tariffs() else {
63//! return Err("The tariffs the CDR contains could not be read well enough to price.".into());
64//! };
65//! let tariffs = tariffs.ignore_warnings();
66//!
67//! let Ok(report) = cdr::price(&cdr, &tariffs, &jiff::tz::get!("Europe/Amsterdam")) else {
68//! return Err("The CDR could not be priced.".into());
69//! };
70//! let (report, warnings) = report.into_parts();
71//!
72//! if !warnings.is_empty() {
73//! eprintln!("Pricing the CDR resulted in `{}` warnings", warnings.len_warnings());
74//!
75//! for group in warnings {
76//! let (element, warnings) = group.to_parts();
77//! eprintln!(" {}", element.path);
78//!
79//! for warning in warnings {
80//! eprintln!(" - {warning}");
81//! }
82//! }
83//! }
84//!
85//! # Ok::<(), Box<dyn std::error::Error + Send + Sync + 'static>>(())
86//! ```
87//!
88//! ## Price a CDR using tariff in separate JSON file
89//!
90//! If you have a CDR JSON with a tariff in a separate JSON file you can price the CDR with the
91//! following code:
92//!
93//! ```rust
94//! # use ocpi_tariffs::{cdr, json, tariff, warning, Version};
95//! #
96//! # const CDR_JSON: &str = include_str!("cdr.json");
97//! # const TARIFF_JSON: &str = include_str!("tariff.json");
98//!
99//! let cdr_doc = json::parse_object(CDR_JSON)?;
100//! let cdr = cdr::check(cdr_doc, Version::V211).ignore_warnings();
101//! let Ok(cdr) = cdr::build(cdr) else {
102//! return Err("The CDR could not be read well enough to price.".into());
103//! };
104//! let cdr = cdr.ignore_warnings();
105//!
106//! let tariff_doc = json::parse_object(TARIFF_JSON)?;
107//! let (tariff, _tariff_warnings) = tariff::check(tariff_doc, Version::V211).into_parts();
108//! let Ok(tariff) = tariff::build(tariff) else {
109//! return Err("The tariff could not be read well enough to price.".into());
110//! };
111//! let tariff = tariff.ignore_warnings();
112//!
113//! let Ok(report) = cdr::price(&cdr, &[tariff], &jiff::tz::get!("Europe/Amsterdam")) else {
114//! return Err("The CDR could not be priced.".into());
115//! };
116//! let (report, warnings) = report.into_parts();
117//!
118//! if !warnings.is_empty() {
119//! eprintln!("Pricing the CDR resulted in `{}` warnings", warnings.len_warnings());
120//!
121//! for group in warnings {
122//! let (element, warnings) = group.to_parts();
123//! eprintln!(" {}", element.path);
124//!
125//! for warning in warnings {
126//! eprintln!(" - {warning}");
127//! }
128//! }
129//! }
130//!
131//! # Ok::<(), Box<dyn std::error::Error + Send + Sync + 'static>>(())
132//! ```
133//!
134
135// Set here rather than in `[workspace.lints.rust]`: an example is its own crate and links every
136// dependency and dev-dependency of the package, so a workspace-wide setting reports each of the
137// dozen an example does not happen to use.
138#![warn(
139 unused_crate_dependencies,
140 reason = "a dependency nothing imports is still compiled, audited and imposed on consumers"
141)]
142// Also set here rather than in `[workspace.lints.rust]`, because this crate's public API is the
143// one that has consumers. A workspace-wide setting would also demand documentation of the `cli`
144// crate, whose public items exist only to back its binary, and of the build script.
145#![warn(missing_docs)]
146
147#[cfg(test)]
148mod test;
149
150#[cfg(test)]
151mod test_rust_decimal_arbitrary_precision;
152
153pub mod cdr;
154pub mod country;
155pub mod currency;
156pub mod datetime;
157pub mod duration;
158mod energy;
159pub mod explain;
160pub mod fix;
161pub mod generate;
162pub mod json;
163pub mod lint;
164pub mod money;
165pub mod number;
166pub mod price;
167pub mod schema;
168pub mod string;
169pub mod tariff;
170pub mod timezone;
171pub mod version;
172pub mod warning;
173pub mod weekday;
174
175use std::fmt;
176
177#[doc(inline)]
178pub use duration::{ToDuration, ToHoursDecimal};
179#[doc(inline)]
180pub use energy::{Ampere, Kw, Kwh};
181#[doc(inline)]
182pub use explain::Language;
183#[doc(inline)]
184pub use money::{Cost, Money, Price, Vat};
185use schema::{FromSchema, LowerSchema};
186#[doc(inline)]
187pub use version::Version;
188#[doc(inline)]
189pub use warning::{Caveat, Failure, Verdict, VerdictExt, Warning};
190use weekday::Weekday;
191
192/// The Id for a tariff used in the pricing of a CDR.
193pub type TariffId = String;
194
195/// Add two types together and saturate to max if the addition operation overflows.
196///
197/// This is private to the crate as `ocpi-tariffs` does not want to provide numerical types for use by other crates.
198trait SaturatingAdd {
199 /// Add two types together and saturate to max if the addition operation overflows.
200 #[must_use]
201 fn saturating_add(self, other: Self) -> Self;
202}
203
204/// Subtract two types from each other and saturate to zero if the subtraction operation overflows.
205///
206/// This is private to the crate as `ocpi-tariffs` does not want to provide numerical types for use by other crates.
207trait SaturatingSub {
208 /// Subtract two types from each other and saturate to zero if the subtraction operation overflows.
209 #[must_use]
210 fn saturating_sub(self, other: Self) -> Self;
211}
212
213/// A debug utility to `Display` an `Option<T>` as either `Display::fmt(T)` or the null set `∅`.
214struct DisplayOption<T>(Option<T>)
215where
216 T: fmt::Display;
217
218impl<T> fmt::Display for DisplayOption<T>
219where
220 T: fmt::Display,
221{
222 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223 match &self.0 {
224 Some(v) => fmt::Display::fmt(v, f),
225 None => f.write_str("∅"),
226 }
227 }
228}