ocpi-tariffs 0.54.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
#[cfg(test)]
mod test_from_schema;

use std::convert::Infallible;

use chrono::{DateTime, TimeDelta, Utc};
use rust_decimal::Decimal;

use super::super::Consumed;
use crate::{
    Ampere, FromSchema, Kw, Kwh, Price, ToDuration as _, Verdict, country, currency,
    number::FromDecimal as _,
    price::{Period, Warning},
    schema::{self, HasElement as _},
    string,
    warning::{self, GatherWarnings as _, IntoCaveat as _, IntoInfallible as _},
};

/// The CDR object describes the Charging Session and its costs. How these costs are build up etc.
///
/// * See: [OCPI spec 2.2.1: CDR](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc>).
#[derive(Debug)]
pub struct Cdr {
    /// Start timestamp of the charging session.
    pub start_date_time: DateTime<Utc>,

    /// Stop timestamp of the charging session.
    pub end_date_time: DateTime<Utc>,

    /// List of charging periods that make up this charging session.
    /// A session should consist of 1 or more periods, where each period
    /// has a different relevant Tariff.
    pub charging_periods: Vec<ChargingPeriod>,

    pub kind: Kind,

    pub totals: Totals,
}

/// Whether a CDR bills a session or credits a CDR sent before, as its `credit` field states.
///
/// OCPI 2.1.1 has no `credit` field, so every v2.1.1 CDR is `Normal`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
    /// A CDR with `credit` absent or `false`, which the spec calls a "Normal (non-credit)" CDR
    /// (`specs/v221/mod_cdrs.asciidoc:326`).
    Normal,

    /// A CDR with `credit` set to `true`.
    Credit,
}

#[derive(Debug)]
pub struct Totals {
    /// Total cost of this transaction.
    pub cost: Price,

    /// Total cost of the flat dimension.
    pub fixed_cost: Option<Price>,

    /// Total energy charged, in kWh.
    pub energy: Kwh,

    /// Total cost related to the energy dimension.
    pub energy_cost: Option<Price>,

    /// Total duration of the session, charging and not charging, in hours.
    ///
    /// This is the CDR's `total_time`, which the spec defines as the whole session. It is not the
    /// charging time: the spec gives that as `total_time - total_parking_time`.
    pub duration_total: TimeDelta,

    /// Total cost related to the charging time dimension.
    ///
    /// This is the CDR's `total_time_cost`, which the spec defines as the cost resulting from the
    /// duration of charging. This field is charging-related while `duration_total` above is
    /// not. The pair disagrees because the spec's own pair does.
    pub duration_charging_cost: Option<Price>,

    /// Total time not charging, in hours.
    pub duration_idle: Option<TimeDelta>,

    /// Total cost related to the `parking`/idle time dimension.
    pub duration_idle_cost: Option<Price>,
}

/// The volume that has been consumed for a specific dimension during a charging period.
#[derive(Debug, Clone)]
pub(crate) struct Dimension {
    pub dimension_type: DimensionType,

    /// Volume of the dimension consumed, measured according to the dimension type.
    pub volume: Decimal,
}

/// The volume that has been consumed for a specific dimension during a charging period.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DimensionType {
    /// Consumed energy in `kWh`.
    Energy,

    /// The peak current, in 'A', during this period.
    MaxCurrent,

    /// The lowest current, in `A`, during this period.
    MinCurrent,

    /// The maximum power, in 'kW', reached during this period.
    MaxPower,

    /// The minimum power, in 'kW', reached during this period.
    MinPower,

    /// The parking time, in hours, consumed in this period.
    ///
    /// NOTE: We use the term `idle` in variables and fields instead of `parking` to avoid confusion
    /// in the definition of parking. The OCPI spec defines `parking` as the time spent not charging.
    ParkingTime,

    /// The reservation time, in hours, consumed in this period.
    ReservationTime,

    /// The charging time, in hours, consumed in this period.
    Time,

    Current,

    EnergyExport,

    EnergyImport,

    Power,

    StateOfCharge,
}

impl FromSchema<'_, schema::v221::CdrDimensionType> for DimensionType {
    type Warning = Infallible;

    fn from_schema(source: &schema::v221::CdrDimensionType) -> Verdict<Self, Self::Warning> {
        use schema::v221::CdrDimensionType;

        let v = match source {
            CdrDimensionType::Energy => Self::Energy,
            CdrDimensionType::MaxCurrent => Self::MaxCurrent,
            CdrDimensionType::MinCurrent => Self::MinCurrent,
            CdrDimensionType::ParkingTime => Self::ParkingTime,
            CdrDimensionType::Time => Self::Time,
            CdrDimensionType::Current => Self::Current,
            CdrDimensionType::EnergyExport => Self::EnergyExport,
            CdrDimensionType::EnergyImport => Self::EnergyImport,
            CdrDimensionType::MaxPower => Self::MaxPower,
            CdrDimensionType::MinPower => Self::MinPower,
            CdrDimensionType::Power => Self::Power,
            CdrDimensionType::ReservationTime => Self::ReservationTime,
            CdrDimensionType::StateOfCharge => Self::StateOfCharge,
        };

        Ok(v.into_infallible_caveat())
    }
}

/// A single charging period, containing a nonempty list of charge dimensions.
///
/// * See: [OCPI spec 2.2.1: CDR ChargingPeriod](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc#mod_cdrs_chargingperiod_class>).
#[derive(Clone, Debug)]
pub struct ChargingPeriod {
    /// Start timestamp of the charging period. This period ends when a next period starts, the
    /// last period ends when the session ends.
    pub start_date_time: DateTime<Utc>,

    /// List of relevant values for this charging period.
    pub dimensions: Vec<Dimension>,
}

impl<'buf> FromSchema<'buf, schema::v221::Cdr<'buf>> for Cdr {
    type Warning = Warning;

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

        // `country_code`, `currency` and `party_id` are not used while pricing, but the schema
        // only checks their shape, so their contents are still worth a warning. None of them
        // can stop a CDR being priced.
        if let schema::Integrity::Ok(country_code) = &source.country_code {
            let code_set =
                country::CodeSet::from_schema(country_code).gather_warnings_into(&mut warnings)?;

            if let country::CodeSet::Alpha3(_) = code_set {
                warnings.insert(country_code.element(), Warning::CountryShouldBeAlpha2);
            }
        }

        if let schema::Integrity::Ok(currency) = &source.currency {
            let _ignore_value =
                currency::Code::from_schema(currency).gather_warnings_into(&mut warnings);
        }

        if let schema::Integrity::Ok(party_id) = &source.party_id {
            let _ignore_value = string::AsciiExactLen::<'_, 3>::from_schema(party_id)
                .gather_warnings_into(&mut warnings);
        }

        let start_date_time = warnings.ok_or_bail(&source.start_date_time)?;
        let start_date_time =
            DateTime::<Utc>::from_schema(start_date_time)?.gather_warnings_into(&mut warnings);

        let end_date_time = warnings.ok_or_bail(&source.end_date_time)?;
        let end_date_time =
            DateTime::<Utc>::from_schema(end_date_time)?.gather_warnings_into(&mut warnings);

        // A period the schema could not build rejects the CDR rather than being skipped: a
        // CDR missing one of its periods is validated against the wrong consumption amounts.
        let periods = warnings.ok_or_bail(&source.charging_periods)?;
        let mut charging_periods = Vec::with_capacity(periods.len());
        for period in periods {
            let period = warnings.ok_or_bail(period)?;
            charging_periods
                .push(ChargingPeriod::from_schema(period)?.gather_warnings_into(&mut warnings));
        }

        // Pricing presumes the periods are in order. The CDR is not required to list them sorted.
        charging_periods.sort_unstable_by_key(|period| period.start_date_time);

        let credit = warnings.ok_or_bail(&source.credit)?;
        let kind = match credit {
            Some(true) => Kind::Credit,
            Some(false) | None => Kind::Normal,
        };

        let total_cost = warnings.ok_or_bail(&source.total_cost)?;
        let total_cost = Price::from_schema(total_cost)?.gather_warnings_into(&mut warnings);

        let total_energy = warnings.ok_or_bail(&source.total_energy)?;
        let total_energy = Kwh::from_schema(total_energy)?.gather_warnings_into(&mut warnings);

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

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

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

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

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

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

        let cdr = Cdr {
            start_date_time,
            end_date_time,
            charging_periods,
            kind,
            totals: Totals {
                cost: total_cost,
                fixed_cost: total_fixed_cost,
                energy: total_energy,
                energy_cost: total_energy_cost,
                duration_total: total_time.to_duration(),
                duration_charging_cost: total_time_cost,
                duration_idle: total_parking_time.map(|d| d.to_duration()),
                duration_idle_cost: total_parking_cost,
            },
        };

        Ok(cdr.into_caveat(warnings))
    }
}

impl<'buf> FromSchema<'buf, schema::v221::ChargingPeriod<'buf>> for ChargingPeriod {
    type Warning = Warning;

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

        let start_date_time = warnings.ok_or_bail(&source.start_date_time)?;
        let start_date_time =
            DateTime::<Utc>::from_schema(start_date_time)?.gather_warnings_into(&mut warnings);

        // `dimensions` is required; a period that measures nothing is rejected.
        let dimensions = warnings.ok_or_bail(&source.dimensions)?;

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

            if let Some(dimension) = dimension {
                lowered.push(dimension);
            }
        }

        let period = ChargingPeriod {
            start_date_time,
            dimensions: lowered,
        };

        Ok(period.into_caveat(warnings))
    }
}

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

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

        // An unknown (or wrong-typed) `type` leaves the volume with no meaning, so the
        // dimension 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 = DimensionType::from_schema(&dimension_type.value()).into_infallible();

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

        let dimension = Dimension {
            dimension_type,
            volume,
        };

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

impl From<ChargingPeriod> for Period {
    fn from(period: ChargingPeriod) -> Self {
        let ChargingPeriod {
            start_date_time,
            dimensions,
        } = period;
        let mut consumed = Consumed {
            current_max: None,
            current_min: None,
            duration_charging: None,
            duration_idle: None,
            energy: None,
            power_max: None,
            power_min: None,
        };

        for dimension in dimensions {
            let Dimension {
                dimension_type,
                volume,
            } = dimension;

            match dimension_type {
                DimensionType::MinCurrent => {
                    consumed.current_min = Some(Ampere::from_decimal(volume));
                }
                DimensionType::MaxCurrent => {
                    consumed.current_max = Some(Ampere::from_decimal(volume));
                }
                DimensionType::MaxPower => {
                    consumed.power_max = Some(Kw::from_decimal(volume));
                }
                DimensionType::MinPower => {
                    consumed.power_min = Some(Kw::from_decimal(volume));
                }
                DimensionType::Energy => {
                    consumed.energy = Some(Kwh::from_decimal(volume));
                }
                DimensionType::Time => {
                    consumed.duration_charging = Some(volume.to_duration());
                }
                DimensionType::ParkingTime => {
                    consumed.duration_idle = Some(volume.to_duration());
                }
                DimensionType::Current
                | DimensionType::EnergyExport
                | DimensionType::EnergyImport
                | DimensionType::Power
                | DimensionType::ReservationTime
                | DimensionType::StateOfCharge => {
                    // The pricer does not use these dimension types.
                }
            }
        }

        Period {
            start_date_time,
            consumed,
        }
    }
}