ocpi-tariffs 0.52.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
//! Types for parsing v2.1.1 tariffs.

#[cfg(test)]
mod test_from_schema;

use chrono::{Duration, NaiveDate, NaiveTime, TimeDelta};
use rust_decimal::Decimal;

use super::{v221, Warning};
use crate::{
    currency,
    duration::Seconds,
    energy::{Kw, Kwh},
    money::VatOrigin,
    number::FromDecimal as _,
    schema, string,
    tariff::v2x,
    warning::{self, GatherWarnings as _, IntoCaveat as _, IntoInfallible as _},
    FromSchema, Money, Verdict, Weekday,
};

/// A tariff description used to generate a CDR.
///
/// See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#131-tariff-object>.
///
/// We don't parse the `type`, `tariff_alt_text`, `tariff_alt_url`, `energy_mix` or `last_updated` fields
/// as they do not affect the generation of the CDR.
#[derive(Debug)]
pub(crate) struct Tariff<'buf> {
    /// Uniquely identifies the tariff within the CPO's platform (and sub-operator platforms).
    pub id: string::CiMaxLen<'buf, 36>,

    /// ISO-4217 code of the currency of this tariff.
    pub currency: currency::Code,

    /// List of at least one Element.
    pub elements: Vec<Element>,
}

/// A Tariff Element is a group of Price Components that share a set of restrictions under which they apply.
///
/// See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#144-tariffelement-class>.
#[derive(Debug)]
pub(crate) struct Element {
    /// List of Price Components that each describe how a certain dimension is priced.
    pub price_components: Vec<PriceComponent>,

    /// Restrictions that describe under which circumstances the Price Components of this Tariff Element apply.
    pub restrictions: Option<Restrictions>,
}

/// List of price components that make up the pricing of this tariff.
///
/// See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_tariffs.md#42-pricecomponent-class>.
#[derive(Debug)]
pub(crate) struct PriceComponent {
    /// The dimension that is being priced.
    pub dimension_type: v2x::DimensionType,

    /// Price per unit (excl. VAT) for this dimension.
    pub price: Money,

    /// Minimum amount to be billed. That is, the dimension will be billed in this `step_size` blocks.
    /// Consumed amounts are rounded up to the smallest multiple of `step_size` that is greater than the consumed amount.
    pub step_size: u64,
}

/// A `TariffRestrictions` object describes if and when a Tariff Element becomes active or inactive during a Charging Session.
/// These restrictions are not to be interpreted as making the Tariff Element applicable or not applicable for the entire Charging Session.
///
/// When more than one restriction is set, they are to be treated as a logical AND.
/// So a Tariff Element is active if and only if all the properties in its `TariffRestrictions` match.
///
/// See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#mod_tariffs_tariffrestrictions_class>.
///
/// We do not parse the `reservation` field as it has no effect on the generated CDR.
#[derive(Debug)]
pub(crate) struct Restrictions {
    /// The `Element` is valid from this time of day in local time.
    ///
    /// The time zone is defined in the `time_zone` field of the Location.
    start_time: Option<NaiveTime>,

    /// The `Element` is valid until this time of day in local time.
    ///
    /// The time zone is defined in the `time_zone` field of the Location.
    end_time: Option<NaiveTime>,

    /// The `Element` is valid from this date (inclusive) in local time.
    ///
    /// The time zone is defined in the `time_zone` field of the Location.
    start_date: Option<NaiveDate>,

    /// The `Element` is valid until this date (exclusive) in local time.
    ///
    /// The time zone is defined in the `time_zone` field of the Location.
    end_date: Option<NaiveDate>,

    /// Minimum consumed energy in kWh, for example 20, valid from this amount of energy (inclusive) being used.
    min_kwh: Option<Kwh>,

    /// Maximum consumed energy in kWh, for example 50, valid until this amount of energy (exclusive) being used.
    max_kwh: Option<Kwh>,

    /// If the charging power is equal to or lower than this value, the associated `TariffElement` becomes inactive.
    min_power: Option<Kw>,

    /// If the charging power is equal to or higher than this value, the associated `TariffElement` becomes inactive.
    max_power: Option<Kw>,

    /// Minimum duration in seconds the Charging Session MUST last (inclusive).
    ///
    /// When the duration of a Charging Session is longer than the defined value, this `TariffElement` is or becomes active.
    /// Before that moment, this `TariffElement` is not yet active.
    min_duration: Option<Duration>,

    /// Maximum duration in seconds the Charging Session MUST last (exclusive).
    ///
    /// When the duration of a Charging Session is shorter than the defined value, this `TariffElement` is or becomes active.
    /// After that moment, this `TariffElement` is no longer active.
    max_duration: Option<Duration>,

    /// Which day(s) of the week this `TariffElement` is active.
    day_of_week: Option<Vec<Weekday>>,
}

impl<'a> From<Tariff<'a>> for v221::Tariff<'a> {
    fn from(tariff: Tariff<'a>) -> Self {
        let Tariff {
            id,
            currency,
            elements,
        } = tariff;

        let elements = elements.into_iter().map(v221::Element::from).collect();
        v221::Tariff {
            party_id: None,
            id,
            currency,
            min_price: None,
            max_price: None,
            start_date_time: None,
            end_date_time: None,
            elements,
        }
    }
}

impl From<Element> for v221::Element {
    fn from(element: Element) -> Self {
        let Element {
            price_components,
            restrictions,
        } = element;

        v221::Element {
            price_components: price_components
                .into_iter()
                .map(v221::PriceComponent::from)
                .collect(),
            restrictions: restrictions.map(v221::Restrictions::from),
        }
    }
}

impl From<PriceComponent> for v221::PriceComponent {
    fn from(value: PriceComponent) -> Self {
        let PriceComponent {
            dimension_type,
            price,
            step_size,
        } = value;
        v221::PriceComponent {
            dimension_type,
            vat: VatOrigin::Unknown,
            price,
            step_size,
        }
    }
}

impl From<Restrictions> for v221::Restrictions {
    fn from(restrictions: Restrictions) -> Self {
        let Restrictions {
            start_time,
            end_time,
            start_date,
            end_date,
            min_kwh,
            max_kwh,
            min_power,
            max_power,
            min_duration,
            max_duration,
            day_of_week,
        } = restrictions;

        v221::Restrictions {
            start_time,
            end_time,
            start_date,
            end_date,
            min_kwh,
            max_kwh,
            min_current: None,
            max_current: None,
            min_power,
            max_power,
            min_duration,
            max_duration,
            day_of_week,
            reservation: None,
        }
    }
}

impl<'buf> FromSchema<'buf, schema::v211::Tariff<'buf>> for Tariff<'buf> {
    type Warning = Warning;

    fn from_schema(source: &schema::v211::Tariff<'buf>) -> Verdict<Self, Self::Warning> {
        let mut warnings = warning::Set::new();

        let currency = warnings.ok_or_bail(&source.currency)?;
        let currency = currency::Code::from_schema(currency)?.gather_warnings_into(&mut warnings);

        let id = warnings.ok_or_bail(&source.id)?;
        let id = string::CiMaxLen::<'_, 36>::from_schema(id)?.gather_warnings_into(&mut warnings);

        // An element the schema could not build rejects the tariff rather than being skipped:
        // a tariff missing one of its elements prices a session at the wrong rate. An
        // `elements` array that is present but empty is left to the consumer; see
        // `tariff::Versioned::to_v221`.
        let elements = warnings.ok_or_bail(&source.elements)?;
        let mut lowered = Vec::with_capacity(elements.len());
        for element in elements {
            let element = warnings.ok_or_bail(element)?;
            lowered.push(Element::from_schema(element)?.gather_warnings_into(&mut warnings));
        }

        let tariff = Tariff {
            currency,
            id,
            elements: lowered,
        };

        Ok(tariff.into_caveat(warnings))
    }
}

impl<'buf> FromSchema<'buf, schema::v211::Element<'buf>> for Element {
    type Warning = Warning;

    fn from_schema(source: &schema::v211::Element<'buf>) -> Verdict<Self, Self::Warning> {
        let mut warnings = warning::Set::new();

        // `price_components` is required; an element that prices nothing is rejected.
        let components = warnings.ok_or_bail(&source.price_components)?;

        // A component lowers to `None` when its `type` is unknown, which drops it as
        // unpriceable. A component the schema could not build at all is a different case: the
        // element is rejected rather than silently priced without one of its components.
        let mut price_components = Vec::with_capacity(components.len());
        for component in components {
            let component = warnings.ok_or_bail(component)?;
            let component = Option::<PriceComponent>::from_schema(component)?
                .gather_warnings_into(&mut warnings);

            if let Some(component) = component {
                price_components.push(component);
            }
        }

        // `restrictions` is optional; absent or `null` leaves the element unrestricted. A
        // present but unusable value is rejected, because an element that silently loses its
        // restrictions applies more widely than authored and changes the price.
        let restrictions = warnings.ok_or_bail(&source.restrictions)?;
        let restrictions = restrictions
            .as_ref()
            .map(Restrictions::from_schema)
            .transpose()?
            .gather_warnings_into(&mut warnings);

        let elem = Element {
            price_components,
            restrictions,
        };

        Ok(elem.into_caveat(warnings))
    }
}

impl<'buf> FromSchema<'buf, schema::v211::PriceComponent<'buf>> for Option<PriceComponent> {
    type Warning = Warning;

    fn from_schema(source: &schema::v211::PriceComponent<'buf>) -> Verdict<Self, Self::Warning> {
        let mut warnings = warning::Set::new();

        // An unknown (or wrong-typed) `type` makes the component unpriceable, so it is
        // dropped.
        if let schema::Integrity::Err(_) = &source.dimension_type {
            return Ok(None.into_caveat(warnings));
        }
        let dimension_type = warnings.ok_or_bail(&source.dimension_type)?;
        let dimension_type =
            v2x::DimensionType::from_schema(&dimension_type.value()).into_infallible();

        let price = warnings.ok_or_bail(&source.price)?;
        let price = Decimal::from_schema(price)?.gather_warnings_into(&mut warnings);

        let step_size = warnings.ok_or_bail(&source.step_size)?;
        let step_size = u64::from_schema(step_size)?.gather_warnings_into(&mut warnings);

        let comp = PriceComponent {
            dimension_type,
            price: Money::from_decimal(price),
            step_size,
        };

        Ok(Some(comp).into_caveat(warnings))
    }
}

impl<'buf> FromSchema<'buf, schema::v211::Restrictions<'buf>> for Restrictions {
    type Warning = Warning;

    fn from_schema(source: &schema::v211::Restrictions<'buf>) -> Verdict<Self, Self::Warning> {
        let mut warnings = warning::Set::new();

        // Every field is optional, so an absent one is `Ok(None)`. A field that is present but
        // unusable rejects the whole `Restrictions` instead of being dropped: silently
        // discarding one restriction widens or narrows when the element is active, which
        // changes the price.
        let start_time = warnings.ok_or_bail(&source.start_time)?;
        let start_time = start_time
            .as_ref()
            .map(NaiveTime::from_schema)
            .transpose()?
            .gather_warnings_into(&mut warnings);

        let end_time = warnings.ok_or_bail(&source.end_time)?;
        let end_time = end_time
            .as_ref()
            .map(NaiveTime::from_schema)
            .transpose()?
            .gather_warnings_into(&mut warnings);

        let start_date = warnings.ok_or_bail(&source.start_date)?;
        let start_date = start_date
            .as_ref()
            .map(NaiveDate::from_schema)
            .transpose()?
            .gather_warnings_into(&mut warnings);

        let end_date = warnings.ok_or_bail(&source.end_date)?;
        let end_date = end_date
            .as_ref()
            .map(NaiveDate::from_schema)
            .transpose()?
            .gather_warnings_into(&mut warnings);

        let min_kwh = warnings.ok_or_bail(&source.min_kwh)?;
        let min_kwh = min_kwh
            .as_ref()
            .map(Kwh::from_schema)
            .transpose()?
            .gather_warnings_into(&mut warnings);

        let max_kwh = warnings.ok_or_bail(&source.max_kwh)?;
        let max_kwh = max_kwh
            .as_ref()
            .map(Kwh::from_schema)
            .transpose()?
            .gather_warnings_into(&mut warnings);

        let min_power = warnings.ok_or_bail(&source.min_power)?;
        let min_power = min_power
            .as_ref()
            .map(Kw::from_schema)
            .transpose()?
            .gather_warnings_into(&mut warnings);

        let max_power = warnings.ok_or_bail(&source.max_power)?;
        let max_power = max_power
            .as_ref()
            .map(Kw::from_schema)
            .transpose()?
            .gather_warnings_into(&mut warnings);

        let min_duration = warnings.ok_or_bail(&source.min_duration)?;
        let min_duration = min_duration
            .as_ref()
            .map(Seconds::from_schema)
            .transpose()?
            .gather_warnings_into(&mut warnings)
            .map(TimeDelta::from);

        let max_duration = warnings.ok_or_bail(&source.max_duration)?;
        let max_duration = max_duration
            .as_ref()
            .map(Seconds::from_schema)
            .transpose()?
            .gather_warnings_into(&mut warnings)
            .map(TimeDelta::from);

        // A `day_of_week` entry that could not be built is rejected for the same reason: a
        // list missing one of its days silently changes when the element applies.
        let day_of_week = warnings.ok_or_bail(&source.day_of_week)?;
        let day_of_week = match day_of_week {
            Some(days) => {
                let mut weekdays = Vec::with_capacity(days.len());
                for day in days {
                    let day = warnings.ok_or_bail(day)?;
                    weekdays.push(Weekday::from_schema(&day.value()).into_infallible());
                }
                Some(weekdays)
            }
            None => None,
        };

        let res = Restrictions {
            start_time,
            end_time,
            start_date,
            end_date,
            min_kwh,
            max_kwh,
            min_power,
            max_power,
            min_duration,
            max_duration,
            day_of_week,
        };

        Ok(res.into_caveat(warnings))
    }
}