ocpi-tariffs 0.55.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
//! Timestamps are formatted as a string with a max length of 25 chars. Each timestamp follows RFC 3339,
//! with some additional limitations. All timestamps are expected to be in UTC. The absence of the
//! timezone designator implies a UTC timestamp. Fractional seconds may be used.
//!
//! # Examples
//!
//! Example of how timestamps should be formatted in OCPI, other formats/patterns are not allowed:
//!
//! - `"2015-06-29T20:39:09Z"`
//! - `"2015-06-29T20:39:09"`
//! - `"2016-12-29T17:45:09.2Z"`
//! - `"2016-12-29T17:45:09.2"`
//! - `"2018-01-01T01:08:01.123Z"`
//! - `"2018-01-01T01:08:01.123"`

#[cfg(test)]
pub(crate) mod test;

#[cfg(test)]
mod test_from_schema;

#[cfg(test)]
mod test_parse_date;

#[cfg(test)]
mod test_parse_date_time;

#[cfg(test)]
mod test_parse_time;

use std::fmt;

use jiff::{Timestamp, civil, tz};

use crate::{
    LowerSchema, json,
    schema::{self, HasElement as _},
    warning,
};

/// Read a calendar date matching `[ ]*[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}[ ]*`.
///
/// OCPI writes a date as `YYYY-MM-DD`. Two forms this function reads leave the date unambiguous: a
/// month or day without its leading zero, such as `2023-1-5`, and spaces around the date. The
/// schema walk reports both as `schema::Warning::IncorrectFormat`. Any four-digit year is read,
/// including `0023`.
///
/// This function rejects a year with a sign and a year of fewer than four digits, because neither
/// reads unambiguously. A `-` makes the year negative. A short year, such as the `23` of
/// `23-01-05`, may not mean the year it reads as. This function rejects a `+` too, so that it
/// reads no sign at all.
///
/// `jiff`'s parser for `civil::Date` reads `20230105` and `+002023-01-05`, and rejects
/// `2023-1-5` and spaces around the date. So this function sets the forms itself, as
/// [`parse_date_time`] does.
///
/// The date lowering and the schema walk both read a date through this function, so the walk
/// proposes a date only when the library reads one, and proposes the date the library read.
pub(crate) fn parse_date(s: &str) -> Result<civil::Date, DateError> {
    let s = s.trim_matches(' ');

    let mut parts = s.split('-');
    let (Some(year), Some(month), Some(day), None) =
        (parts.next(), parts.next(), parts.next(), parts.next())
    else {
        return Err(DateError::Syntax);
    };

    if !digits(year, 4..=4) || !digits(month, 1..=2) || !digits(day, 1..=2) {
        return Err(DateError::Syntax);
    }

    // The year is 4 ASCII digits, which always fit an `i16`. The month and day are each 1 or 2
    // ASCII digits, which always fit an `i8`. So this `else` arm is unreachable. It returns
    // `Syntax` rather than unwrapping because this crate does not panic.
    let (Ok(year), Ok(month), Ok(day)) = (year.parse(), month.parse(), day.parse()) else {
        return Err(DateError::Syntax);
    };

    let Ok(date) = civil::Date::new(year, month, day) else {
        return Err(DateError::NotACalendarDate);
    };

    Ok(date)
}

/// Read a time of day matching `[ ]*[0-9]{1,2}:[0-9]{1,2}[ ]*`.
///
/// OCPI writes `start_time` and `end_time` as `HH:MM`. Two forms this function reads leave the
/// time unambiguous: an hour or minute without its leading zero, such as `9:5`, and spaces around
/// the time. The schema walk reports both as `schema::Warning::IncorrectFormat`.
///
/// This function rejects a space inside the time, as in `09: 00`. OCPI's `HH:MM` has no such
/// space, and the space isn't one of the two forms above that this function reads anyway.
///
/// `jiff`'s parser for `civil::Time` reads `0900` and a bare hour such as `09`, and rejects
/// `9:5` and spaces around the time. So this function sets the forms itself, as
/// [`parse_date_time`] does.
///
/// The time lowering, the schema walk and the fix for `lint::tariff::Warning::ContainsEntireDay`
/// all read a time through this function. So the walk proposes a time only when the library reads
/// one, and the fix removes a bound only when the library reads it as midnight.
pub(crate) fn parse_time(s: &str) -> Result<civil::Time, TimeError> {
    let s = s.trim_matches(' ');

    let Some((hour, minute)) = s.split_once(':') else {
        return Err(TimeError::Syntax);
    };

    if !digits(hour, 1..=2) || !digits(minute, 1..=2) {
        return Err(TimeError::Syntax);
    }

    // Each part is 1 or 2 ASCII digits, which always fits an `i8`, so this `else` arm is
    // unreachable. It returns `Syntax` rather than unwrapping because this crate does not panic.
    let (Ok(hour), Ok(minute)) = (hour.parse(), minute.parse()) else {
        return Err(TimeError::Syntax);
    };

    let Ok(time) = civil::Time::new(hour, minute, 0, 0) else {
        return Err(TimeError::NotATimeOfDay);
    };

    Ok(time)
}

/// Read a datetime and return the instant it names, in UTC.
///
/// OCPI writes a datetime following RFC 3339, as `2015-06-29T20:39:09Z`, and a datetime without
/// an offset is in UTC. This function reads:
///
/// - a date as [`parse_date`] reads it, so a month or day may lack its leading zero
/// - a `T`, a `t` or one space between the date and the time
/// - a time written `H:M:S`, each field one or two digits, optionally followed by a `.` and 1 to 9
///   fractional digits
/// - an optional `Z`, `z` or `±HH:MM` offset directly after the time
/// - spaces around the datetime
///
/// This function rejects these forms, none of which OCPI writes:
///
/// - a signed or short year, such as `+2024` or `24`
/// - an offset without its colon, such as `+0100`
/// - `UTC` as an offset
/// - a space before the offset
/// - more than one space between the date and the time
/// - more than 9 fractional digits
///
/// `jiff`'s parser for `Timestamp` reads an offset without its colon, such as `+0100`,
/// which OCPI doesn't allow. It rejects a month with one digit, which a real CDR writes. So this
/// function sets the forms itself.
///
/// RFC 3339 allows a second of `60` for a leap second, and this function rejects it. A
/// timestamp has no instant for that second, so reading it means choosing another instant. jiff's
/// parser chooses `59`, the second before the leap second. Rejecting the leap second keeps that
/// choice from deciding when a session started or ended.
///
/// The last instant this function returns is `9999-12-30T22:00:00.999999999Z`, and it reads
/// any later instant as that one.
pub(crate) fn parse_date_time(s: &str) -> Result<Timestamp, DateTimeError> {
    let s = s.trim_matches(' ');

    let Some((date, time_and_offset)) = s.split_once(['T', 't', ' ']) else {
        return Err(DateTimeError::Syntax);
    };

    let date = match parse_date(date) {
        Ok(date) => date,
        Err(DateError::Syntax) => return Err(DateTimeError::Syntax),
        Err(DateError::NotACalendarDate) => return Err(DateTimeError::NotACalendarDate),
    };

    // A time is digits, `:` and `.`, so the first `+` or `-` after the date starts the offset.
    // One that falls inside a malformed time leaves a time the field checks below reject.
    let (time, offset) = if let Some(time) = time_and_offset.strip_suffix(['Z', 'z']) {
        (time, None)
    } else if let Some(sign_at) = time_and_offset.find(['+', '-']) {
        let (time, offset) = time_and_offset.split_at(sign_at);
        (time, Some(offset))
    } else {
        (time_and_offset, None)
    };

    let mut fields = time.split(':');
    let (Some(hour), Some(minute), Some(second), None) =
        (fields.next(), fields.next(), fields.next(), fields.next())
    else {
        return Err(DateTimeError::Syntax);
    };

    let (second, fraction) = match second.split_once('.') {
        Some((second, fraction)) => (second, Some(fraction)),
        None => (second, None),
    };

    if !digits(hour, 1..=2) || !digits(minute, 1..=2) || !digits(second, 1..=2) {
        return Err(DateTimeError::Syntax);
    }

    let fraction = match fraction {
        // A datetime without a fraction is read as one with the fraction `.0`.
        None => "0",
        Some(fraction) if digits(fraction, 1..=9) => fraction,
        Some(_) => return Err(DateTimeError::Syntax),
    };

    // The hour, minute and second are each 1 or 2 ASCII digits, which always fit an `i8`. The
    // fraction is 1 to 9 ASCII digits, which always fit an `i32`. So this `else` arm is
    // unreachable. It returns `Syntax` rather than unwrapping because this crate does not panic.
    let (Ok(hour), Ok(minute), Ok(second), Ok(fraction_value)) = (
        hour.parse(),
        minute.parse(),
        second.parse(),
        fraction.parse::<i32>(),
    ) else {
        return Err(DateTimeError::Syntax);
    };

    // A fraction of n digits counts units of 10^-n seconds, so multiplying it by 10^(9 - n)
    // gives nanoseconds: `.2` is 200,000,000. A fraction has 1 to 9 digits, so the product is
    // under 1,000,000,000 and this `else` arm is unreachable. It returns `Syntax` rather than
    // unwrapping because this crate does not panic.
    let nanoseconds = u32::try_from(fraction.len())
        .ok()
        .and_then(|fraction_digits| 9_u32.checked_sub(fraction_digits))
        .and_then(|zeros| 10_i32.checked_pow(zeros))
        .and_then(|scale| fraction_value.checked_mul(scale));
    let Some(nanoseconds) = nanoseconds else {
        return Err(DateTimeError::Syntax);
    };

    // RFC 3339 writes a leap second as a second of `60`, which `civil::Time::new` rejects.
    let Ok(time) = civil::Time::new(hour, minute, second, nanoseconds) else {
        return Err(DateTimeError::NotATimeOfDay);
    };

    let date_time = date.to_datetime(time);

    // A datetime without an offset is in UTC.
    let offset = offset.unwrap_or("+00:00");

    let (sign, hours_and_minutes) = offset.split_at(1);
    let Some((hours, minutes)) = hours_and_minutes.split_once(':') else {
        return Err(DateTimeError::Syntax);
    };

    if !digits(hours, 2..=2) || !digits(minutes, 2..=2) {
        return Err(DateTimeError::Syntax);
    }

    // Each part is 2 ASCII digits, which always fits an `i8`, so this `else` arm is
    // unreachable. It returns `Syntax` rather than unwrapping because this crate does not panic.
    let (Ok(hours), Ok(minutes)) = (hours.parse(), minutes.parse()) else {
        return Err(DateTimeError::Syntax);
    };

    // A `tz::Offset` holds up to 25:59:59, so building one directly would read `+24:00`.
    // This function allows an offset only within the range of a time of day, so
    // `civil::Time::new` checks the hours and minutes.
    let Ok(offset) = civil::Time::new(hours, minutes, 0, 0) else {
        return Err(DateTimeError::NotAnOffset);
    };

    // An offset is under 24 hours, which a `tz::Offset` always holds, so this `else` arm
    // is unreachable. It returns `NotAnOffset` rather than unwrapping because this crate does not
    // panic.
    let Ok(offset) = tz::Offset::try_from(offset.duration_since(civil::Time::midnight())) else {
        return Err(DateTimeError::NotAnOffset);
    };

    let offset = if sign == "+" { offset } else { offset.negate() };

    // A `jiff::Timestamp` holds no instant after `9999-12-30T22:00:00.999999999Z`, and a
    // tariff may write a later one, such as an `end_date_time` of `9999-12-31T23:59:59Z` to mean
    // it never expires. Rejecting that instant would reject the tariff, so this function reads it
    // as `Timestamp::MAX`. No session reaches either instant, so the tariff prices the same.
    // A year is at least `0000`, so no datetime falls before `Timestamp::MIN`.
    let timestamp = offset.to_timestamp(date_time).unwrap_or(Timestamp::MAX);

    Ok(timestamp)
}

/// Return whether `text` is only ASCII digits and has a length within `lengths`.
fn digits(text: &str, lengths: std::ops::RangeInclusive<usize>) -> bool {
    lengths.contains(&text.len()) && text.bytes().all(|b| b.is_ascii_digit())
}

/// Why [`parse_time`] could not parse the time.
#[derive(Debug, Eq, PartialEq)]
pub(crate) enum TimeError {
    /// The text does not match `[ ]*[0-9]{1,2}:[0-9]{1,2}[ ]*`.
    Syntax,

    /// The numbers don't name a time of day, as in `24:00` or `09:60`.
    NotATimeOfDay,
}

impl fmt::Display for TimeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Syntax => f.write_str("expected a time written as `HH:MM`"),
            Self::NotATimeOfDay => f.write_str("the time does not exist in a day"),
        }
    }
}

/// Why [`parse_date`] could not parse the date.
#[derive(Debug, Eq, PartialEq)]
pub(crate) enum DateError {
    /// The text does not match `[ ]*[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}[ ]*`.
    Syntax,

    /// The numbers don't name a calendar date, as in `2023-02-30`.
    NotACalendarDate,
}

impl fmt::Display for DateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Syntax => f.write_str("expected a date written as `YYYY-MM-DD`"),
            Self::NotACalendarDate => f.write_str("the date does not exist in the calendar"),
        }
    }
}

/// Why [`parse_date_time`] could not parse the datetime.
#[derive(Debug, Eq, PartialEq)]
pub(crate) enum DateTimeError {
    /// The text is not in a form [`parse_date_time`] reads.
    Syntax,

    /// The date doesn't name a calendar date, as in `2023-02-30T00:00:00Z`.
    NotACalendarDate,

    /// The time doesn't name a time of day, as in `2023-01-05T24:00:00Z` or the leap second
    /// `2016-12-31T23:59:60Z`.
    NotATimeOfDay,

    /// The offset is 24 hours or more, or its minutes are 60 or more, as in `+24:00`.
    NotAnOffset,
}

impl fmt::Display for DateTimeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Syntax => f.write_str("expected a datetime written as `YYYY-MM-DDTHH:MM:SSZ`"),
            Self::NotACalendarDate => f.write_str("the date does not exist in the calendar"),
            Self::NotATimeOfDay => f.write_str("the time does not exist in a day"),
            Self::NotAnOffset => f.write_str("the offset is not between -23:59 and +23:59"),
        }
    }
}

/// The warnings that can happen when parsing or linting a date, a time or a datetime.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum Warning {
    /// The datetime does not need to contain escape codes.
    ContainsEscapeCodes,

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

    /// The datetime is not valid.
    ///
    /// Timestamps are formatted as a string with a max length of 25 chars. Each timestamp follows RFC 3339,
    /// with some additional limitations. All timestamps are expected to be in UTC. The absence of the
    /// timezone designator implies a UTC timestamp. Fractional seconds may be used.
    ///
    /// # Examples
    ///
    /// Example of how timestamps should be formatted in OCPI, other formats/patterns are not allowed:
    ///
    /// - `"2015-06-29T20:39:09Z"`
    /// - `"2015-06-29T20:39:09"`
    /// - `"2016-12-29T17:45:09.2Z"`
    /// - `"2016-12-29T17:45:09.2"`
    /// - `"2018-01-01T01:08:01.123Z"`
    /// - `"2018-01-01T01:08:01.123"`
    Invalid(String),
}

impl fmt::Display for Warning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ContainsEscapeCodes => {
                f.write_str("The value contains escape codes but it does not need them.")
            }
            Self::Decode(warning) => fmt::Display::fmt(warning, f),
            Self::Invalid(err) => write!(f, "The value is not valid: {err}"),
        }
    }
}

impl crate::Warning for Warning {
    fn id(&self) -> warning::Id {
        match self {
            Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
            Self::Decode(kind) => kind.id(),
            Self::Invalid(_) => warning::Id::from_static("invalid"),
        }
    }
}

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

impl<'buf> LowerSchema<'buf, schema::Str<'buf>> for Timestamp {
    type Warning = Warning;

    fn lower_schema(
        source: &schema::Str<'buf>,
        warnings: &mut dyn warning::Gather<Warning>,
    ) -> Result<Self, warning::Error<Warning>> {
        let elem = source.element();

        let pending_str = source
            .value()
            .has_escapes(elem, &mut warning::Converting::new(warnings));

        let s = match pending_str {
            json::PendingStr::NoEscapes(s) => s,
            json::PendingStr::HasEscapes => {
                return Err(warning::Error::new(elem, Warning::ContainsEscapeCodes));
            }
        };

        let date_time = match parse_date_time(s) {
            Ok(v) => v,
            Err(err) => {
                return Err(warning::Error::new(elem, Warning::Invalid(err.to_string())));
            }
        };

        Ok(date_time)
    }
}

impl<'buf> LowerSchema<'buf, schema::Str<'buf>> for civil::Date {
    type Warning = Warning;

    fn lower_schema(
        source: &schema::Str<'buf>,
        warnings: &mut dyn warning::Gather<Warning>,
    ) -> Result<Self, warning::Error<Warning>> {
        let elem = source.element();

        // The schema confirmed the value is a string, so there is no kind check; its
        // content is read directly.
        let pending_str = source
            .value()
            .has_escapes(elem, &mut warning::Converting::new(warnings));

        let s = match pending_str {
            json::PendingStr::NoEscapes(s) => s,
            json::PendingStr::HasEscapes => {
                return Err(warning::Error::new(elem, Warning::ContainsEscapeCodes));
            }
        };

        let date = match parse_date(s) {
            Ok(v) => v,
            Err(err) => {
                return Err(warning::Error::new(elem, Warning::Invalid(err.to_string())));
            }
        };

        Ok(date)
    }
}

impl<'buf> LowerSchema<'buf, schema::Str<'buf>> for civil::Time {
    type Warning = Warning;

    fn lower_schema(
        source: &schema::Str<'buf>,
        warnings: &mut dyn warning::Gather<Warning>,
    ) -> Result<Self, warning::Error<Warning>> {
        let elem = source.element();

        // The schema confirmed the value is a string, so there is no kind check; its
        // content is read directly.
        let pending_str = source
            .value()
            .has_escapes(elem, &mut warning::Converting::new(warnings));

        let s = match pending_str {
            json::PendingStr::NoEscapes(s) => s,
            json::PendingStr::HasEscapes => {
                return Err(warning::Error::new(elem, Warning::ContainsEscapeCodes));
            }
        };

        let date = match parse_time(s) {
            Ok(v) => v,
            Err(err) => {
                return Err(warning::Error::new(elem, Warning::Invalid(err.to_string())));
            }
        };

        Ok(date)
    }
}