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
437
438
439
440
441
442
//! Tests for lowering `schema::v211` tariff IR objects into domain types via `FromSchema`.
//!
//! A `schema::v211` IR object is only produced by the builder, so each test drives a real
//! `v2.1.1` tariff through `build_tariff` and lowers the tariff itself, its single element,
//! that element's single price component, or its restrictions out of it.

#![allow(
    clippy::indexing_slicing,
    clippy::unwrap_in_result,
    reason = "unwraps and indexing are allowed anywhere in tests"
)]

use std::assert_matches;

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

use super::{Element, PriceComponent, Restrictions, Tariff};
use crate::{
    currency, json,
    schema::{v211, Integrity, Warning as SchemaWarning},
    tariff::{v2x::DimensionType, Warning},
    warning, FromSchema as _, Weekday,
};

/// A minimal, fully valid `v2.1.1` tariff with a single price component.
const VALID: &str = r#"{
    "currency": "EUR",
    "id": "ID",
    "last_updated": "2024-01-01T00:00:00Z",
    "elements": [
        {"price_components": [{"price": 0.25, "step_size": 1, "type": "ENERGY"}]}
    ]
}"#;

/// The same tariff with every `Restrictions` field set on its single element.
const VALID_RESTRICTIONS: &str = r#"{
    "currency": "EUR",
    "id": "ID",
    "last_updated": "2024-01-01T00:00:00Z",
    "elements": [
        {
            "price_components": [{"price": 0.25, "step_size": 1, "type": "ENERGY"}],
            "restrictions": {
                "start_time": "09:00",
                "end_time": "18:00",
                "start_date": "2024-01-01",
                "end_date": "2024-12-31",
                "min_kwh": 1.0,
                "max_kwh": 50.0,
                "min_power": 3.0,
                "max_power": 22.0,
                "min_duration": 60,
                "max_duration": 3600,
                "day_of_week": ["MONDAY", "TUESDAY"]
            }
        }
    ]
}"#;

/// Build a `v2.1.1` tariff, dropping the schema-level warnings.
fn build_tariff<'buf>(doc: &json::Document<'buf>) -> v211::Tariff<'buf> {
    v211::build_tariff(doc).ignore_warnings()
}

/// Borrow the single element IR object out of a built tariff.
fn element<'a, 'buf>(tariff: &'a v211::Tariff<'buf>) -> &'a v211::Element<'buf> {
    let Integrity::Ok(elements) = &tariff.elements else {
        panic!("elements should be built: {:?}", tariff.elements);
    };
    let Integrity::Ok(element) = &elements[0] else {
        panic!("the element should be built");
    };
    element
}

/// Borrow the single price component IR object out of a built tariff.
fn component<'a, 'buf>(tariff: &'a v211::Tariff<'buf>) -> &'a v211::PriceComponent<'buf> {
    let Integrity::Ok(components) = &element(tariff).price_components else {
        panic!("price_components should be built");
    };
    let Integrity::Ok(comp) = &components[0] else {
        panic!("the price component should be built");
    };
    comp
}

/// Borrow the single element's `Restrictions` IR object out of a built tariff.
fn restrictions<'a, 'buf>(tariff: &'a v211::Tariff<'buf>) -> &'a v211::Restrictions<'buf> {
    let element = element(tariff);
    let Integrity::Ok(Some(restrictions)) = &element.restrictions else {
        panic!("restrictions should be built: {:?}", element.restrictions);
    };
    restrictions
}

fn all_warnings(warnings: &warning::Set<Warning>) -> Vec<&Warning> {
    warnings.path_map().into_values().flatten().collect()
}

#[test]
fn price_component_lowers_from_schema() {
    let doc = json::parse(VALID.into()).unwrap();
    let tariff = build_tariff(&doc);

    let (comp, warnings) = Option::<PriceComponent>::from_schema(component(&tariff))
        .unwrap()
        .into_parts();

    let comp = comp.expect("a valid price component should build");
    assert_eq!(comp.dimension_type, DimensionType::Energy);
    assert_eq!(Decimal::from(comp.price), dec!(0.25));
    assert_eq!(comp.step_size, 1);
    assert!(all_warnings(&warnings).is_empty());
}

#[test]
fn unknown_dimension_type_drops_component() {
    let src = VALID.replace(r#""type": "ENERGY""#, r#""type": "FOO""#);
    let doc = json::parse(src.as_str().into()).unwrap();
    let tariff = build_tariff(&doc);

    let comp = Option::<PriceComponent>::from_schema(component(&tariff))
        .unwrap()
        .unwrap();

    // The component is unpriceable, so it is dropped rather than failing the tariff.
    assert!(comp.is_none());
}

#[test]
fn missing_price_is_rejected() {
    let src = VALID.replace(r#""price": 0.25, "#, "");
    let doc = json::parse(src.as_str().into()).unwrap();
    let tariff = build_tariff(&doc);

    let err = Option::<PriceComponent>::from_schema(component(&tariff)).unwrap_err();
    let error = err.unwrap();

    assert_matches!(error.into_warning(), Warning::Rejected);
}

#[test]
fn restrictions_lower_from_schema() {
    let doc = json::parse(VALID_RESTRICTIONS.into()).unwrap();
    let tariff = build_tariff(&doc);

    let (res, warnings) = Restrictions::from_schema(restrictions(&tariff))
        .unwrap()
        .into_parts();

    assert_eq!(res.start_time, NaiveTime::from_hms_opt(9, 0, 0));
    assert_eq!(res.end_time, NaiveTime::from_hms_opt(18, 0, 0));
    assert_eq!(res.start_date, NaiveDate::from_ymd_opt(2024, 1, 1));
    assert_eq!(res.end_date, NaiveDate::from_ymd_opt(2024, 12, 31));
    assert_eq!(res.min_kwh.map(Decimal::from), Some(dec!(1.0)));
    assert_eq!(res.max_kwh.map(Decimal::from), Some(dec!(50.0)));
    assert_eq!(res.min_power.map(Decimal::from), Some(dec!(3.0)));
    assert_eq!(res.max_power.map(Decimal::from), Some(dec!(22.0)));
    assert_eq!(res.min_duration, Some(TimeDelta::seconds(60)));
    assert_eq!(res.max_duration, Some(TimeDelta::seconds(3600)));
    assert_eq!(
        res.day_of_week,
        Some(vec![Weekday::Monday, Weekday::Tuesday])
    );
    assert!(all_warnings(&warnings).is_empty());
}

#[test]
fn absent_restriction_fields_are_none() {
    let src = VALID.replace(
        r#""price_components": ["#,
        r#""restrictions": {}, "price_components": ["#,
    );
    let doc = json::parse(src.as_str().into()).unwrap();
    let tariff = build_tariff(&doc);

    let res = Restrictions::from_schema(restrictions(&tariff))
        .unwrap()
        .unwrap();

    assert_eq!(res.start_time, None);
    assert_eq!(res.end_time, None);
    assert_eq!(res.start_date, None);
    assert_eq!(res.end_date, None);
    assert_eq!(res.min_kwh, None);
    assert_eq!(res.max_kwh, None);
    assert_eq!(res.min_power, None);
    assert_eq!(res.max_power, None);
    assert_eq!(res.min_duration, None);
    assert_eq!(res.max_duration, None);
    assert_eq!(res.day_of_week, None);
}

#[test]
fn null_restriction_fields_are_none() {
    // A `null` field has no meaning in OCPI, so it is read as absent rather than as a value.
    const ALL_NULL: &str = r#"{
        "start_time": null,
        "end_time": null,
        "start_date": null,
        "end_date": null,
        "min_kwh": null,
        "max_kwh": null,
        "min_power": null,
        "max_power": null,
        "min_duration": null,
        "max_duration": null,
        "day_of_week": null
    }"#;

    let src = VALID.replace(
        r#""price_components": ["#,
        &format!(r#""restrictions": {ALL_NULL}, "price_components": ["#),
    );
    let doc = json::parse(src.as_str().into()).unwrap();
    let tariff = build_tariff(&doc);

    let (res, warnings) = Restrictions::from_schema(restrictions(&tariff))
        .unwrap()
        .into_parts();

    assert_eq!(res.start_time, None);
    assert_eq!(res.end_time, None);
    assert_eq!(res.start_date, None);
    assert_eq!(res.end_date, None);
    assert_eq!(res.min_kwh, None);
    assert_eq!(res.max_kwh, None);
    assert_eq!(res.min_power, None);
    assert_eq!(res.max_power, None);
    assert_eq!(res.min_duration, None);
    assert_eq!(res.max_duration, None);
    assert_eq!(res.day_of_week, None);
    assert!(all_warnings(&warnings).is_empty());
}

#[test]
fn string_encoded_price_lowers_cleanly() {
    // A price written as a JSON string is flagged by the schema walk, but it still lowers to
    // the same `Money`.
    let src = VALID.replace(r#""price": 0.25"#, r#""price": "3.0000""#);
    let doc = json::parse(src.as_str().into()).unwrap();
    let built = build_tariff(&doc);

    let (tariff, warnings) = Tariff::from_schema(&built).unwrap().into_parts();

    assert_eq!(
        Decimal::from(tariff.elements[0].price_components[0].price),
        dec!(3.0000)
    );
    assert!(all_warnings(&warnings).is_empty());
}

#[test]
fn unusable_restriction_field_is_rejected() {
    // A restriction that is present but unusable must not be silently dropped: doing so would
    // widen when the element applies and change the price.
    let src = VALID_RESTRICTIONS.replace(r#""min_kwh": 1.0"#, r#""min_kwh": true"#);
    let doc = json::parse(src.as_str().into()).unwrap();
    let tariff = build_tariff(&doc);

    let err = Restrictions::from_schema(restrictions(&tariff)).unwrap_err();
    let error = err.unwrap();

    assert_matches!(error.into_warning(), Warning::Rejected);
}

#[test]
fn unknown_weekday_entry_is_rejected() {
    let src = VALID_RESTRICTIONS.replace(r#""TUESDAY""#, r#""FUNDAY""#);
    let doc = json::parse(src.as_str().into()).unwrap();
    let tariff = build_tariff(&doc);

    let err = Restrictions::from_schema(restrictions(&tariff)).unwrap_err();
    let error = err.unwrap();

    assert_matches!(error.into_warning(), Warning::Rejected);
}

#[test]
fn element_lowers_from_schema() {
    let doc = json::parse(VALID.into()).unwrap();
    let tariff = build_tariff(&doc);

    let (elem, warnings) = Element::from_schema(element(&tariff)).unwrap().into_parts();

    assert_eq!(elem.price_components.len(), 1);
    assert_eq!(
        elem.price_components[0].dimension_type,
        DimensionType::Energy
    );
    assert!(elem.restrictions.is_none());
    assert!(all_warnings(&warnings).is_empty());
}

#[test]
fn element_lowers_its_restrictions() {
    let doc = json::parse(VALID_RESTRICTIONS.into()).unwrap();
    let tariff = build_tariff(&doc);

    let elem = Element::from_schema(element(&tariff)).unwrap().unwrap();

    let restrictions = elem.restrictions.expect("the restrictions should build");
    assert_eq!(restrictions.start_time, NaiveTime::from_hms_opt(9, 0, 0));
}

#[test]
fn null_restrictions_leaves_the_element_unrestricted() {
    let src = VALID.replace(
        r#""price_components": ["#,
        r#""restrictions": null, "price_components": ["#,
    );
    let doc = json::parse(src.as_str().into()).unwrap();
    let tariff = build_tariff(&doc);

    let elem = Element::from_schema(element(&tariff)).unwrap().unwrap();

    assert!(elem.restrictions.is_none());
}

#[test]
fn missing_price_components_is_rejected() {
    let src = VALID.replace(
        r#""price_components": [{"price": 0.25, "step_size": 1, "type": "ENERGY"}]"#,
        "",
    );
    let doc = json::parse(src.as_str().into()).unwrap();
    let tariff = build_tariff(&doc);

    let err = Element::from_schema(element(&tariff)).unwrap_err();
    let error = err.unwrap();

    assert_matches!(error.into_warning(), Warning::Rejected);
}

#[test]
fn unbuildable_price_component_entry_is_rejected() {
    // Unlike an unpriceable component, an entry the schema could not build at all must not be
    // dropped: the element would then be priced without one of its components.
    let src = VALID.replace(r#"{"price": 0.25, "step_size": 1, "type": "ENERGY"}"#, "5");
    let doc = json::parse(src.as_str().into()).unwrap();
    let tariff = build_tariff(&doc);

    let err = Element::from_schema(element(&tariff)).unwrap_err();
    let error = err.unwrap();

    assert_matches!(error.into_warning(), Warning::Rejected);
}

#[test]
fn tariff_lowers_from_schema() {
    let doc = json::parse(VALID.into()).unwrap();
    let built = build_tariff(&doc);

    let (tariff, warnings) = Tariff::from_schema(&built).unwrap().into_parts();

    assert_eq!(&*tariff.id, "ID");
    assert_eq!(tariff.currency, currency::Code::Eur);
    assert_eq!(tariff.elements.len(), 1);
    assert_eq!(
        tariff.elements[0].price_components[0].dimension_type,
        DimensionType::Energy
    );
    assert!(all_warnings(&warnings).is_empty());
}

#[test]
fn each_missing_required_field_is_rejected() {
    for field in [r#""currency": "EUR","#, r#""id": "ID","#] {
        let src = VALID.replace(field, "");
        let doc = json::parse(src.as_str().into()).unwrap();
        let built = build_tariff(&doc);

        let err = Tariff::from_schema(&built)
            .err()
            .unwrap_or_else(|| panic!("a tariff without `{field}` should be rejected"));
        let error = err.unwrap();

        assert_matches!(error.into_warning(), Warning::Rejected);
    }
}

#[test]
fn missing_elements_is_rejected() {
    const NO_ELEMENTS: &str = r#"{
        "currency": "EUR",
        "id": "ID",
        "last_updated": "2024-01-01T00:00:00Z"
    }"#;

    let doc = json::parse(NO_ELEMENTS.into()).unwrap();
    let built = build_tariff(&doc);

    let err = Tariff::from_schema(&built).unwrap_err();
    let error = err.unwrap();

    assert_matches!(error.into_warning(), Warning::Rejected);
}

#[test]
fn unbuildable_element_entry_is_rejected() {
    // An element the schema could not build must not be skipped: the tariff would then price
    // a session at the wrong rate.
    let src = VALID.replace(
        r#"{"price_components": [{"price": 0.25, "step_size": 1, "type": "ENERGY"}]}"#,
        "5",
    );
    let doc = json::parse(src.as_str().into()).unwrap();
    let built = build_tariff(&doc);

    let err = Tariff::from_schema(&built).unwrap_err();
    let error = err.unwrap();

    assert_matches!(error.into_warning(), Warning::Rejected);
}

#[test]
fn empty_elements_lowers_to_no_elements() {
    // The empty array is reported by the schema walk as a located `Cardinality` warning, so
    // this layer does not reject it; `tariff::Versioned::to_v221` rejects the tariff instead.
    let src = VALID.replace(
        r#"[
        {"price_components": [{"price": 0.25, "step_size": 1, "type": "ENERGY"}]}
    ]"#,
        "[]",
    );
    let doc = json::parse(src.as_str().into()).unwrap();
    let (built, schema_warnings) = v211::build_tariff(&doc).into_parts();

    let cardinality_warnings = schema_warnings
        .path_map()
        .into_values()
        .flatten()
        .filter(|warning| matches!(warning, SchemaWarning::Cardinality { .. }))
        .count();
    assert_eq!(cardinality_warnings, 1);

    let tariff = Tariff::from_schema(&built).unwrap().unwrap();

    assert!(tariff.elements.is_empty());
}