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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! Tests for lowering `schema::v221` tariff IR objects into domain types via `FromSchema`.
//!
//! A `schema::v221` IR object is only produced by the builder, so each test drives a real
//! `v2.2.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::{DateTime, NaiveDate, NaiveTime, TimeDelta, Utc};
use rust_decimal::Decimal;
use rust_decimal_macros::dec;

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

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

/// The same tariff with every `Restrictions` field set on its single element.
const VALID_RESTRICTIONS: &str = r#"{
    "country_code": "NL",
    "party_id": "TNM",
    "currency": "EUR",
    "id": "ID",
    "last_updated": "2024-01-01T00:00:00Z",
    "elements": [
        {
            "price_components": [{"price": 0.25, "step_size": 1, "type": "ENERGY", "vat": 21.0}],
            "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_current": 6.0,
                "max_current": 32.0,
                "min_power": 3.0,
                "max_power": 22.0,
                "min_duration": 60,
                "max_duration": 3600,
                "day_of_week": ["MONDAY", "TUESDAY"],
                "reservation": "RESERVATION"
            }
        }
    ]
}"#;

/// The same tariff with every optional top-level field set.
const VALID_FULL: &str = r#"{
    "country_code": "NL",
    "party_id": "TNM",
    "currency": "EUR",
    "id": "ID",
    "last_updated": "2024-01-01T00:00:00Z",
    "min_price": {"excl_vat": 1.0, "incl_vat": 1.21},
    "max_price": {"excl_vat": 100.0, "incl_vat": 121.0},
    "start_date_time": "2024-01-01T00:00:00Z",
    "end_date_time": "2024-12-31T23:59:59Z",
    "elements": [
        {"price_components": [{"price": 0.25, "step_size": 1, "type": "ENERGY", "vat": 21.0}]}
    ]
}"#;

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

/// Borrow the single element IR object out of a built tariff.
fn element<'a, 'buf>(tariff: &'a v221::Tariff<'buf>) -> &'a v221::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 v221::Tariff<'buf>) -> &'a v221::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 v221::Tariff<'buf>) -> &'a v221::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_matches!(comp.vat, VatOrigin::Provided(_));
    assert!(all_warnings(&warnings).is_empty());
}

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

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

    let comp = comp.expect("a price component without VAT should still build");
    assert_matches!(comp.vat, VatOrigin::NotProvided);
}

#[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 fractional_step_size_is_rejected() {
    // The schema proves `step_size` is a JSON number literal but not that it is a whole one,
    // so `u64::from_schema` is the gate that rejects it. This is the only remaining source of
    // `Warning::FieldInvalidValue`.
    let src = VALID.replace(r#""step_size": 1"#, r#""step_size": 1.5"#);
    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::FieldInvalidValue { value, .. } if value == "1.5"
    );
}

#[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_current.map(Decimal::from), Some(dec!(6.0)));
    assert_eq!(res.max_current.map(Decimal::from), Some(dec!(32.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_matches!(
        res.reservation,
        Some(ReservationRestrictionType::Reservation)
    );
    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_current, None);
    assert_eq!(res.max_current, 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_matches!(res.reservation, 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_current": null,
        "max_current": null,
        "min_power": null,
        "max_power": null,
        "min_duration": null,
        "max_duration": null,
        "day_of_week": null,
        "reservation": 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_current, None);
    assert_eq!(res.max_current, 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_matches!(res.reservation, None);
    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 wrong_kind_day_of_week_is_rejected() {
    let src = VALID_RESTRICTIONS.replace(r#"["MONDAY", "TUESDAY"]"#, "5");
    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 unknown_dimension_type_drops_the_component_from_the_element() {
    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 elem = Element::from_schema(element(&tariff)).unwrap().unwrap();

    // The component is unpriceable, so it is dropped and the element still builds.
    assert!(elem.price_components.is_empty());
}

#[test]
fn missing_price_components_is_rejected() {
    let src = VALID.replace(
        r#""price_components": [{"price": 0.25, "step_size": 1, "type": "ENERGY", "vat": 21.0}]"#,
        "",
    );
    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", "vat": 21.0}"#,
        "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 wrong_kind_restrictions_is_rejected() {
    let src = VALID.replace(
        r#""price_components": ["#,
        r#""restrictions": 5, "price_components": ["#,
    );
    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();

    let party_id = tariff.party_id.expect("the CPO ID should be built");
    assert_eq!(party_id.country_code, country::Code::Nl);
    assert_eq!(&*party_id.id, "TNM");
    assert_eq!(&*tariff.id, "ID");
    assert_eq!(tariff.currency, currency::Code::Eur);
    assert!(tariff.min_price.is_none());
    assert!(tariff.max_price.is_none());
    assert_eq!(tariff.start_date_time, None);
    assert_eq!(tariff.end_date_time, None);
    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 tariff_lowers_its_optional_fields() {
    let doc = json::parse(VALID_FULL.into()).unwrap();
    let built = build_tariff(&doc);

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

    let min_price = tariff.min_price.expect("min_price should be built");
    assert_eq!(Decimal::from(min_price.excl_vat), dec!(1.0));
    assert_eq!(min_price.incl_vat.map(Decimal::from), Some(dec!(1.21)));

    let max_price = tariff.max_price.expect("max_price should be built");
    assert_eq!(Decimal::from(max_price.excl_vat), dec!(100.0));
    assert_eq!(max_price.incl_vat.map(Decimal::from), Some(dec!(121.0)));

    assert_eq!(
        tariff.start_date_time,
        Some("2024-01-01T00:00:00Z".parse::<DateTime<Utc>>().unwrap())
    );
    assert_eq!(
        tariff.end_date_time,
        Some("2024-12-31T23:59:59Z".parse::<DateTime<Utc>>().unwrap())
    );
    assert!(all_warnings(&warnings).is_empty());
}

#[test]
fn bare_number_price_lowers_as_excl_vat() {
    // The `v2.1.1` bare-number form is accepted by the `v2.2.1` schema, so no `PriceOrNumber`
    // step is needed here.
    let src = VALID_FULL.replace(r#"{"excl_vat": 1.0, "incl_vat": 1.21}"#, "1.5");
    let doc = json::parse(src.as_str().into()).unwrap();
    let built = build_tariff(&doc);

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

    let min_price = tariff.min_price.expect("min_price should be built");
    assert_eq!(Decimal::from(min_price.excl_vat), dec!(1.5));
    assert_eq!(min_price.incl_vat, None);
}

#[test]
fn null_optional_fields_are_none() {
    let src = VALID_FULL
        .replace(r#"{"excl_vat": 1.0, "incl_vat": 1.21}"#, "null")
        .replace(r#"{"excl_vat": 100.0, "incl_vat": 121.0}"#, "null")
        .replace(
            r#""start_date_time": "2024-01-01T00:00:00Z""#,
            r#""start_date_time": null"#,
        )
        .replace(
            r#""end_date_time": "2024-12-31T23:59:59Z""#,
            r#""end_date_time": null"#,
        );
    let doc = json::parse(src.as_str().into()).unwrap();
    let built = build_tariff(&doc);

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

    assert!(tariff.min_price.is_none());
    assert!(tariff.max_price.is_none());
    assert_eq!(tariff.start_date_time, None);
    assert_eq!(tariff.end_date_time, None);
}

#[test]
fn alpha3_country_code_lowers_to_the_same_code() {
    // The lowering keeps the code whichever set it came from: we want the data, not a
    // judgment on which form the spec prefers.
    let src = VALID.replace(r#""country_code": "NL""#, r#""country_code": "NLD""#);
    let doc = json::parse(src.as_str().into()).unwrap();
    let built = build_tariff(&doc);

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

    let party_id = tariff.party_id.expect("the CPO ID should be built");
    assert_eq!(party_id.country_code, country::Code::Nl);
}

#[test]
fn each_missing_required_field_is_rejected() {
    for field in [
        r#""country_code": "NL","#,
        r#""party_id": "TNM","#,
        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#"{
        "country_code": "NL",
        "party_id": "TNM",
        "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", "vat": 21.0}]}"#,
        "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 unusable_min_price_is_rejected() {
    let src = VALID_FULL.replace(r#"{"excl_vat": 1.0, "incl_vat": 1.21}"#, "true");
    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 unparsable_start_date_time_is_rejected() {
    let src = VALID_FULL.replace(
        r#""start_date_time": "2024-01-01T00:00:00Z""#,
        r#""start_date_time": "not a date""#,
    );
    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::DateTime(_));
}

#[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; a feature that needs at least one element rejects on
    // that schema warning instead.
    let src = VALID.replace(
        r#"[
        {"price_components": [{"price": 0.25, "step_size": 1, "type": "ENERGY", "vat": 21.0}]}
    ]"#,
        "[]",
    );
    let doc = json::parse(src.as_str().into()).unwrap();
    let (built, schema_warnings) = v221::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());
}