ocpi-tariffs 0.20.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
//! # OCPI Tariffs library
//!
//! Calculate the (sub)totals of a [charge session](https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/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`.
//!
//! See the [`price::Report`] for a detailed list of all the fields that help analyze and valitate the pricing of a `CDR`.
//!
//! - Use the [`cdr::parse`] and [`tariff::parse`] function to parse and guess which OCPI version of a CDR or tariff you have.
//! - Use the [`cdr::parse_with_version`] and [`tariff::parse_with_version`] functions to parse a CDR of tariff as the given version.
//! - Use the [`tariff::lint`] to lint a tariff: flag common errors, bugs, dangerous constructs and stylistic flaws in the tariff.

/// Module containing the functionality to price charge sessions with provided tariffs.
pub mod cdr;
pub mod country;
pub mod currency;
mod datetime;
mod de;
mod duration;
mod energy;
pub mod guess;
pub mod json;
pub mod lint;
mod money;
mod number;
pub mod price;
pub mod tariff;
pub mod timezone;
mod types;
mod v211;
mod v221;
pub mod warning;

use std::{collections::BTreeSet, fmt};

pub(crate) use datetime::DateTime;
use datetime::{Date, Time};
use duration::{HoursDecimal, SecondsRound};
use energy::{Ampere, Kw, Kwh};
pub(crate) use number::Number;
use serde::{Deserialize, Deserializer};
use types::DayOfWeek;
use warning::IntoCaveat;

pub use money::{Money, Price, Vat};
#[doc(inline)]
pub use warning::{Caveat, Verdict, VerdictExt, Warning};

/// Set of unexpected fields encountered while parsing a CDR or tariff.
pub type UnexpectedFields = BTreeSet<String>;

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

/// The OCPI versions supported by this crate
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Version {
    V221,
    V211,
}

impl Versioned for Version {
    fn version(&self) -> Version {
        *self
    }
}

impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Version::V221 => f.write_str("v221"),
            Version::V211 => f.write_str("v211"),
        }
    }
}

/// An object for a specific OCPI [`Version`].
pub trait Versioned: fmt::Debug {
    /// Return the `Version` this object is for.
    fn version(&self) -> Version;
}

/// An object with an uncertain [`Version`].
pub trait Unversioned: fmt::Debug {
    /// The concrete [`Versioned`] type.
    type Versioned: Versioned;

    /// Forced an [`Unversioned`] object to be the given [`Version`].
    fn force_into_versioned(self, version: Version) -> Self::Versioned;
}

/// Out of range error type used in various converting APIs
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub struct OutOfRange(());

impl std::error::Error for OutOfRange {}

impl OutOfRange {
    const fn new() -> OutOfRange {
        OutOfRange(())
    }
}

impl fmt::Display for OutOfRange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "out of range")
    }
}

impl fmt::Debug for OutOfRange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "out of range")
    }
}

/// Errors that can happen if a JSON str is parsed.
pub struct ParseError {
    /// The type of object we were trying to deserialize.
    object: ObjectType,

    /// The error that occurred while deserializing.
    kind: ParseErrorKind,
}

/// The kind of Error that occurred.
pub enum ParseErrorKind {
    /// Some Error types are erased to abvoid leaking dependencies.
    Erased(Box<dyn std::error::Error + Send + Sync + 'static>),

    /// The integrated JSON parser was unable to parse a JSON str.
    Json(json::Error),

    /// The OCPI object should be a JSON object.
    ShouldBeAnObject,
}

impl std::error::Error for ParseError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match &self.kind {
            ParseErrorKind::Erased(err) => Some(&**err),
            ParseErrorKind::Json(err) => Some(err),
            ParseErrorKind::ShouldBeAnObject => None,
        }
    }
}

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

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "while deserializing {:?}: ", self.object)?;

        match &self.kind {
            ParseErrorKind::Erased(err) => write!(f, "{err}"),
            ParseErrorKind::Json(err) => write!(f, "{err}"),
            ParseErrorKind::ShouldBeAnObject => f.write_str("The root element should be an object"),
        }
    }
}

impl ParseError {
    /// Create a [`DeserializeError`] from a generic std Error for a CDR object.
    fn from_cdr_err(err: json::Error) -> Self {
        Self {
            object: ObjectType::Tariff,
            kind: ParseErrorKind::Json(err),
        }
    }

    /// Create a [`DeserializeError`] from a generic std Error for a tariff object.
    fn from_tariff_err(err: json::Error) -> Self {
        Self {
            object: ObjectType::Tariff,
            kind: ParseErrorKind::Json(err),
        }
    }

    /// Create a [`DeserializeError`] from a generic std Error for a CDR object.
    fn from_cdr_serde_err(err: serde_json::Error) -> Self {
        Self {
            object: ObjectType::Cdr,
            kind: ParseErrorKind::Erased(err.into()),
        }
    }

    /// Create a [`DeserializeError`] from a generic std Error for a tariff object.
    fn from_tariff_serde_err(err: serde_json::Error) -> Self {
        Self {
            object: ObjectType::Tariff,
            kind: ParseErrorKind::Erased(err.into()),
        }
    }

    fn cdr_should_be_object() -> ParseError {
        Self {
            object: ObjectType::Cdr,
            kind: ParseErrorKind::ShouldBeAnObject,
        }
    }

    fn tariff_should_be_object() -> ParseError {
        Self {
            object: ObjectType::Tariff,
            kind: ParseErrorKind::ShouldBeAnObject,
        }
    }

    /// Deconstruct the error.
    pub fn into_parts(self) -> (ObjectType, ParseErrorKind) {
        (self.object, self.kind)
    }
}

/// The type of OCPI objects that can be parsed.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ObjectType {
    /// An OCPI Charge Detail Record.
    ///
    /// * See: [OCPI spec 2.2.1: CDR](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc>)
    Cdr,

    /// An OCPI tariff.
    ///
    /// * See: [OCPI spec 2.2.1: Tariff](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc>)
    Tariff,
}

fn null_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
    T: Default + Deserialize<'de>,
    D: Deserializer<'de>,
{
    let opt = Option::deserialize(deserializer)?;
    Ok(opt.unwrap_or_default())
}

#[cfg(test)]
mod test {
    use std::{env, fmt, io::IsTerminal as _, path::Path, sync::Once};

    use rust_decimal::Decimal;
    use serde::{
        de::{value::StrDeserializer, IntoDeserializer as _},
        Deserialize,
    };
    use tracing::debug;
    use tracing_subscriber::util::SubscriberInitExt as _;

    use crate::{json, DateTime};

    /// Creates and sets the default tracing subscriber if not already done.
    #[track_caller]
    pub fn setup() {
        static INITIALIZED: Once = Once::new();

        INITIALIZED.call_once_force(|state| {
            if state.is_poisoned() {
                return;
            }

            let is_tty = std::io::stderr().is_terminal();

            let level = match env::var("RUST_LOG") {
                Ok(s) => s.parse().unwrap_or(tracing::Level::INFO),
                Err(err) => match err {
                    env::VarError::NotPresent => tracing::Level::INFO,
                    env::VarError::NotUnicode(_) => {
                        panic!("`RUST_LOG` is not unicode");
                    }
                },
            };

            let subscriber = tracing_subscriber::fmt()
                .with_ansi(is_tty)
                .with_file(true)
                .with_level(false)
                .with_line_number(true)
                .with_max_level(level)
                .with_target(false)
                .with_test_writer()
                .without_time()
                .finish();

            subscriber
                .try_init()
                .expect("Init tracing_subscriber::Subscriber");
        });
    }

    /// Gives access to the inner `Decimal` by reference.
    pub trait AsDecimal {
        fn as_dec(&self) -> &Decimal;
    }

    /// Compares two decimal objects with a tolerance
    pub trait DecimalPartialEq<Rhs = Self> {
        #[must_use]
        fn eq_dec(&self, other: &Rhs) -> bool;
    }

    #[track_caller]
    pub fn assert_no_unexpected_fields(unexpected_fields: &json::UnexpectedFields<'_>) {
        if !unexpected_fields.is_empty() {
            const MAX_FIELD_DISPLAY: usize = 20;

            if unexpected_fields.len() > MAX_FIELD_DISPLAY {
                let truncated_fields = unexpected_fields
                    .iter()
                    .take(MAX_FIELD_DISPLAY)
                    .map(|path| path.to_string())
                    .collect::<Vec<_>>();

                panic!(
                    "Unexpected fields found({}); displaying the first ({}): \n{}\n... and {} more",
                    unexpected_fields.len(),
                    truncated_fields.len(),
                    truncated_fields.join(",\n"),
                    unexpected_fields.len() - truncated_fields.len(),
                )
            } else {
                panic!(
                    "Unexpected fields found({}):\n{}",
                    unexpected_fields.len(),
                    unexpected_fields.to_strings().join(",\n")
                )
            };
        }
    }

    #[track_caller]
    pub fn assert_unexpected_fields(
        unexpected_fields: &json::UnexpectedFields<'_>,
        expected: &[&'static str],
    ) {
        if unexpected_fields.len() != expected.len() {
            let unexpected_fields = unexpected_fields
                .into_iter()
                .map(|path| path.to_string())
                .collect::<Vec<_>>();

            panic!(
                "The unexpected fields and expected fields lists have different lengths.\n\nUnexpected fields found:\n{}",
                unexpected_fields.join(",\n")
            );
        }

        let unmatched_paths = unexpected_fields
            .into_iter()
            .zip(expected.iter())
            .filter(|(a, b)| a != *b)
            .collect::<Vec<_>>();

        if !unmatched_paths.is_empty() {
            let unmatched_paths = unmatched_paths
                .into_iter()
                .map(|(a, b)| format!("{a} != {b}"))
                .collect::<Vec<_>>();

            panic!(
                "The unexpected fields don't match the expected fields.\n\nUnexpected fields found:\n{}",
                unmatched_paths.join(",\n")
            );
        }
    }

    /// A Field in the expect JSON.
    ///
    /// We need to distinguish between a field that's present and null and absent.
    #[derive(Debug, Default)]
    pub enum Expectation<T> {
        /// The field is present.
        Present(ExpectValue<T>),

        /// The field is not preent.
        #[default]
        Absent,
    }

    /// The value of an expectation field.
    #[derive(Debug)]
    pub enum ExpectValue<T> {
        /// The field has a value.
        Some(T),

        /// The field is set to `null`.
        Null,
    }

    impl<T> ExpectValue<T>
    where
        T: fmt::Debug,
    {
        /// Convert the expectation into an `Option`.
        pub fn into_option(self) -> Option<T> {
            match self {
                Self::Some(v) => Some(v),
                Self::Null => None,
            }
        }

        /// Consume the expectation and return the inner value of type `T`.
        ///
        /// # Panics
        ///
        /// Parnics if the `FieldValue` is `Null`.
        #[track_caller]
        pub fn expect_value(self) -> T {
            match self {
                ExpectValue::Some(v) => v,
                ExpectValue::Null => panic!("the field expects a value"),
            }
        }
    }

    impl<'de, T> Deserialize<'de> for Expectation<T>
    where
        T: Deserialize<'de>,
    {
        #[expect(clippy::unwrap_in_result, reason = "This is test util code")]
        #[track_caller]
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: serde::Deserializer<'de>,
        {
            let value = serde_json::Value::deserialize(deserializer)?;

            if value.is_null() {
                return Ok(Expectation::Present(ExpectValue::Null));
            }

            let v = T::deserialize(value).unwrap();
            Ok(Expectation::Present(ExpectValue::Some(v)))
        }
    }

    /// Create a `DateTime` from a RFC 3339 formatted string.
    #[track_caller]
    pub fn datetime_from_str(s: &str) -> DateTime {
        let de: StrDeserializer<'_, serde::de::value::Error> = s.into_deserializer();
        DateTime::deserialize(de).unwrap()
    }

    /// Try read an expectation JSON file based on the name of the given object JSON file.
    ///
    /// If the JSON object file is called `cdr.json` with a feature of `price` an expectation file
    /// called `expect_cdr_price.json` is searched for.
    #[track_caller]
    pub fn read_expect_json(json_file_path: &Path, feature: &str) -> Option<String> {
        let json_dir = json_file_path
            .parent()
            .expect("The given file should live in a dir");

        let json_file_name = json_file_path
            .file_stem()
            .expect("The `json_file_path` should be a file")
            .to_str()
            .expect("The `json_file_path` should have a valid name");

        // An underscore is prefixed to the filename to exclude the file from being included
        // as input for a `test_each` glob driven test.
        let expect_file_name = format!("output_{feature}__{json_file_name}.json");

        debug!("Try to read expectation file: `{expect_file_name}`");

        let s = std::fs::read_to_string(json_dir.join(&expect_file_name))
            .ok()
            .map(|mut s| {
                json_strip_comments::strip(&mut s).ok();
                s
            });

        debug!("Successfully Read expectation file: `{expect_file_name}`");
        s
    }
}

#[cfg(test)]
mod test_rust_decimal_arbitrary_precision {
    use rust_decimal_macros::dec;

    use crate::Number;

    #[test]
    fn should_serialize_decimal_with_12_fraction_digits() {
        let dec = dec!(0.123456789012);
        let actual = serde_json::to_string(&dec).unwrap();
        assert_eq!(actual, r#""0.123456789012""#.to_owned());
    }

    #[test]
    fn should_serialize_decimal_with_8_fraction_digits() {
        let dec = dec!(37.12345678);
        let actual = serde_json::to_string(&dec).unwrap();
        assert_eq!(actual, r#""37.12345678""#.to_owned());
    }

    #[test]
    fn should_serialize_0_decimal_without_fraction_digits() {
        let dec = dec!(0);
        let actual = serde_json::to_string(&dec).unwrap();
        assert_eq!(actual, r#""0""#.to_owned());
    }

    #[test]
    fn should_serialize_12_num_with_4_fraction_digits() {
        let num: Number = dec!(0.1234).try_into().unwrap();
        let actual = serde_json::to_string(&num).unwrap();
        assert_eq!(actual, r#""0.1234""#.to_owned());
    }

    #[test]
    fn should_serialize_8_num_with_4_fraction_digits() {
        let num: Number = dec!(37.1234).try_into().unwrap();
        let actual = serde_json::to_string(&num).unwrap();
        assert_eq!(actual, r#""37.1234""#.to_owned());
    }

    #[test]
    fn should_serialize_0_num_without_fraction_digits() {
        let num: Number = dec!(0).try_into().unwrap();
        let actual = serde_json::to_string(&num).unwrap();
        assert_eq!(actual, r#""0""#.to_owned());
    }
}