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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
use std::{fmt, ops::Deref};

use chrono::{NaiveDateTime, TimeZone as _, Timelike as _, Utc};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::{
    into_caveat, json,
    warning::{self, GatherWarnings as _},
    IntoCaveat, Verdict,
};

pub type ChronoDateTime = chrono::DateTime<Utc>;

#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum WarningKind {
    /// The datetime does not need to contain escape codes.
    ContainsEscapeCodes,

    /// The field at the path could not be decoded.
    Decode(json::decode::WarningKind),

    /// The datetime is not valid.
    Invalid(Error),

    /// The JSON value given is not a string.
    InvalidType,
}

impl fmt::Display for WarningKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            WarningKind::ContainsEscapeCodes => write!(f, "contains_escape_codes"),
            WarningKind::Decode(warning) => fmt::Display::fmt(warning, f),
            WarningKind::Invalid(_) => write!(f, "invalid"),
            WarningKind::InvalidType => write!(f, "invalid_type"),
        }
    }
}

impl warning::Kind for WarningKind {
    fn id(&self) -> std::borrow::Cow<'static, str> {
        match self {
            WarningKind::ContainsEscapeCodes => "contains_escape_codes".into(),
            WarningKind::Decode(kind) => format!("decode.{}", kind.id()).into(),
            WarningKind::Invalid(_) => "invalid".into(),
            WarningKind::InvalidType => "invalid_type".into(),
        }
    }
}

#[derive(Debug, Eq, PartialEq)]
pub struct Error(chrono::ParseError);

impl Ord for Error {
    fn cmp(&self, _other: &Self) -> std::cmp::Ordering {
        std::cmp::Ordering::Equal
    }
}

impl PartialOrd for Error {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

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

into_caveat!(chrono::Duration);

impl json::FromJson<'_, '_> for chrono::Duration {
    type WarningKind = duration::WarningKind;

    fn from_json(elem: &'_ json::Element<'_>) -> Verdict<Self, Self::WarningKind> {
        let mut warnings = warning::Set::new();
        let Some(s) = elem.as_number_str() else {
            warnings.with_elem(duration::WarningKind::InvalidType, elem);
            return Err(warnings);
        };

        // We only support positive durations in an OCPI object.
        let seconds = match s.parse::<u64>() {
            Ok(n) => n,
            Err(err) => {
                warnings.with_elem(duration::WarningKind::Invalid(err.to_string()), elem);
                return Err(warnings);
            }
        };

        // Then we convert the positive duration to an i64 as that is how `chrono::Duration`
        // represents seconds.
        let Ok(seconds) = i64::try_from(seconds) else {
            warnings.with_elem(
                duration::WarningKind::Invalid(
                    "The duration value is larger than an i64 can represent.".into(),
                ),
                elem,
            );
            return Err(warnings);
        };
        let duration = chrono::Duration::seconds(seconds);

        Ok(duration.into_caveat(warnings))
    }
}

pub mod duration {
    //! The Warning infrastructure for the `chrono::Duration` type used in the processing of the
    //! `min_duration` and `max_duration` fields of the tariff Restriction.
    //!
    //! * See: [OCPI spec 2.2.1: Tariff Restriction](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#146-tariffrestrictions-class>)
    //! * See: [OCPI spec 2.1.1: Tariff Restriction](<https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_tariffs.md#45-tariffrestrictions-class>)

    use std::{borrow::Cow, fmt};

    use crate::warning;

    #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
    pub enum WarningKind {
        /// Unable to parse the duration.
        Invalid(String),

        /// The JSON value given is not an int.
        InvalidType,
    }

    impl fmt::Display for WarningKind {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                WarningKind::Invalid(err) => write!(f, "Unable to parse the duration: {err}"),
                WarningKind::InvalidType => write!(f, "The value should be a string."),
            }
        }
    }

    impl warning::Kind for WarningKind {
        fn id(&self) -> Cow<'static, str> {
            match self {
                WarningKind::Invalid(_) => "invalid".into(),
                WarningKind::InvalidType => "invalid_type".into(),
            }
        }
    }
}

/// A `chrono` UTC date time.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct DateTime(ChronoDateTime);

into_caveat!(DateTime);

impl DateTime {
    #[must_use]
    pub fn to_second_precision(self) -> DateTime {
        let naive_date_time = self
            .naive_local()
            .with_nanosecond(0)
            .expect("Resetting nanos to zero is always Some");

        DateTime(self.timezone().from_utc_datetime(&naive_date_time))
    }

    pub fn into_inner(self) -> ChronoDateTime {
        self.0
    }

    /// Returns an RFC 3339 date and time string such as `1996-12-19T16:39:57-08:00`.
    pub fn to_rfc3399(self) -> String {
        self.0.to_rfc3339()
    }
}

impl From<DateTime> for ChronoDateTime {
    fn from(value: DateTime) -> Self {
        value.0
    }
}

impl Deref for DateTime {
    type Target = ChronoDateTime;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<ChronoDateTime> for DateTime {
    fn from(value: ChronoDateTime) -> Self {
        DateTime(value)
    }
}

impl From<json::decode::WarningKind> for WarningKind {
    fn from(warn_kind: json::decode::WarningKind) -> Self {
        Self::Decode(warn_kind)
    }
}

impl json::FromJson<'_, '_> for DateTime {
    type WarningKind = WarningKind;

    fn from_json(elem: &json::Element<'_>) -> Verdict<Self, Self::WarningKind> {
        let mut warnings = warning::Set::new();
        let Some(s) = elem.as_raw_str() else {
            warnings.with_elem(WarningKind::InvalidType, elem);
            return Err(warnings);
        };

        let pending_str = s.has_escapes(elem).gather_warnings_into(&mut warnings);

        let s = match pending_str {
            json::decode::PendingStr::NoEscapes(s) => s,
            json::decode::PendingStr::HasEscapes(_) => {
                warnings.with_elem(WarningKind::ContainsEscapeCodes, elem);
                return Err(warnings);
            }
        };

        // First try parsing with a timezone, if that doesn't work try to parse without
        let err = match s.parse::<ChronoDateTime>() {
            Ok(date) => return Ok(Self(date).into_caveat(warnings)),
            Err(err) => err,
        };

        let Ok(date) = s.parse::<NaiveDateTime>() else {
            warnings.with_elem(WarningKind::Invalid(Error(err)), elem);
            return Err(warnings);
        };

        let datetime = Self(Utc.from_utc_datetime(&date));
        Ok(datetime.into_caveat(warnings))
    }
}

impl<'de> Deserialize<'de> for DateTime {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let date_string = String::deserialize(deserializer)?;

        // First try parsing with a timezone, if that doesn't work try to parse without
        let err = match date_string.parse::<ChronoDateTime>() {
            Ok(date) => return Ok(date.into()),
            Err(err) => err,
        };

        if let Ok(date) = date_string.parse::<NaiveDateTime>() {
            Ok(Utc.from_utc_datetime(&date).into())
        } else {
            Err(serde::de::Error::custom(err))
        }
    }
}

impl Serialize for DateTime {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.format("%Y-%m-%dT%H:%M:%SZ").to_string())
    }
}

impl fmt::Display for DateTime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.format("%Y-%m-%dT%H:%M:%SZ"))
    }
}

/// A OCPI specific local date, without a time.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize)]
pub struct Date(chrono::NaiveDate);

into_caveat!(Date);
into_caveat!(chrono::NaiveDate);

impl json::FromJson<'_, '_> for chrono::NaiveDate {
    type WarningKind = WarningKind;

    fn from_json(elem: &json::Element<'_>) -> Verdict<Self, Self::WarningKind> {
        let mut warnings = warning::Set::new();
        let Some(s) = elem.as_raw_str() else {
            warnings.with_elem(WarningKind::InvalidType, elem);
            return Err(warnings);
        };

        let pending_str = s.has_escapes(elem).gather_warnings_into(&mut warnings);

        let s = match pending_str {
            json::decode::PendingStr::NoEscapes(s) => s,
            json::decode::PendingStr::HasEscapes(_) => {
                warnings.with_elem(WarningKind::ContainsEscapeCodes, elem);
                return Err(warnings);
            }
        };

        let date = match s.parse::<chrono::NaiveDate>() {
            Ok(v) => v,
            Err(err) => {
                warnings.with_elem(WarningKind::Invalid(Error(err)), elem);
                return Err(warnings);
            }
        };

        Ok(date.into_caveat(warnings))
    }
}

impl json::FromJson<'_, '_> for Date {
    type WarningKind = WarningKind;

    fn from_json(elem: &json::Element<'_>) -> Verdict<Self, Self::WarningKind> {
        Ok(chrono::NaiveDate::from_json(elem)?.map(Self))
    }
}

impl<'de> Deserialize<'de> for Date {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::Error;

        let s = <String as Deserialize>::deserialize(deserializer)?;
        let date = chrono::NaiveDate::parse_from_str(&s, "%Y-%m-%d").map_err(D::Error::custom)?;

        Ok(Self(date))
    }
}

impl From<Date> for chrono::NaiveDate {
    fn from(value: Date) -> Self {
        value.0
    }
}

/// A OCPI specific local time, without a date.
#[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord, Serialize)]
pub struct Time(chrono::NaiveTime);

impl<'de> Deserialize<'de> for Time {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::Error;

        let s = <String as Deserialize>::deserialize(deserializer)?;
        let date = chrono::NaiveTime::parse_from_str(&s, "%H:%M").map_err(D::Error::custom)?;

        Ok(Self(date))
    }
}

impl From<Time> for chrono::NaiveTime {
    fn from(value: Time) -> Self {
        value.0
    }
}

into_caveat!(Time);
into_caveat!(chrono::NaiveTime);

impl json::FromJson<'_, '_> for chrono::NaiveTime {
    type WarningKind = time::WarningKind;

    fn from_json(elem: &json::Element<'_>) -> Verdict<Self, Self::WarningKind> {
        let mut warnings = warning::Set::new();
        let value = elem.as_value();

        let Some(s) = value.as_raw_str() else {
            warnings.with_elem(time::WarningKind::InvalidType, elem);
            return Err(warnings);
        };

        let pending_str = s.has_escapes(elem).gather_warnings_into(&mut warnings);

        let s = match pending_str {
            json::decode::PendingStr::NoEscapes(s) => s,
            json::decode::PendingStr::HasEscapes(_) => {
                warnings.with_elem(time::WarningKind::ContainsEscapeCodes, elem);
                return Err(warnings);
            }
        };

        let date = match chrono::NaiveTime::parse_from_str(s, "%H:%M") {
            Ok(v) => v,
            Err(err) => {
                warnings.with_elem(time::WarningKind::Invalid(err.to_string()), elem);
                return Err(warnings);
            }
        };

        Ok(date.into_caveat(warnings))
    }
}

impl json::FromJson<'_, '_> for Time {
    type WarningKind = time::WarningKind;

    fn from_json(elem: &json::Element<'_>) -> Verdict<Self, Self::WarningKind> {
        Ok(chrono::NaiveTime::from_json(elem)?.map(Self))
    }
}

pub mod time {
    //! The Warning infrastructure for the `Time` type.
    //!
    //! * See: [OCPI spec 2.2.1: Tariff Restriction Time](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#146-tariffrestrictions-class>)
    //! * See: [OCPI spec 2.1.1: Tariff Restriction Time](<https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_tariffs.md#45-tariffrestrictions-class>)

    use std::{borrow::Cow, fmt};

    use crate::{json, warning};

    #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
    pub enum WarningKind {
        /// Neither the day of the week does not need escape codes.
        ContainsEscapeCodes,

        /// The field at the path could not be decoded.
        Decode(json::decode::WarningKind),

        /// Unable to parse the time.
        Invalid(String),

        /// The JSON value given is not a string.
        InvalidType,
    }

    impl fmt::Display for WarningKind {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                WarningKind::ContainsEscapeCodes => write!(
                    f,
                    "The value contains escape codes but it does not need them."
                ),
                WarningKind::Decode(warning) => fmt::Display::fmt(warning, f),
                WarningKind::Invalid(msg) => write!(f, "Unable to parse the time: {msg}"),
                WarningKind::InvalidType => write!(f, "The value should be a string."),
            }
        }
    }

    impl warning::Kind for WarningKind {
        fn id(&self) -> Cow<'static, str> {
            match self {
                WarningKind::ContainsEscapeCodes => "contains_escape_codes".into(),
                WarningKind::Decode(kind) => format!("decode.{}", kind.id()).into(),
                WarningKind::Invalid(_) => "invalid".into(),
                WarningKind::InvalidType => "invalid_type".into(),
            }
        }
    }

    impl From<json::decode::WarningKind> for WarningKind {
        fn from(warn_kind: json::decode::WarningKind) -> Self {
            Self::Decode(warn_kind)
        }
    }
}

#[cfg(test)]
mod test {
    use std::str::FromStr;

    use crate::datetime::ChronoDateTime;

    use super::{DateTime, Error};

    #[test]
    const fn error_should_be_send_and_sync() {
        const fn f<T: Send + Sync>() {}

        f::<Error>();
    }

    impl FromStr for DateTime {
        type Err = <ChronoDateTime as FromStr>::Err;

        fn from_str(s: &str) -> Result<Self, Self::Err> {
            let dt = s.parse()?;
            Ok(Self(dt))
        }
    }
}

#[cfg(test)]
mod test_datetime_serde_deser {
    use chrono::{TimeZone, Timelike, Utc};

    use super::*;

    fn parse_timestamp(timestamp: &str) -> ChronoDateTime {
        serde_json::from_str::<DateTime>(timestamp).unwrap().into()
    }

    #[test]
    fn should_parse_utc_datetime() {
        assert_eq!(
            parse_timestamp(r#""2015-06-29T22:39:09Z""#),
            Utc.with_ymd_and_hms(2015, 6, 29, 22, 39, 9).unwrap()
        );
    }

    #[test]
    fn should_parse_timezone_to_utc() {
        assert_eq!(
            parse_timestamp(r#""2015-06-29T22:39:09+02:00""#),
            Utc.with_ymd_and_hms(2015, 6, 29, 20, 39, 9).unwrap()
        );
    }

    #[test]
    fn should_parse_timezone_naive_to_utc() {
        // This is a mess, but unfortunately OCPI 2.1.1 and 2.2 specify that datetimes without any
        // timezone specification are also allowed
        assert_eq!(
            parse_timestamp(r#""2015-06-29T22:39:09""#),
            Utc.with_ymd_and_hms(2015, 6, 29, 22, 39, 9).unwrap()
        );
    }

    #[test]
    fn should_format_as_utc() {
        let test_datetime: DateTime = Utc.with_ymd_and_hms(2015, 6, 29, 22, 39, 9).unwrap().into();

        assert_eq!(
            serde_json::to_string(&test_datetime).unwrap(),
            r#""2015-06-29T22:39:09Z""#
        );
    }

    #[test]
    fn should_format_without_partial_seconds() {
        let test_datetime: DateTime = Utc
            .with_ymd_and_hms(2015, 6, 29, 22, 39, 9)
            .unwrap()
            .with_nanosecond(12_345_678)
            .unwrap()
            .into();

        assert_eq!(
            serde_json::to_string(&test_datetime).unwrap(),
            r#""2015-06-29T22:39:09Z""#
        );
    }
}

#[cfg(test)]
mod test_datetime_from_json {
    use assert_matches::assert_matches;
    use chrono::{TimeZone, Utc};

    use crate::{
        json::{self, FromJson as _},
        Verdict,
    };

    use super::{DateTime, WarningKind};

    #[track_caller]
    fn parse_timestamp_from_json(json: &'static str) -> Verdict<DateTime, WarningKind> {
        let elem = json::parse(json).unwrap();
        let date_time_time = elem.find_field("start_date_time").unwrap();
        DateTime::from_json(date_time_time.element())
    }

    #[test]
    fn should_parse_utc_datetime() {
        const JSON: &str = r#"{ "start_date_time": "2015-06-29T22:39:09Z" }"#;

        let (datetime, warnings) = parse_timestamp_from_json(JSON).unwrap().into_parts();
        assert_matches!(*warnings, []);
        assert_eq!(
            datetime.into_inner(),
            Utc.with_ymd_and_hms(2015, 6, 29, 22, 39, 9).unwrap()
        );
    }

    #[test]
    fn should_parse_timezone_to_utc() {
        const JSON: &str = r#"{ "start_date_time": "2015-06-29T22:39:09+02:00" }"#;

        let (datetime, warnings) = parse_timestamp_from_json(JSON).unwrap().into_parts();
        assert_matches!(*warnings, []);
        assert_eq!(
            datetime.into_inner(),
            Utc.with_ymd_and_hms(2015, 6, 29, 20, 39, 9).unwrap()
        );
    }

    #[test]
    fn should_parse_timezone_naive_to_utc() {
        // This is a mess, but unfortunately OCPI 2.1.1 and 2.2 specify that datetimes without any
        // timezone specification are also allowed
        const JSON: &str = r#"{ "start_date_time": "2015-06-29T22:39:09" }"#;

        let (datetime, warnings) = parse_timestamp_from_json(JSON).unwrap().into_parts();
        assert_matches!(*warnings, []);

        assert_eq!(
            datetime.into_inner(),
            Utc.with_ymd_and_hms(2015, 6, 29, 22, 39, 9).unwrap()
        );
    }
}