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
use std::fmt;

use tracing::debug;

use crate::{cdr, json, tariff, v211, v221, ParseError, Unversioned, Versioned};

pub type CdrVersion<'buf> = Version<cdr::Versioned<'buf>, cdr::Unversioned<'buf>>;
pub type CdrReport<'buf> = Report<'buf, cdr::Versioned<'buf>, cdr::Unversioned<'buf>>;

/// Guess the `Version` of the given CDR.
///
/// See: `cdr::guess_version`.
pub(crate) fn cdr_version(cdr_json: &str) -> Result<CdrVersion<'_>, ParseError> {
    cdr_version_intern(cdr_json)
}

/// Guess the `Version` of the given CDR and report on any unexpected fields in the JSON.
///
/// See: `cdr::guess_version_with_report`.
pub(crate) fn cdr_version_and_report(cdr_json: &str) -> Result<CdrReport<'_>, ParseError> {
    let version = cdr_version_intern(cdr_json)?;

    let Version::Certain(object) = version else {
        return Ok(Report {
            version,
            unexpected_fields: json::UnexpectedFields::empty(),
        });
    };

    let schema = match object {
        cdr::Versioned::V211(_) => &v211::CDR_SCHEMA,
        cdr::Versioned::V221(_) => &v221::CDR_SCHEMA,
    };

    let report = json::parse_with_schema(cdr_json, schema).map_err(ParseError::from_cdr_err)?;
    let json::Report {
        element: _,
        unexpected_fields,
    } = report;

    Ok(CdrReport {
        unexpected_fields,
        version: Version::Certain(object),
    })
}

/// The private impl for detecting a CDR's version
fn cdr_version_intern(cdr_json: &str) -> Result<CdrVersion<'_>, ParseError> {
    let element = json::parse(cdr_json).map_err(ParseError::from_cdr_err)?;
    let value = element.value();
    let json::Value::Object(fields) = value else {
        return Err(ParseError::cdr_should_be_object());
    };

    for field in fields {
        let key = field.key().as_raw();

        if key.eq_ignore_ascii_case("stop_date_time") {
            return Ok(Version::Certain(cdr::Versioned::V211(element)));
        } else if key.eq_ignore_ascii_case("end_date_time")
            || key.eq_ignore_ascii_case("cdr_location")
            || key.eq_ignore_ascii_case("cdr_token")
        {
            return Ok(Version::Certain(cdr::Versioned::V221(element)));
        }
    }

    Ok(Version::Uncertain(cdr::Unversioned::new(element)))
}

pub type TariffVersion<'buf> = Version<tariff::Versioned<'buf>, tariff::Unversioned<'buf>>;
pub type TariffReport<'buf> = Report<'buf, tariff::Versioned<'buf>, tariff::Unversioned<'buf>>;

/// Guess the `Version` of the given tariff.
///
/// See: [`tariff::guess_version`]
pub(crate) fn tariff_version(tariff_json: &str) -> Result<TariffVersion<'_>, ParseError> {
    tariff_version_intern(tariff_json)
}

/// Guess the `Version` of the given tariff and report on any unexpected fields in the JSON.
///
/// See: [`tariff::guess_version_with_report`]
pub(crate) fn tariff_version_with_report(
    tariff_json: &str,
) -> Result<TariffReport<'_>, ParseError> {
    let version = tariff_version_intern(tariff_json)?;

    let Version::Certain(object) = version else {
        return Ok(Report {
            version,
            unexpected_fields: json::UnexpectedFields::empty(),
        });
    };

    let schema = match object {
        tariff::Versioned::V211(_) => &v211::TARIFF_SCHEMA,
        tariff::Versioned::V221(_) => &v221::TARIFF_SCHEMA,
    };

    let report =
        json::parse_with_schema(tariff_json, schema).map_err(ParseError::from_tariff_err)?;
    let json::Report {
        element: _,
        unexpected_fields,
    } = report;

    Ok(TariffReport {
        unexpected_fields,
        version: Version::Certain(object),
    })
}

/// The private impl for detecting a tariff's version
fn tariff_version_intern(tariff_json: &str) -> Result<TariffVersion<'_>, ParseError> {
    /// The list of field names exclusively defined in the `v221` spec.
    const V221_EXCLUSIVE_FIELDS: &[&str] = &[
        "country_code",
        "party_id",
        "type",
        "min_price",
        "max_price",
        "start_date_time",
        "end_date_time",
    ];

    /// The list of field names shared between the `v211` and `v221` specs.
    const V211_V221_SHARED_FIELDS: &[&str] = &[
        "id",
        "currency",
        "tariff_alt_text",
        "tariff_alt_url",
        "elements",
        "energy_mix",
        "last_updated",
    ];

    // Parse the tariff without a schema first to determine the version.
    let element = json::parse(tariff_json).map_err(ParseError::from_tariff_err)?;
    let value = element.value();
    let json::Value::Object(fields) = value else {
        return Err(ParseError::tariff_should_be_object());
    };

    for field in fields {
        let key = field.key().as_raw();

        // If the field is in the v221 exclusive list we know without a doubt that it's a v221 tariff.
        if V221_EXCLUSIVE_FIELDS.contains(&key) {
            debug!("Tariff is v221 because of field: `{key}`");
            return Ok(TariffVersion::Certain(tariff::Versioned::V221(element)));
        }
    }

    for field in fields {
        let key = field.key().as_raw();

        if V211_V221_SHARED_FIELDS.contains(&key) {
            return Ok(TariffVersion::Certain(tariff::Versioned::V211(element)));
        }
    }

    Ok(TariffVersion::Uncertain(tariff::Unversioned::new(element)))
}

/// The guessed version for the CDR or tariff objects.
#[derive(Debug)]
pub enum Version<V, U>
where
    V: Versioned,
    U: fmt::Debug,
{
    /// If the Version of the object is certain, the [`Versioned`] object is stored here.
    Certain(V),

    /// The version can't be determined with certainty.
    /// The object with an uncertain version is stored here.
    Uncertain(U),
}

impl<V, U> Version<V, U>
where
    V: Versioned,
    U: Unversioned<Versioned = V>,
{
    /// Convert [`Versioned`] object with it's [`Version`](crate::Version).
    pub fn into_version(self) -> Version<crate::Version, ()> {
        match self {
            Version::Certain(v) => Version::Certain(v.version()),
            Version::Uncertain(_) => Version::Uncertain(()),
        }
    }

    /// Convert [`Versioned`] object with it's [`Version`](crate::Version).
    pub fn as_version(&self) -> Version<crate::Version, ()> {
        match self {
            Version::Certain(v) => Version::Certain(v.version()),
            Version::Uncertain(_) => Version::Uncertain(()),
        }
    }

    /// Convert [`Versioned`] object with it's [`Version`](crate::Version).
    pub fn certain_or(self, fallback: crate::Version) -> V {
        match self {
            Version::Certain(v) => v,
            Version::Uncertain(u) => u.force_into_versioned(fallback),
        }
    }

    /// Discard the object if the version is uncertain.
    pub fn certain_or_none(self) -> Option<V> {
        match self {
            Version::Certain(v) => Some(v),
            Version::Uncertain(_) => None,
        }
    }
}

/// The guess version report.
///
/// This contains the guessed version of the given JSON object and a list of unexpected fields
/// if the JSON contains fields not specified in the guessed version of the OCPI spec.
///
/// The `unexpected_fields` list will always be empty if the guessed `Version` is `Uncertain`.
#[derive(Debug)]
pub struct Report<'buf, V, U>
where
    V: Versioned,
    U: fmt::Debug,
{
    /// A list of fields that were not expected: The schema did not define them.
    ///
    /// This list will always be empty if the guessed `Version` is `Uncertain`.
    unexpected_fields: json::UnexpectedFields<'buf>,

    /// The guessed version.
    ///
    /// The `unexpected_fields` list will always be empty if the guessed `Version` is `Uncertain`.
    version: Version<V, U>,
}

impl<'buf, V, U> Report<'buf, V, U>
where
    V: Versioned,
    U: fmt::Debug,
{
    pub fn version(&self) -> &Version<V, U> {
        &self.version
    }

    pub fn into_parts(self) -> (Version<V, U>, json::UnexpectedFields<'buf>) {
        let Self {
            unexpected_fields,
            version,
        } = self;
        (version, unexpected_fields)
    }
}

#[cfg(test)]
mod test {
    use super::{Unversioned, Version, Versioned};

    impl<V, U> Version<V, U>
    where
        V: Versioned,
        U: Unversioned<Versioned = V>,
    {
        /// Return the `Versioned` object if the `Version` is `Certain`.
        ///
        /// # Panics
        ///
        /// Will panic if the `Version` is `Uncertain`.
        pub fn unwrap_certain(self) -> V {
            match self {
                Version::Certain(v) => v,
                Version::Uncertain(_) => panic!("The version of the object is unknown"),
            }
        }
    }
}

#[cfg(test)]
mod test_guess_cdr {
    use assert_matches::assert_matches;

    use crate::{test, Versioned as _};

    use super::{cdr_version_and_report, Report, Version};

    #[test]
    fn should_guess_cdr_version_v211() {
        const JSON: &str = include_str!("../test_data/v211/lint/every_field_set/cdr.json");

        test::setup();

        let Report {
            version,
            unexpected_fields,
        } = cdr_version_and_report(JSON).unwrap();

        let cdr = assert_matches!(version, Version::Certain ( cdr ) => cdr );
        assert_matches!(cdr.version(), crate::Version::V211);

        test::assert_no_unexpected_fields(&unexpected_fields);
    }

    #[test]
    fn should_guess_cdr_version_v221() {
        const JSON: &str = include_str!("../test_data/v221/lint/every_field_set/cdr.json");

        test::setup();

        let Report {
            version,
            unexpected_fields,
        } = cdr_version_and_report(JSON).unwrap();

        let cdr = assert_matches!(version, Version::Certain ( cdr ) => cdr );
        assert_matches!(cdr.version(), crate::Version::V221);

        test::assert_no_unexpected_fields(&unexpected_fields);
    }
}

#[cfg(test)]
mod test_guess_tariff {
    use assert_matches::assert_matches;

    use crate::{test, Versioned as _};

    use super::{tariff_version_with_report, Report, Version};

    #[test]
    fn should_guess_tariff_version_v211() {
        const JSON: &str = include_str!("../test_data/v211/lint/every_field_set/tariff.json");

        test::setup();

        let Report {
            version,
            unexpected_fields,
        } = tariff_version_with_report(JSON).unwrap();

        let tariff = assert_matches!(version, Version::Certain ( tariff ) => tariff );
        assert_matches!(tariff.version(), crate::Version::V211);

        test::assert_no_unexpected_fields(&unexpected_fields);
    }

    #[test]
    fn should_guess_tariff_version_v221() {
        const JSON: &str = include_str!("../test_data/v221/lint/every_field_set/tariff.json");

        test::setup();

        let Report {
            version,
            unexpected_fields,
        } = tariff_version_with_report(JSON).unwrap();

        let tariff = assert_matches!(version, Version::Certain ( tariff ) => tariff );
        assert_matches!(tariff.version(), crate::Version::V221);

        test::assert_no_unexpected_fields(&unexpected_fields);
    }
}

#[cfg(test)]
mod test_real_world {
    use std::path::Path;

    use assert_matches::assert_matches;

    use crate::{test, Versioned as _};

    use super::{cdr_version_and_report, tariff_version_with_report, Report, Version};

    #[test_each::file(
        glob = "ocpi-tariffs/test_data/v221/real_world/*/cdr*.json",
        name(segments = 2)
    )]
    fn should_guess_version_v221(cdr_json: &str, path: &Path) {
        test::setup();

        {
            let Report {
                version,
                unexpected_fields,
            } = cdr_version_and_report(cdr_json).unwrap();

            let tariff = assert_matches!(version, Version::Certain ( tariff ) => tariff );
            assert_matches!(tariff.version(), crate::Version::V221);

            test::assert_no_unexpected_fields(&unexpected_fields);
        }

        {
            let tariff = std::fs::read_to_string(path.parent().unwrap().join("tariff.json")).ok();

            if let Some(tariff) = tariff {
                let Report {
                    version: guess,
                    unexpected_fields,
                } = tariff_version_with_report(&tariff).unwrap();

                let tariff = assert_matches!(guess, Version::Certain ( tariff ) => tariff);
                assert_matches!(tariff.version(), crate::Version::V221);

                test::assert_no_unexpected_fields(&unexpected_fields);
            }
        }
    }

    #[test_each::file(
        glob = "ocpi-tariffs/test_data/v211/lint/*/cdr*.json",
        name(segments = 2)
    )]
    fn should_guess_version_v211(cdr_json: &str, path: &Path) {
        test::setup();

        {
            let Report {
                version: guess,
                unexpected_fields,
            } = cdr_version_and_report(cdr_json).unwrap();

            let cdr = assert_matches!(guess, Version::Certain ( cdr ) => cdr);
            assert_matches!(cdr.version(), crate::Version::V211);

            test::assert_no_unexpected_fields(&unexpected_fields);
        }

        {
            let tariff_json =
                std::fs::read_to_string(path.parent().unwrap().join("tariff.json")).ok();

            if let Some(tariff) = tariff_json {
                let Report {
                    version: guess,
                    unexpected_fields,
                } = tariff_version_with_report(&tariff).unwrap();

                let tariff = assert_matches!(guess, Version::Certain ( tariff ) => tariff);
                assert_matches!(tariff.version(), crate::Version::V211);

                test::assert_no_unexpected_fields(&unexpected_fields);
            }
        }
    }
}