ocpi-tariffs 0.55.0

OCPI tariff calculations
Documentation
//! # OCPI Tariffs library
//!
//! Calculate the (sub)totals of a [charge session](https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc)
//! using the [`cdr::price`] function and use the generated [`price::Report`] to review and compare the calculated
//! totals versus the sources from the `CDR`.
//!
//! A CDR or a tariff goes through four steps: parse, check, build and use.
//! Each step after parsing returns its own warnings, so a caller can tell which step found a
//! fault.
//!
//! ```text
//! &str
//!  |  json::parse_object
//!  v
//! json::Document
//!  |  cdr::check, tariff::check
//!  v
//! cdr::Checked, tariff::Checked  -->  tariff::lint, tariff::fix, timezone::find_or_infer
//!  |  cdr::build, tariff::build
//!  v
//! cdr::Cdr, tariff::Tariff  -->  cdr::price, tariff::explain, cdr::generate_from_tariff
//! ```
//!
//! The check takes the OCPI version as well as the document.
//! When the version isn't known, [`cdr::infer_version`] or [`tariff::infer_version`] guesses it
//! from the document first.
//! A built [`cdr::Cdr`] builds the tariffs it contains with [`cdr::Cdr::tariffs`].
//!
//! - Use [`json::parse_object`] to parse a CDR or tariff `&str` into a [`json::Document`].
//! - Use the [`cdr::check`] and [`tariff::check`] functions to check a [`json::Document`]
//!   against the schema for a given version.
//! - Use [`cdr::build`] to read a CDR into the [`cdr::Cdr`] that [`cdr::price`] takes.
//! - Use [`tariff::build`] to read a tariff into the [`tariff::Tariff`] that
//!   [`tariff::explain`] and [`cdr::generate_from_tariff`] take.
//! - Use [`tariff::lint`] to lint a tariff: flag the constructs a schema-valid tariff can still
//!   get wrong.
//! - Use [`tariff::fix`] to apply the fixes for the schema and lint warnings, and get the fixed
//!   JSON back.
//! - Use [`timezone::find_or_infer`] to find the timezone that [`cdr::price`] needs,
//!   from a checked CDR.
//! - Use [`tariff::explain`] to describe a tariff in human language. Finding fault with a tariff
//!   is [`tariff::lint`]'s job.
//!
//! # Examples
//!
//! ## Price a CDR with embedded tariff
//!
//! If you have a CDR JSON with an embedded tariff you can price the CDR with the following code:
//!
//! ```rust
//! # use ocpi_tariffs::{cdr, json, warning, Version};
//! #
//! # const CDR_JSON: &str = include_str!("cdr.json");
//!
//! let doc = json::parse_object(CDR_JSON)?;
//! let cdr = cdr::check(doc, Version::V211).ignore_warnings();
//! let Ok(cdr) = cdr::build(cdr) else {
//!     return Err("The CDR could not be read well enough to price.".into());
//! };
//! let cdr = cdr.ignore_warnings();
//!
//! let Ok(tariffs) = cdr.tariffs() else {
//!     return Err("The tariffs the CDR contains could not be read well enough to price.".into());
//! };
//! let tariffs = tariffs.ignore_warnings();
//!
//! let Ok(report) = cdr::price(&cdr, &tariffs, &jiff::tz::get!("Europe/Amsterdam")) else {
//!     return Err("The CDR could not be priced.".into());
//! };
//! 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>>(())
//! ```
//!
//! ## Price a CDR using tariff in separate JSON file
//!
//! If you have a CDR JSON with a tariff in a separate JSON file you can price the CDR with the
//! following code:
//!
//! ```rust
//! # use ocpi_tariffs::{cdr, json, tariff, warning, Version};
//! #
//! # const CDR_JSON: &str = include_str!("cdr.json");
//! # const TARIFF_JSON: &str = include_str!("tariff.json");
//!
//! let cdr_doc = json::parse_object(CDR_JSON)?;
//! let cdr = cdr::check(cdr_doc, Version::V211).ignore_warnings();
//! let Ok(cdr) = cdr::build(cdr) else {
//!     return Err("The CDR could not be read well enough to price.".into());
//! };
//! let cdr = cdr.ignore_warnings();
//!
//! let tariff_doc = json::parse_object(TARIFF_JSON)?;
//! let (tariff, _tariff_warnings) = tariff::check(tariff_doc, Version::V211).into_parts();
//! let Ok(tariff) = tariff::build(tariff) else {
//!     return Err("The tariff could not be read well enough to price.".into());
//! };
//! let tariff = tariff.ignore_warnings();
//!
//! let Ok(report) = cdr::price(&cdr, &[tariff], &jiff::tz::get!("Europe/Amsterdam")) else {
//!     return Err("The CDR could not be priced.".into());
//! };
//! 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>>(())
//! ```
//!

// Set here rather than in `[workspace.lints.rust]`: an example is its own crate and links every
// dependency and dev-dependency of the package, so a workspace-wide setting reports each of the
// dozen an example does not happen to use.
#![warn(
    unused_crate_dependencies,
    reason = "a dependency nothing imports is still compiled, audited and imposed on consumers"
)]
// Also set here rather than in `[workspace.lints.rust]`, because this crate's public API is the
// one that has consumers. A workspace-wide setting would also demand documentation of the `cli`
// crate, whose public items exist only to back its binary, and of the build script.
#![warn(missing_docs)]

#[cfg(test)]
mod test;

#[cfg(test)]
mod test_rust_decimal_arbitrary_precision;

pub mod cdr;
pub mod country;
pub mod currency;
pub mod datetime;
pub mod duration;
mod energy;
pub mod explain;
pub mod fix;
pub mod generate;
pub mod json;
pub mod lint;
pub mod money;
pub mod number;
pub mod price;
pub mod schema;
pub mod string;
pub mod tariff;
pub mod timezone;
pub mod version;
pub mod warning;
pub mod weekday;

use std::fmt;

#[doc(inline)]
pub use duration::{ToDuration, ToHoursDecimal};
#[doc(inline)]
pub use energy::{Ampere, Kw, Kwh};
#[doc(inline)]
pub use explain::Language;
#[doc(inline)]
pub use money::{Cost, Money, Price, Vat};
use schema::{FromSchema, LowerSchema};
#[doc(inline)]
pub use version::Version;
#[doc(inline)]
pub use warning::{Caveat, Failure, Verdict, VerdictExt, Warning};
use weekday::Weekday;

/// The Id for a tariff used in the pricing of a CDR.
pub type TariffId = String;

/// Add two types together and saturate to max if the addition operation overflows.
///
/// This is private to the crate as `ocpi-tariffs` does not want to provide numerical types for use by other crates.
trait SaturatingAdd {
    /// Add two types together and saturate to max if the addition operation overflows.
    #[must_use]
    fn saturating_add(self, other: Self) -> Self;
}

/// Subtract two types from each other and saturate to zero if the subtraction operation overflows.
///
/// This is private to the crate as `ocpi-tariffs` does not want to provide numerical types for use by other crates.
trait SaturatingSub {
    /// Subtract two types from each other and saturate to zero if the subtraction operation overflows.
    #[must_use]
    fn saturating_sub(self, other: Self) -> Self;
}

/// A debug utility to `Display` an `Option<T>` as either `Display::fmt(T)` or the null set `∅`.
struct DisplayOption<T>(Option<T>)
where
    T: fmt::Display;

impl<T> fmt::Display for DisplayOption<T>
where
    T: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.0 {
            Some(v) => fmt::Display::fmt(v, f),
            None => f.write_str("∅"),
        }
    }
}