ocpi-tariffs 0.43.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
//! The collection of lints that apply to all supported OCPI versions.

pub(crate) mod currency {
    use tracing::{debug, instrument};

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

    /// Validate the `country_code` field.
    #[instrument(skip_all)]
    pub(crate) fn lint(elem: &json::Element<'_>) -> Verdict<(), currency::Warning> {
        let mut warnings = warning::Set::<currency::Warning>::new();
        let code = currency::Code::from_json(elem)?.gather_warnings_into(&mut warnings);

        debug!("code: {code:?}");

        Ok(().into_caveat(warnings))
    }
}

pub(crate) mod datetime {
    use chrono::{DateTime, Utc};
    use tracing::instrument;

    use crate::{
        json::{self, FromJson as _},
        lint::tariff::Warning,
        warning::{self, GatherWarnings as _, IntoCaveat as _},
        Verdict,
    };

    /// Lint both `start_date_time` and `end_date_time`.
    ///
    /// It's allowed for the `start_date_time` to be equal to the `end_date_time` but the
    /// `start_date_time` should not be greater than the `end_date_time`.
    #[instrument(skip_all)]
    pub(crate) fn lint_start_end(
        start_date_time_elem: Option<&json::Element<'_>>,
        end_date_time_elem: Option<&json::Element<'_>>,
    ) -> Verdict<(), Warning> {
        let mut warnings = warning::Set::<Warning>::new();

        let start_date = start_date_time_elem
            .map(DateTime::<Utc>::from_json)
            .transpose()?
            .gather_warnings_into(&mut warnings);
        let end_date = end_date_time_elem
            .map(DateTime::<Utc>::from_json)
            .transpose()?
            .gather_warnings_into(&mut warnings);

        if let Some(((start, start_elem), end)) = start_date.zip(start_date_time_elem).zip(end_date)
        {
            if start > end {
                warnings.insert(Warning::StartDateTimeIsAfterEndDateTime, start_elem);
            }
        }

        Ok(().into_caveat(warnings))
    }
}

pub mod time {
    //! Linting and warning infrastructure for the `start_time` and `end_time` fields.
    //!
    //! * See: [OCPI spec 2.2.1: Tariff Restrictions](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#146-tariffrestrictions-class>)
    //! * See: [OCPI spec 2.1.1: Tariff Restrictions](<https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_tariffs.md#45-tariffrestrictions-class>)
    use std::fmt;

    use chrono::{NaiveTime, Timelike as _};

    use crate::{
        datetime, from_warning_all,
        json::{self, FromJson as _},
        warning::{self, GatherWarnings as _, IntoCaveat as _},
        Verdict,
    };

    const DAY_BOUNDARY: HourMin = HourMin::new(0, 0);
    const NEAR_END_OF_DAY: HourMin = HourMin::new(23, 59);

    #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
    pub enum Warning {
        /// Both `start_time` and `end_time` are defined and contain the entire day,
        /// making the restriction superfluous.
        ContainsEntireDay,

        /// The `end_time` restriction is set to `23::59`.
        ///
        /// The spec states: "To stop at end of the day use: 00:00.".
        ///
        /// * See: [OCPI spec 2.2.1: Tariff Restrictions](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#146-tariffrestrictions-class>)
        EndTimeIsNearEndOfDay,

        /// The `start_time` and `end_time` are equal and so the element is never valid.
        NeverValid,

        /// Each field needs to be a valid time.
        DateTime(datetime::Warning),
    }

    impl fmt::Display for Warning {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                Self::ContainsEntireDay => f.write_str("Both `start_time` and `end_time` are defined and contain the entire day."),
                Self::EndTimeIsNearEndOfDay => f.write_str(r#"
The `end_time` restriction is set to `23::59`.

The spec states: "To stop at end of the day use: 00:00.".

See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#146-tariffrestrictions-class>"#),
                Self::NeverValid => f.write_str("The `start_time` and `end_time` are equal and so the element is never valid."),
                Self::DateTime(kind) => fmt::Display::fmt(kind, f),
            }
        }
    }

    impl crate::Warning for Warning {
        fn id(&self) -> warning::Id {
            match self {
                Self::ContainsEntireDay => warning::Id::from_static("contains_entire_day"),
                Self::EndTimeIsNearEndOfDay => {
                    warning::Id::from_static("end_time_is_near_end_of_day")
                }
                Self::NeverValid => warning::Id::from_static("never_valid"),
                Self::DateTime(kind) => kind.id(),
            }
        }
    }

    from_warning_all!(datetime::Warning => Warning::DateTime);

    /// Lint the `start_time` and `end_time` field.
    pub(crate) fn lint(
        start_time_elem: Option<&json::Element<'_>>,
        end_time_elem: Option<&json::Element<'_>>,
    ) -> Verdict<(), Warning> {
        let mut warnings = warning::Set::<Warning>::new();

        let start = elem_to_time_hm(start_time_elem, &mut warnings)?;
        let end = elem_to_time_hm(end_time_elem, &mut warnings)?;

        // If both `start_time` and `end_time` are defined, then perform range linting.
        if let Some(((start_time, start_elem), (end_time, end_elem))) = start.zip(end) {
            if end_time == NEAR_END_OF_DAY {
                warnings.insert(Warning::EndTimeIsNearEndOfDay, end_elem);
            }

            if start_time == DAY_BOUNDARY && is_day_end(end_time) {
                warnings.insert(Warning::ContainsEntireDay, start_elem);
            } else if start_time == end_time {
                warnings.insert(Warning::NeverValid, start_elem);
            }
        } else if let Some((start_time, start_elem)) = start {
            if start_time == DAY_BOUNDARY {
                warnings.insert(Warning::ContainsEntireDay, start_elem);
            }
        } else if let Some((end_time, end_elem)) = end {
            if is_day_end(end_time) {
                warnings.insert(Warning::ContainsEntireDay, end_elem);
            }
        }

        Ok(().into_caveat(warnings))
    }

    /// The time of day represented as hour and minute.
    #[derive(Copy, Clone, Eq, PartialEq)]
    struct HourMin {
        /// Hour of the day. Stored as `u32` because that's what `chrono` returns from `NaiveTime::hour()`.
        hour: u32,

        /// Minute of the hour. Stored as `u32` because that's what `chrono` returns from `NaiveTime::minute()`.
        min: u32,
    }

    impl HourMin {
        /// Create a new `HourMin` time.
        const fn new(hour: u32, min: u32) -> Self {
            Self { hour, min }
        }
    }

    /// Return true if the given time is close to or at the end of day.
    fn is_day_end(time: HourMin) -> bool {
        time == NEAR_END_OF_DAY || time == DAY_BOUNDARY
    }

    /// Return `Ok((HourMin, json::Element))` if the given [`json::Element`] is a valid [`NaiveTime`].
    fn elem_to_time_hm<'a, 'buf>(
        time_elem: Option<&'a json::Element<'buf>>,
        warnings: &mut warning::Set<Warning>,
    ) -> Result<Option<(HourMin, &'a json::Element<'buf>)>, warning::ErrorSet<Warning>> {
        let v = time_elem.map(NaiveTime::from_json).transpose()?;

        Ok(v.gather_warnings_into(warnings)
            .map(|t| HourMin {
                hour: t.hour(),
                min: t.minute(),
            })
            .zip(time_elem))
    }
}

pub mod elements {
    //! The linting and Warning infrastructure for the `elements` field.
    //!
    //! * See: [OCPI spec 2.2.1: Tariff Element](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#144-tariffelement-class>)
    //! * See: [OCPI spec 2.1.1: Tariff Element](<https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_tariffs.md#43-tariffelement-class>)

    use std::fmt;

    use tracing::instrument;

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

    use super::restrictions;

    #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
    pub enum Warning {
        /// The array exists but is empty. This means that no day is allowed.
        Empty,

        /// The JSON value given is not an array.
        InvalidType { type_found: json::ValueKind },

        /// There is no `elements` array and it's required.
        RequiredField,

        /// The `restriction` field is nested in the `elements` array.
        Restrictions(restrictions::Warning),
    }

    impl Warning {
        fn invalid_type(elem: &json::Element<'_>) -> Self {
            Self::InvalidType {
                type_found: elem.value().kind(),
            }
        }
    }

    impl fmt::Display for Warning {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                Self::Empty => write!(
                    f,
                    "An empty list of days means that no day is allowed. Is this what you want?"
                ),
                Self::InvalidType { type_found } => {
                    write!(f, "The value should be an array but is `{type_found}`")
                }
                Self::RequiredField => write!(f, "The `$.elements` field is required."),
                Self::Restrictions(kind) => fmt::Display::fmt(kind, f),
            }
        }
    }

    impl crate::Warning for Warning {
        fn id(&self) -> warning::Id {
            match self {
                Self::Empty => warning::Id::from_static("empty"),
                Self::InvalidType { .. } => warning::Id::from_static("invalid_type"),
                Self::RequiredField => warning::Id::from_static("required"),
                Self::Restrictions(kind) => kind.id(),
            }
        }
    }

    from_warning_all!(restrictions::Warning => Warning::Restrictions);

    /// Lint the `elements` field.
    ///
    /// * See: [OCPI v2.2.1 Tariff Element](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#mod_tariffs_tariffelement_class>)
    #[instrument(skip_all)]
    pub(crate) fn lint(elem: &json::Element<'_>) -> Verdict<(), Warning> {
        let mut warnings = warning::Set::<Warning>::new();

        // The `elements` field should be an array.
        let Some(items) = elem.as_array() else {
            return warnings.bail(Warning::invalid_type(elem), elem);
        };

        // The `elements` array should contain at least one `Element`.
        if items.is_empty() {
            return warnings.bail(Warning::Empty, elem);
        }

        for ocpi_element in items {
            let Some(fields) = ocpi_element.as_object_fields() else {
                return warnings.bail(Warning::invalid_type(elem), ocpi_element);
            };

            let restrictions = fields.find_field("restrictions");

            // The `restrictions` field is optional
            if let Some(field) = restrictions {
                restrictions::lint(field.element()).gather_warnings_into(&mut warnings)?;
            }
        }

        Ok(().into_caveat(warnings))
    }
}

pub mod restrictions {
    //! The linting and Warning infrastructure for the `restriction` field.
    //!
    //! * See: [OCPI spec 2.2.1: Tariff Restrictions](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#mod_tariffs_tariffrestrictions_class>)
    //! * See: [OCPI spec 2.1.1: Tariff Restrictions](<https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_tariffs.md#45-tariffrestrictions-class>)

    use std::fmt;

    use tracing::instrument;

    use crate::{
        from_warning_all,
        json::{self, FieldsAsExt as _},
        warning::{self, DeescalateError, GatherWarnings as _, IntoCaveat as _},
        Verdict,
    };

    use super::{time, weekday};

    #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
    pub enum Warning {
        /// The `day_of_week` field is nested in the `restrictions` object.
        Weekday(weekday::Warning),

        /// The JSON value given is not an object.
        InvalidType { type_found: json::ValueKind },

        /// The `start_time` and `end_time` fields are nested in the `restrictions` object.
        Time(time::Warning),
    }

    impl Warning {
        fn invalid_type(elem: &json::Element<'_>) -> Self {
            Self::InvalidType {
                type_found: elem.value().kind(),
            }
        }
    }

    impl fmt::Display for Warning {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                Self::Weekday(kind) => fmt::Display::fmt(kind, f),
                Self::InvalidType { type_found } => {
                    write!(f, "The value should be an object but is `{type_found}`")
                }
                Self::Time(kind) => fmt::Display::fmt(kind, f),
            }
        }
    }

    impl crate::Warning for Warning {
        fn id(&self) -> warning::Id {
            match self {
                Self::Weekday(kind) => kind.id(),
                Self::InvalidType { .. } => warning::Id::from_static("invalid_type"),
                Self::Time(kind) => kind.id(),
            }
        }
    }

    from_warning_all!(
        weekday::Warning => Warning::Weekday,
        time::Warning => Warning::Time
    );

    /// Lint the `restrictions` field.
    #[instrument(skip_all)]
    pub(crate) fn lint(elem: &json::Element<'_>) -> Verdict<(), Warning> {
        let mut warnings = warning::Set::<Warning>::new();

        let Some(fields) = elem.as_object_fields() else {
            return warnings.bail(Warning::invalid_type(elem), elem);
        };

        let fields = fields.as_raw_map();

        {
            let start_time = fields.get("start_time").map(|e| &**e);
            let end_time = fields.get("end_time").map(|e| &**e);

            let _drop: Option<()> = time::lint(start_time, end_time)
                .gather_warnings_into(&mut warnings)
                .deescalate_error_into(&mut warnings);
        }

        {
            let day_of_week = fields.get("day_of_week").map(|e| &**e);

            let _drop: Option<()> = weekday::lint(day_of_week)
                .gather_warnings_into(&mut warnings)
                .deescalate_error_into(&mut warnings);
        }

        Ok(().into_caveat(warnings))
    }
}

pub mod weekday {
    //! Linting and warning infrastructure for the `day_of_week` field.
    //!
    //! * See: [OCPI spec 2.2.1: Tariff Restrictions](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#146-tariffrestrictions-class>)
    //! * See: [OCPI spec 2.2.1: Tariff DayOfWeek](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#mod_tariffs_dayofweek_enum>)
    //! * See: [OCPI spec 2.1.1: Tariff Restrictions](<https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_tariffs.md#45-tariffrestrictions-class>)
    //! * See: [OCPI spec 2.1.1: Tariff DayOfWeek](<https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_tariffs.md#41-dayofweek-enum>)

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

    use crate::{
        from_warning_all,
        json::{self, FromJson},
        warning::{self, GatherWarnings as _, IntoCaveat as _},
        Verdict, Weekday,
    };

    #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
    pub enum Warning {
        /// The list contains all days of the week.
        ContainsEntireWeek,

        /// Each field needs to be a valid weekday.
        Weekday(crate::weekday::Warning),

        /// There is at least one duplicate day.
        Duplicates,

        /// An empty array means that no day is allowed.
        Empty,

        /// The JSON value given is not an array.
        InvalidType { type_found: json::ValueKind },

        /// The days are unsorted.
        Unsorted,
    }

    impl Warning {
        fn invalid_type(elem: &json::Element<'_>) -> Self {
            Self::InvalidType {
                type_found: elem.value().kind(),
            }
        }
    }

    impl fmt::Display for Warning {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                Self::ContainsEntireWeek => write!(f, "All days of the week are defined. You can simply leave out the `day_of_week` field."),
                Self::Weekday(kind) => fmt::Display::fmt(kind, f),
                Self::Duplicates => write!(f, "There's at least one duplicate day."),
                Self::Empty => write!(
                    f,
                    "An empty list of days means that no day is allowed. Is this what you want?"
                ),
                Self::InvalidType { type_found } => {
                    write!(f, "The value should be an array but is `{type_found}`")
                }
                Self::Unsorted => write!(f, "The days are unsorted."),
            }
        }
    }

    impl crate::Warning for Warning {
        fn id(&self) -> warning::Id {
            match self {
                Self::ContainsEntireWeek => warning::Id::from_static("contains_entire_week"),
                Self::Weekday(kind) => kind.id(),
                Self::Duplicates => warning::Id::from_static("duplicates"),
                Self::Empty => warning::Id::from_static("empty"),
                Self::InvalidType { .. } => warning::Id::from_static("invalid_type"),
                Self::Unsorted => warning::Id::from_static("unsorted"),
            }
        }
    }

    from_warning_all!(crate::weekday::Warning => Warning::Weekday);

    /// Lint the `day_of_week` field.
    pub(crate) fn lint(elem: Option<&json::Element<'_>>) -> Verdict<(), Warning> {
        /// This is the correct order of the days of the week.
        static ALL_DAYS_OF_WEEK: LazyLock<BTreeSet<Weekday>> = LazyLock::new(|| {
            BTreeSet::from([
                Weekday::Monday,
                Weekday::Tuesday,
                Weekday::Wednesday,
                Weekday::Thursday,
                Weekday::Friday,
                Weekday::Saturday,
                Weekday::Sunday,
            ])
        });

        let mut warnings = warning::Set::<Warning>::new();

        // The `day_of_week` field is optional.
        let Some(elem) = elem else {
            return Ok(().into_caveat(warnings));
        };

        // The `day_of_week` field should be an array.
        let Some(items) = elem.as_array() else {
            return warnings.bail(Warning::invalid_type(elem), elem);
        };

        // Issue a warning if the `day_of_week` array is defined but empty.
        // This can be a user misunderstanding.
        if items.is_empty() {
            warnings.insert(Warning::Empty, elem);
            return Ok(().into_caveat(warnings));
        }

        // Convert each array item to a day and bail out on serious errors.
        let days = items
            .iter()
            .map(Weekday::from_json)
            .collect::<Result<Vec<_>, _>>()?;

        // Collect warnings from the conversion of each array item to a day.
        let days = days.gather_warnings_into(&mut warnings);

        // Issue a warning if the days are not sorted.
        if !days.is_sorted() {
            warnings.insert(Warning::Unsorted, elem);
        }

        let day_set: BTreeSet<_> = days.iter().copied().collect();

        // If the set length is less than the list, that means at least one duplicate was removed
        // during the conversion.
        if day_set.len() != days.len() {
            warnings.insert(Warning::Duplicates, elem);
        }

        // Issue a warning of all days of the week are defined.
        // This is equivalent to not defining the `day_of_week` array.
        if day_set == *ALL_DAYS_OF_WEEK {
            warnings.insert(Warning::ContainsEntireWeek, elem);
        }

        Ok(().into_caveat(warnings))
    }
}