Skip to main content

ocpi_tariffs/lint/tariff/
v2x.rs

1//! The collection of lints that apply to all supported OCPI versions.
2
3pub(crate) mod currency {
4    use tracing::{debug, instrument};
5
6    use crate::{
7        currency,
8        json::{self, FromJson as _},
9        warning::{self, GatherWarnings as _, IntoCaveat as _},
10        Verdict,
11    };
12
13    /// Validate the `country_code` field.
14    #[instrument(skip_all)]
15    pub(crate) fn lint(elem: &json::Element<'_>) -> Verdict<(), currency::Warning> {
16        let mut warnings = warning::Set::<currency::Warning>::new();
17        let code = currency::Code::from_json(elem)?.gather_warnings_into(&mut warnings);
18
19        debug!("code: {code:?}");
20
21        Ok(().into_caveat(warnings))
22    }
23}
24
25pub(crate) mod datetime {
26    use chrono::{DateTime, Utc};
27    use tracing::instrument;
28
29    use crate::{
30        json::{self, FromJson as _},
31        lint::tariff::Warning,
32        warning::{self, GatherWarnings as _, IntoCaveat as _},
33        Verdict,
34    };
35
36    /// Lint both `start_date_time` and `end_date_time`.
37    ///
38    /// It's allowed for the `start_date_time` to be equal to the `end_date_time` but the
39    /// `start_date_time` should not be greater than the `end_date_time`.
40    #[instrument(skip_all)]
41    pub(crate) fn lint_start_end(
42        start_date_time_elem: Option<&json::Element<'_>>,
43        end_date_time_elem: Option<&json::Element<'_>>,
44    ) -> Verdict<(), Warning> {
45        let mut warnings = warning::Set::<Warning>::new();
46
47        let start_date = start_date_time_elem
48            .map(DateTime::<Utc>::from_json)
49            .transpose()?
50            .gather_warnings_into(&mut warnings);
51        let end_date = end_date_time_elem
52            .map(DateTime::<Utc>::from_json)
53            .transpose()?
54            .gather_warnings_into(&mut warnings);
55
56        if let Some(((start, start_elem), end)) = start_date.zip(start_date_time_elem).zip(end_date)
57        {
58            if start > end {
59                warnings.with_elem(Warning::StartDateTimeIsAfterEndDateTime, start_elem);
60            }
61        }
62
63        Ok(().into_caveat(warnings))
64    }
65}
66
67pub mod time {
68    //! Linting and warning infrastructure for the `start_time` and `end_time` fields.
69    //!
70    //! * 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>)
71    //! * 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>)
72    use std::fmt;
73
74    use chrono::{NaiveTime, Timelike as _};
75
76    use crate::{
77        datetime, from_warning_all,
78        json::{self, FromJson as _},
79        warning::{self, GatherWarnings as _, IntoCaveat as _},
80        Verdict,
81    };
82
83    const DAY_BOUNDARY: HourMin = HourMin::new(0, 0);
84    const NEAR_END_OF_DAY: HourMin = HourMin::new(23, 59);
85
86    #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
87    pub enum Warning {
88        /// Both `start_time` and `end_time` are defined and contain the entire day,
89        /// making the restriction superfluous.
90        ContainsEntireDay,
91
92        /// The `end_time` restriction is set to `23::59`.
93        ///
94        /// The spec states: "To stop at end of the day use: 00:00.".
95        ///
96        /// * 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>)
97        EndTimeIsNearEndOfDay,
98
99        /// The `start_time` and `end_time` are equal and so the element is never valid.
100        NeverValid,
101
102        /// Each field needs to be a valid time.
103        DateTime(datetime::Warning),
104    }
105
106    impl fmt::Display for Warning {
107        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108            match self {
109                Warning::ContainsEntireDay => f.write_str("Both `start_time` and `end_time` are defined and contain the entire day."),
110                Warning::EndTimeIsNearEndOfDay => f.write_str(r#"
111The `end_time` restriction is set to `23::59`.
112
113The spec states: "To stop at end of the day use: 00:00.".
114
115See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#146-tariffrestrictions-class>"#),
116                Warning::NeverValid => f.write_str("The `start_time` and `end_time` are equal and so the element is never valid."),
117                Warning::DateTime(kind) => fmt::Display::fmt(kind, f),
118            }
119        }
120    }
121
122    impl crate::Warning for Warning {
123        fn id(&self) -> warning::Id {
124            match self {
125                Warning::ContainsEntireDay => warning::Id::from_static("contains_entire_day"),
126                Warning::EndTimeIsNearEndOfDay => {
127                    warning::Id::from_static("end_time_is_near_end_of_day")
128                }
129                Warning::NeverValid => warning::Id::from_static("never_valid"),
130                Warning::DateTime(kind) => kind.id(),
131            }
132        }
133    }
134
135    from_warning_all!(datetime::Warning => Warning::DateTime);
136
137    /// Lint the `start_time` and `end_time` field.
138    pub(crate) fn lint(
139        start_time_elem: Option<&json::Element<'_>>,
140        end_time_elem: Option<&json::Element<'_>>,
141    ) -> Verdict<(), Warning> {
142        let mut warnings = warning::Set::<Warning>::new();
143
144        let start = elem_to_time_hm(start_time_elem, &mut warnings)?;
145        let end = elem_to_time_hm(end_time_elem, &mut warnings)?;
146
147        // If both `start_time` and `end_time` are defined, then perform range linting.
148        if let Some(((start_time, start_elem), (end_time, end_elem))) = start.zip(end) {
149            if end_time == NEAR_END_OF_DAY {
150                warnings.with_elem(Warning::EndTimeIsNearEndOfDay, end_elem);
151            }
152
153            if start_time == DAY_BOUNDARY && is_day_end(end_time) {
154                warnings.with_elem(Warning::ContainsEntireDay, start_elem);
155            } else if start_time == end_time {
156                warnings.with_elem(Warning::NeverValid, start_elem);
157            }
158        } else if let Some((start_time, start_elem)) = start {
159            if start_time == DAY_BOUNDARY {
160                warnings.with_elem(Warning::ContainsEntireDay, start_elem);
161            }
162        } else if let Some((end_time, end_elem)) = end {
163            if is_day_end(end_time) {
164                warnings.with_elem(Warning::ContainsEntireDay, end_elem);
165            }
166        }
167
168        Ok(().into_caveat(warnings))
169    }
170
171    /// The time of day represented as hour and minute.
172    #[derive(Copy, Clone, Eq, PartialEq)]
173    struct HourMin {
174        /// Hour of the day. Stored as `u32` because that's what `chrono` returns from `NaiveTime::hour()`.
175        hour: u32,
176
177        /// Minute of the hour. Stored as `u32` because that's what `chrono` returns from `NaiveTime::minute()`.
178        min: u32,
179    }
180
181    impl HourMin {
182        /// Create a new `HourMin` time.
183        const fn new(hour: u32, min: u32) -> Self {
184            Self { hour, min }
185        }
186    }
187
188    /// Return true if the given time is close to or at the end of day.
189    fn is_day_end(time: HourMin) -> bool {
190        time == NEAR_END_OF_DAY || time == DAY_BOUNDARY
191    }
192
193    /// Return `Ok((HourMin, json::Element))` if the given [`json::Element`] is a valid [`NaiveTime`].
194    fn elem_to_time_hm<'a, 'bin>(
195        time_elem: Option<&'a json::Element<'bin>>,
196        warnings: &mut warning::Set<Warning>,
197    ) -> Result<Option<(HourMin, &'a json::Element<'bin>)>, warning::ErrorSet<Warning>> {
198        let v = time_elem.map(NaiveTime::from_json).transpose()?;
199
200        Ok(v.gather_warnings_into(warnings)
201            .map(|t| HourMin {
202                hour: t.hour(),
203                min: t.minute(),
204            })
205            .zip(time_elem))
206    }
207}
208
209pub mod elements {
210    //! The linting and Warning infrastructure for the `elements` field.
211    //!
212    //! * 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>)
213    //! * 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>)
214
215    use std::fmt;
216
217    use tracing::instrument;
218
219    use crate::{
220        from_warning_all,
221        json::{self, FieldsAsExt as _},
222        warning::{self, GatherWarnings as _, IntoCaveat as _},
223        Verdict,
224    };
225
226    use super::restrictions;
227
228    #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
229    pub enum Warning {
230        /// The array exists but is empty. This means that no day is allowed.
231        Empty,
232
233        /// The JSON value given is not an array.
234        InvalidType,
235
236        /// There is no `elements` array and it's required.
237        RequiredField,
238
239        /// The `restriction` field is nested in the `elements` array.
240        Restrictions(restrictions::Warning),
241    }
242
243    impl fmt::Display for Warning {
244        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245            match self {
246                Warning::Empty => write!(
247                    f,
248                    "An empty list of days means that no day is allowed. Is this what you want?"
249                ),
250                Warning::InvalidType => write!(f, "The value should be an array."),
251                Warning::RequiredField => write!(f, "The `$.elements` field is required."),
252                Warning::Restrictions(kind) => fmt::Display::fmt(kind, f),
253            }
254        }
255    }
256
257    impl crate::Warning for Warning {
258        fn id(&self) -> warning::Id {
259            match self {
260                Warning::Empty => warning::Id::from_static("empty"),
261                Warning::InvalidType => warning::Id::from_static("invalid_type"),
262                Warning::RequiredField => warning::Id::from_static("required"),
263                Warning::Restrictions(kind) => kind.id(),
264            }
265        }
266    }
267
268    from_warning_all!(restrictions::Warning => Warning::Restrictions);
269
270    /// Lint the `elements` field.
271    ///
272    /// * 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>)
273    #[instrument(skip_all)]
274    pub(crate) fn lint(elem: &json::Element<'_>) -> Verdict<(), Warning> {
275        let mut warnings = warning::Set::<Warning>::new();
276
277        // The `elements` field should be an array.
278        let Some(items) = elem.as_array() else {
279            return warnings.bail(Warning::InvalidType, elem);
280        };
281
282        // The `elements` array should contain at least one `Element`.
283        if items.is_empty() {
284            return warnings.bail(Warning::Empty, elem);
285        }
286
287        for ocpi_element in items {
288            let Some(fields) = ocpi_element.as_object_fields() else {
289                return warnings.bail(Warning::InvalidType, ocpi_element);
290            };
291
292            let restrictions = fields.find_field("restrictions");
293
294            // The `restrictions` field is optional
295            if let Some(field) = restrictions {
296                restrictions::lint(field.element()).gather_warnings_into(&mut warnings)?;
297            }
298        }
299
300        Ok(().into_caveat(warnings))
301    }
302}
303
304pub mod restrictions {
305    //! The linting and Warning infrastructure for the `restriction` field.
306    //!
307    //! * 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>)
308    //! * 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>)
309
310    use std::fmt;
311
312    use tracing::instrument;
313
314    use crate::{
315        from_warning_all,
316        json::{self, FieldsAsExt as _},
317        warning::{self, DeescalateError, GatherWarnings as _, IntoCaveat as _},
318        Verdict,
319    };
320
321    use super::{time, weekday};
322
323    #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
324    pub enum Warning {
325        /// The `day_of_week` field is nested in the `restrictions` object.
326        Weekday(weekday::Warning),
327
328        /// The JSON value given is not an array.
329        InvalidType,
330
331        /// The `start_time` and `end_time` fields are nested in the `restrictions` object.
332        Time(time::Warning),
333    }
334
335    impl fmt::Display for Warning {
336        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337            match self {
338                Warning::Weekday(kind) => fmt::Display::fmt(kind, f),
339                Warning::InvalidType => write!(f, "The value should be an object."),
340                Warning::Time(kind) => fmt::Display::fmt(kind, f),
341            }
342        }
343    }
344
345    impl crate::Warning for Warning {
346        fn id(&self) -> warning::Id {
347            match self {
348                Warning::Weekday(kind) => kind.id(),
349                Warning::InvalidType => warning::Id::from_static("invalid_type"),
350                Warning::Time(kind) => kind.id(),
351            }
352        }
353    }
354
355    from_warning_all!(
356        weekday::Warning => Warning::Weekday,
357        time::Warning => Warning::Time
358    );
359
360    /// Lint the `restrictions` field.
361    #[instrument(skip_all)]
362    pub(crate) fn lint(elem: &json::Element<'_>) -> Verdict<(), Warning> {
363        let mut warnings = warning::Set::<Warning>::new();
364
365        let Some(fields) = elem.as_object_fields() else {
366            return warnings.bail(Warning::InvalidType, elem);
367        };
368
369        let fields = fields.as_raw_map();
370
371        {
372            let start_time = fields.get("start_time").map(|e| &**e);
373            let end_time = fields.get("end_time").map(|e| &**e);
374
375            let _drop: Option<()> = time::lint(start_time, end_time)
376                .gather_warnings_into(&mut warnings)
377                .deescalate_error_into(&mut warnings);
378        }
379
380        {
381            let day_of_week = fields.get("day_of_week").map(|e| &**e);
382
383            let _drop: Option<()> = weekday::lint(day_of_week)
384                .gather_warnings_into(&mut warnings)
385                .deescalate_error_into(&mut warnings);
386        }
387
388        Ok(().into_caveat(warnings))
389    }
390}
391
392pub mod weekday {
393    //! Linting and warning infrastructure for the `day_of_week` field.
394    //!
395    //! * 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>)
396    //! * 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>)
397    //! * 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>)
398    //! * 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>)
399
400    use std::{collections::BTreeSet, fmt, sync::LazyLock};
401
402    use crate::{
403        from_warning_all,
404        json::{self, FromJson},
405        warning::{self, GatherWarnings as _, IntoCaveat as _},
406        Verdict, Weekday,
407    };
408
409    #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
410    pub enum Warning {
411        /// The list contains all days of the week.
412        ContainsEntireWeek,
413
414        /// Each field needs to be a valid weekday.
415        Weekday(crate::weekday::Warning),
416
417        /// There is at least one duplicate day.
418        Duplicates,
419
420        /// An empty array means that no day is allowed.
421        Empty,
422
423        /// The JSON value given is not an array.
424        InvalidType,
425
426        /// The days are unsorted.
427        Unsorted,
428    }
429
430    impl fmt::Display for Warning {
431        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
432            match self {
433                Warning::ContainsEntireWeek => write!(f, "All days of the week are defined. You can simply leave out the `day_of_week` field."),
434                Warning::Weekday(kind) => fmt::Display::fmt(kind, f),
435                Warning::Duplicates => write!(f, "There's at least one duplicate day."),
436                Warning::Empty => write!(
437                    f,
438                    "An empty list of days means that no day is allowed. Is this what you want?"
439                ),
440                Warning::InvalidType => write!(f, "The value should be an array."),
441                Warning::Unsorted => write!(f, "The days are unsorted."),
442            }
443        }
444    }
445
446    impl crate::Warning for Warning {
447        fn id(&self) -> warning::Id {
448            match self {
449                Warning::ContainsEntireWeek => warning::Id::from_static("contains_entire_week"),
450                Warning::Weekday(kind) => kind.id(),
451                Warning::Duplicates => warning::Id::from_static("duplicates"),
452                Warning::Empty => warning::Id::from_static("empty"),
453                Warning::InvalidType => warning::Id::from_static("invalid_type"),
454                Warning::Unsorted => warning::Id::from_static("unsorted"),
455            }
456        }
457    }
458
459    from_warning_all!(crate::weekday::Warning => Warning::Weekday);
460
461    /// Lint the `day_of_week` field.
462    pub(crate) fn lint(elem: Option<&json::Element<'_>>) -> Verdict<(), Warning> {
463        /// This is the correct order of the days of the week.
464        static ALL_DAYS_OF_WEEK: LazyLock<BTreeSet<Weekday>> = LazyLock::new(|| {
465            BTreeSet::from([
466                Weekday::Monday,
467                Weekday::Tuesday,
468                Weekday::Wednesday,
469                Weekday::Thursday,
470                Weekday::Friday,
471                Weekday::Saturday,
472                Weekday::Sunday,
473            ])
474        });
475
476        let mut warnings = warning::Set::<Warning>::new();
477
478        // The `day_of_week` field is optional.
479        let Some(elem) = elem else {
480            return Ok(().into_caveat(warnings));
481        };
482
483        // The `day_of_week` field should be an array.
484        let Some(items) = elem.as_array() else {
485            return warnings.bail(Warning::InvalidType, elem);
486        };
487
488        // Issue a warning if the `day_of_week` array is defined but empty.
489        // This can be a user misunderstanding.
490        if items.is_empty() {
491            warnings.with_elem(Warning::Empty, elem);
492            return Ok(().into_caveat(warnings));
493        }
494
495        // Convert each array item to a day and bail out on serious errors.
496        let days = items
497            .iter()
498            .map(Weekday::from_json)
499            .collect::<Result<Vec<_>, _>>()?;
500
501        // Collect warnings from the conversion of each array item to a day.
502        let days = days.gather_warnings_into(&mut warnings);
503
504        // Issue a warning if the days are not sorted.
505        if !days.is_sorted() {
506            warnings.with_elem(Warning::Unsorted, elem);
507        }
508
509        let day_set: BTreeSet<_> = days.iter().copied().collect();
510
511        // If the set length is less than the list, that means at least one duplicate was removed
512        // during the conversion.
513        if day_set.len() != days.len() {
514            warnings.with_elem(Warning::Duplicates, elem);
515        }
516
517        // Issue a warning of all days of the week are defined.
518        // This is equivalent to not defining the `day_of_week` array.
519        if day_set == *ALL_DAYS_OF_WEEK {
520            warnings.with_elem(Warning::ContainsEntireWeek, elem);
521        }
522
523        Ok(().into_caveat(warnings))
524    }
525}