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
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
//! Lint a tariff by reading the schema intermediate representation.
//!
//! The walk deconstructs the IR itself rather than going through a whole-object lowering. Such a
//! lowering abandons the object as soon as a required field is missing or invalid, which is right
//! for a feature that needs a usable value but wrong here: a linter has to keep inspecting every
//! remaining field and report everything it finds. Leaf lowerings
//! (a `Str` to a `civil::Time`, a `Number` to a `Decimal`) are used as-is - they are pure, they
//! anchor their warnings at the right element, and reimplementing them would duplicate parsing
//! that belongs in one place.
//!
//! Fields that were absent from the document, or that the schema walk could not build, are
//! skipped without comment. Checking the document against the OCPI schema is a separate step
//! with its own warning set, which [`tariff::check`] returns to the caller.

#[cfg(test)]
mod test;

#[cfg(test)]
mod test_bound_read_once;

#[cfg(test)]
mod test_element_excludes_every_session;

#[cfg(test)]
mod test_rejected;

use std::fmt;

use tracing::{debug, instrument};

use jiff::{Timestamp, civil};
use rust_decimal::Decimal;

use crate::{
    Ampere, FromSchema, Kw, Kwh, Price, Weekday, country, currency, datetime,
    duration::{self, Seconds},
    from_warning_all, json, money, number,
    schema::{self, HasElement as _, Integrity, OcpiEnum},
    string,
    tariff::{self, v2x::DimensionType},
    warning,
};

/// Lint the given tariff and return a report of any [`Warning`]s found.
///
/// A [`tariff::Checked`] is what [`tariff::check`] returns, beside the schema warnings
/// `check` raises. This reports only what linting adds.
///
/// * See: [OCPI spec 2.2.1: Tariff](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariff_object>)
/// * See: [OCPI spec 2.1.1: Tariff](<https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_tariffs.md#31-tariff-object>)
pub(crate) fn lint(tariff: &tariff::Checked<'_>) -> Report {
    let mut warnings = warning::Gatherer::new();

    match tariff.schema() {
        tariff::Version::V221(schema) => lint_v221(tariff, schema, &mut warnings),
        tariff::Version::V211(schema) => lint_v211(tariff, schema, &mut warnings),
    }

    Report {
        warnings: warnings.into_set(),
    }
}

/// A tariff linting report.
#[derive(Debug)]
pub struct Report {
    /// What the linter found: the judgments a schema cannot express, and the warnings raised
    /// while lowering a leaf it wanted to inspect.
    pub warnings: warning::Set<Warning>,
}

/// The warnings the tariff linter can raise.
///
/// The variants that wrap another module's warning are raised by the leaf lowering the
/// linter called to read a field, not by the linter itself.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum Warning {
    /// The bounded time of day is the entire day, which is the same as leaving it out.
    ContainsEntireDay,

    /// The `day_of_week` list holds all seven days, which is the same as leaving it out.
    ContainsEntireWeek,

    /// Raised while reading a country code.
    Country(country::Warning),

    /// Both the CDR and tariff have a `country_code` that should be an alpha-2.
    CpoCountryCodeShouldBeAlpha2,

    /// Raised while reading a currency code.
    Currency(currency::Warning),

    /// Raised while reading a date, a time or a timestamp.
    DateTime(datetime::Warning),

    /// The `day_of_week` list names the same day more than once.
    DayOfWeekDuplicates,

    /// The `day_of_week` list is present but empty, which OCPI reads the same as leaving it out, so
    /// the list restricts no day.
    DayOfWeekEmpty,

    /// The `day_of_week` list is not in Monday-to-Sunday order.
    DayOfWeekUnsorted,

    /// Raised while reading a duration.
    Duration(duration::Warning),

    /// The element's restrictions exclude every session, so pricing never uses it.
    ///
    /// `lint` recognizes three kinds: a `max_duration` of `0`, a `start_time` equal to its
    /// `end_time` other than `00:00`, and a `start_date`, `min_duration` or `min_kwh` at or above
    /// its upper bound.
    ///
    /// `lint` doesn't report an element restricted to `reservation`. Such an element is about
    /// a kind of session pricing doesn't cover. Pricing skips the element and raises
    /// `price::Warning::ReservationElementSkipped`, so removing the element would change what
    /// pricing reports.
    ///
    /// `lint --fix` removes the element only when the warning states
    /// `OtherElements::SomeMayMatch`, because the tariff then still has an element that may match
    /// a session. Under the other two values, `lint` can't confirm that, so the fix keeps the
    /// element.
    ElementExcludesEverySession(OtherElements),

    /// The element's price components price more than one dimension.
    ///
    /// The element's shape suggests that its components apply together as a unit, but pricing
    /// doesn't treat them as one. For each dimension, pricing uses the first element that has a
    /// component for that dimension and whose restrictions match, as OCPI specifies.
    ///
    /// `lint` doesn't report an element with several components of one dimension. That element
    /// prices one dimension.
    ///
    /// * See: [OCPI spec 2.2.1: TariffElement](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariffelement_class>)
    ElementPricesMoreThanOneDimension,

    /// The `end_time` restriction is set to `23:59`.
    ///
    /// The spec states: "To stop at end of the day use: 00:00.".
    ///
    /// * See: [OCPI spec 2.2.1: Tariff Restrictions](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariffrestrictions_class>).
    EndTimeIsNearEndOfDay,

    /// A restriction's upper bound is at or below its lower bound, so the element doesn't match any
    /// session.
    ///
    /// The pairs checked are `start_date` and `end_date`, `min_duration` and `max_duration`, and
    /// `min_kwh` and `max_kwh`. Pricing excludes the value an upper bound states, so a pair whose
    /// bounds are equal doesn't match any session either.
    ///
    /// `lint` doesn't report a reversed `min_power` and `max_power`, or `min_current` and
    /// `max_current`. Pricing compares the lower bound with the highest value a charging period
    /// reports and the upper bound with the lowest, so a period whose readings span both bounds
    /// still matches.
    LowerBoundAtOrAboveUpper,

    /// A `max_*` restriction is zero, so the element can never match.
    MaxZeroNeverMatch,

    /// A `min_duration` restriction is `0`, so it allows every session.
    MinDurationZeroAllowsEverySession,

    /// The `min_price` is greater than `max_price`.
    MinPriceIsGreaterThanMax,

    /// A `min_kwh`, `min_power` or `min_current` restriction is `0`, so it excludes only a
    /// negative value.
    MinZeroExcludesOnlyNegative,

    /// The `start_time` and `end_time` are equal, so the element is never valid.
    NeverValid,

    /// Raised while reading a price.
    Money(money::Warning),

    /// Raised while reading a number.
    Number(number::Warning),

    /// The `restrictions` object is present but holds no restriction.
    RestrictionsEmpty,

    /// The `start_date_time` is after the `end_date_time`.
    StartDateTimeIsAfterEndDateTime,

    /// Raised while reading a string.
    String(string::Warning),
}

/// Whether another element of the tariff may still match a session, as far as pricing can tell.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum OtherElements {
    /// At least one other element may match a session. An element restricted to `reservation` never
    /// matches one.
    SomeMayMatch,

    /// No other element may match a session. Each other element excludes every session or is
    /// restricted to `reservation`.
    NoneMayMatch,

    /// Pricing rejects the whole tariff, for example because one of its fields doesn't read. No
    /// element prices a session until the author fixes that.
    TariffRejected,
}

from_warning_all!(
    country::Warning => Warning::Country,
    currency::Warning => Warning::Currency,
    datetime::Warning => Warning::DateTime,
    duration::Warning => Warning::Duration,
    money::Warning => Warning::Money,
    number::Warning => Warning::Number,
    string::Warning => Warning::String
);

impl crate::Warning for Warning {
    fn id(&self) -> warning::Id {
        match self {
            Self::ContainsEntireDay => warning::Id::from_static("contains_entire_day"),
            Self::ContainsEntireWeek => warning::Id::from_static("contains_entire_week"),
            Self::Country(kind) => kind.id(),
            Self::CpoCountryCodeShouldBeAlpha2 => {
                warning::Id::from_static("cpo_country_code_should_be_alpha2")
            }
            Self::Currency(kind) => kind.id(),
            Self::DateTime(kind) => kind.id(),
            Self::DayOfWeekDuplicates => warning::Id::from_static("duplicates"),
            Self::DayOfWeekEmpty => warning::Id::from_static("empty"),
            Self::DayOfWeekUnsorted => warning::Id::from_static("unsorted"),
            Self::Duration(kind) => kind.id(),
            Self::ElementExcludesEverySession(_) => {
                warning::Id::from_static("element_excludes_every_session")
            }
            Self::ElementPricesMoreThanOneDimension => {
                warning::Id::from_static("element_prices_more_than_one_dimension")
            }
            Self::EndTimeIsNearEndOfDay => warning::Id::from_static("end_time_is_near_end_of_day"),
            Self::LowerBoundAtOrAboveUpper => {
                warning::Id::from_static("lower_bound_at_or_above_upper")
            }
            Self::MaxZeroNeverMatch => warning::Id::from_static("max_zero_will_never_match"),
            Self::MinDurationZeroAllowsEverySession => {
                warning::Id::from_static("min_duration_zero_allows_every_session")
            }
            Self::MinPriceIsGreaterThanMax => {
                warning::Id::from_static("min_price_is_greater_than_max")
            }
            Self::MinZeroExcludesOnlyNegative => {
                warning::Id::from_static("min_zero_excludes_only_negative")
            }
            Self::NeverValid => warning::Id::from_static("never_valid"),
            Self::Money(kind) => kind.id(),
            Self::Number(kind) => kind.id(),
            Self::RestrictionsEmpty => warning::Id::from_static("restrictions_empty"),
            Self::StartDateTimeIsAfterEndDateTime => {
                warning::Id::from_static("start_date_time_is_after_end_date_time")
            }
            Self::String(kind) => kind.id(),
        }
    }

    /// A leaf lowering that could not build a value seeds this marker rather than restating
    /// the structural cause, which the schema walk already located.
    fn is_rejected(&self) -> bool {
        match self {
            Self::Country(kind) => kind.is_rejected(),
            Self::Currency(kind) => kind.is_rejected(),
            Self::DateTime(kind) => kind.is_rejected(),
            Self::Duration(kind) => kind.is_rejected(),
            Self::Money(kind) => kind.is_rejected(),
            Self::Number(kind) => kind.is_rejected(),
            Self::String(kind) => kind.is_rejected(),
            Self::ContainsEntireDay
            | Self::ContainsEntireWeek
            | Self::CpoCountryCodeShouldBeAlpha2
            | Self::DayOfWeekDuplicates
            | Self::DayOfWeekEmpty
            | Self::DayOfWeekUnsorted
            | Self::ElementExcludesEverySession(_)
            | Self::ElementPricesMoreThanOneDimension
            | Self::EndTimeIsNearEndOfDay
            | Self::LowerBoundAtOrAboveUpper
            | Self::MaxZeroNeverMatch
            | Self::MinDurationZeroAllowsEverySession
            | Self::MinPriceIsGreaterThanMax
            | Self::MinZeroExcludesOnlyNegative
            | Self::NeverValid
            | Self::RestrictionsEmpty
            | Self::StartDateTimeIsAfterEndDateTime => false,
        }
    }
}

impl fmt::Display for Warning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ContainsEntireDay => f.write_str("The bounded time of day is the entire day."),
            Self::ContainsEntireWeek => f.write_str(
                "All days of the week are defined. You can simply leave out the \
                 `day_of_week` field.",
            ),
            Self::Country(kind) => fmt::Display::fmt(kind, f),
            Self::CpoCountryCodeShouldBeAlpha2 => {
                f.write_str("The value should be an alpha-2 ISO 3166-1 country code")
            }
            Self::Currency(kind) => fmt::Display::fmt(kind, f),
            Self::DateTime(kind) => fmt::Display::fmt(kind, f),
            Self::DayOfWeekDuplicates => f.write_str("There's at least one duplicate day."),
            Self::DayOfWeekEmpty => f.write_str(
                "An empty list of days restricts no day. You can simply leave out the \
                 `day_of_week` field.",
            ),
            Self::DayOfWeekUnsorted => f.write_str("The days are unsorted."),
            Self::Duration(kind) => fmt::Display::fmt(kind, f),
            Self::ElementExcludesEverySession(OtherElements::SomeMayMatch) => f.write_str(
                "This element's restrictions exclude every session, so pricing never uses it.",
            ),
            Self::ElementExcludesEverySession(OtherElements::NoneMayMatch) => f.write_str(
                "This element's restrictions exclude every session, so pricing never uses it. \
                 No other element may match a session either.",
            ),
            Self::ElementExcludesEverySession(OtherElements::TariffRejected) => f.write_str(
                "This element's restrictions exclude every session, so pricing never uses it. \
                 Pricing also rejects the tariff as a whole.",
            ),
            Self::ElementPricesMoreThanOneDimension => f.write_str(
                "This element prices more than one dimension. Pricing looks up each dimension \
                 separately, so it doesn't treat the element's components as a unit.",
            ),
            Self::EndTimeIsNearEndOfDay => f.write_str(
                "The `end_time` restriction is set to `23:59`. The spec states: \"To stop at \
                 end of the day use: 00:00.\".",
            ),
            Self::LowerBoundAtOrAboveUpper => f.write_str(
                "This upper bound is at or below the lower bound it pairs with, so the element \
                 never matches a session.",
            ),
            Self::MaxZeroNeverMatch => f.write_str(
                "This element contains a zero `max_*` restriction and so will never match. \
                 This element can be removed.",
            ),
            Self::MinDurationZeroAllowsEverySession => f.write_str(
                "A `min_duration` of `0` allows every session, which is what leaving the \
                 field out means.",
            ),
            Self::MinPriceIsGreaterThanMax => {
                f.write_str("The `min_price` is greater than `max_price`.")
            }
            Self::MinZeroExcludesOnlyNegative => f.write_str(
                "A lower bound of `0` excludes only a negative value. Removing the field \
                 would change what a session reporting one costs.",
            ),
            Self::NeverValid => f.write_str(
                "The `start_time` and `end_time` are equal and so the element is never valid.",
            ),
            Self::Money(kind) => fmt::Display::fmt(kind, f),
            Self::Number(kind) => fmt::Display::fmt(kind, f),
            Self::RestrictionsEmpty => f.write_str(
                "The `restrictions` object holds no restriction, which is what leaving it out \
                 means.",
            ),
            Self::StartDateTimeIsAfterEndDateTime => {
                f.write_str("The `start_date_time` is after the `end_date_time`.")
            }
            Self::String(kind) => fmt::Display::fmt(kind, f),
        }
    }
}

/// Lint a `v2.2.1` tariff.
///
/// * See: [OCPI spec 2.2.1: Tariff](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariff_object>)
#[instrument(skip_all)]
fn lint_v221(
    checked: &tariff::Checked<'_>,
    tariff: &schema::v221::Tariff<'_>,
    warnings: &mut dyn warning::Gather<Warning>,
) {
    if let Integrity::Ok(country_code) = &tariff.country_code {
        lint_country_code(country_code, warnings);
    }

    if let Integrity::Ok(party_id) = &tariff.party_id {
        lint_party_id(party_id, warnings);
    }

    if let Integrity::Ok(currency) = &tariff.currency {
        lint_currency(currency, warnings);
    }

    lint_min_max_price(&tariff.min_price, &tariff.max_price, warnings);
    lint_start_end_date_time(&tariff.start_date_time, &tariff.end_date_time, warnings);

    if let Integrity::Ok(elements) = &tariff.elements {
        // The IR element doesn't keep the JSON element it was built from, so a warning on one
        // anchors to the item at the same index in the `elements` array. Keeping it with
        // `ir_object!(@keep_element ...)` would copy each element's whole JSON subtree into the IR.
        // The item is looked up only to raise `ElementExcludesEverySession` and
        // `ElementPricesMoreThanOneDimension`, so the other lints in this loop don't depend on the
        // array.
        let items = elements.element().value().as_array().unwrap_or(&[]);
        let mut excluding_every_session = Vec::new();
        let mut others = OtherElements::NoneMayMatch;

        for (index, element) in elements.into_iter().enumerate() {
            let Integrity::Ok(element) = element else {
                continue;
            };

            // The check runs before the `restrictions` match, because an element with no
            // restrictions can price several dimensions too. A component that can't be read, or
            // whose `type` can't, adds no dimension, and the schema walk reports that component.
            let mut dimensions = Vec::new();

            if let Integrity::Ok(components) = &element.price_components {
                for component in components {
                    let Integrity::Ok(component) = component else {
                        continue;
                    };
                    let Integrity::Ok(dimension_type) = &component.dimension_type else {
                        continue;
                    };
                    dimensions.push(DimensionType::from(&dimension_type.value()));
                }
            }

            lint_more_than_one_dimension(items.get(index), &dimensions, warnings);

            let restrictions = match &element.restrictions {
                Integrity::Ok(Some(restrictions)) => restrictions,
                Integrity::Ok(None) => {
                    others = OtherElements::SomeMayMatch;
                    continue;
                }
                Integrity::Missing(_) | Integrity::Err(_) => continue,
            };

            lint_restrictions_empty(restrictions, warnings);
            let start_time = lower_time(&restrictions.start_time, warnings);
            let end_time = lower_time(&restrictions.end_time, warnings);
            let times = lint_times(start_time, end_time, warnings);
            lint_day_of_week(&restrictions.day_of_week, warnings);

            let start_date = lower_date(&restrictions.start_date, warnings);
            let end_date = lower_date(&restrictions.end_date, warnings);
            let min_current = lower_number::<Ampere>(&restrictions.min_current, warnings);
            let max_current = lower_number::<Ampere>(&restrictions.max_current, warnings);
            let min_duration = lower_number::<Seconds>(&restrictions.min_duration, warnings);
            let max_duration = lower_number::<Seconds>(&restrictions.max_duration, warnings);
            let min_kwh = lower_number::<Kwh>(&restrictions.min_kwh, warnings);
            let max_kwh = lower_number::<Kwh>(&restrictions.max_kwh, warnings);
            let min_power = lower_number::<Kw>(&restrictions.min_power, warnings);
            let max_power = lower_number::<Kw>(&restrictions.max_power, warnings);

            lint_zero(max_current, Warning::MaxZeroNeverMatch, warnings);
            lint_zero(max_duration, Warning::MaxZeroNeverMatch, warnings);
            lint_zero(max_kwh, Warning::MaxZeroNeverMatch, warnings);
            lint_zero(max_power, Warning::MaxZeroNeverMatch, warnings);
            lint_zero(
                min_duration,
                Warning::MinDurationZeroAllowsEverySession,
                warnings,
            );
            lint_min_zero(min_current, warnings);
            lint_min_zero(min_kwh, warnings);
            lint_min_zero(min_power, warnings);
            let dates = lint_lower_bound_at_or_above_upper(start_date, end_date, warnings);
            let durations =
                lint_lower_bound_at_or_above_upper(min_duration, max_duration, warnings);
            let kwh = lint_lower_bound_at_or_above_upper(min_kwh, max_kwh, warnings);

            // Of the bounds `lint_zero` checks, only a `max_duration` of `0` excludes every session.
            // Negative accumulated energy passes a `max_kwh` of `0`, and a charging period that
            // reports no power or current passes a `max_power` or `max_current` of `0`. #596 tracks
            // `MaxZeroNeverMatch`, which says otherwise.
            let exclusions = [
                max_duration_exclusion(max_duration),
                times,
                dates,
                durations,
                kwh,
            ];

            // `Warning::ElementExcludesEverySession` says why an element restricted to `reservation`
            // isn't reported.
            //
            // A `reservation` the schema walk couldn't build is skipped too. Its author still meant
            // the element for reservations.
            //
            // No session matches such an element, so the `continue` leaves `others` as it is.
            if let Integrity::Ok(Some(_)) | Integrity::Err(_) = restrictions.reservation {
                continue;
            }

            if exclusions.contains(&Exclusion::ExcludesEverySession) {
                if let Some(item) = items.get(index) {
                    excluding_every_session.push(item);
                }
            } else {
                others = OtherElements::SomeMayMatch;
            }
        }

        lint_elements_excluding_every_session(checked, &excluding_every_session, others, warnings);
    }
}

/// Lint a `v2.1.1` tariff.
///
/// A `v2.1.1` tariff carries only `currency`, `id` and `elements`, so the lints that read
/// `country_code`, `party_id`, the price bounds or the active window do not apply to it.
///
/// * See: [OCPI spec 2.1.1: Tariff](<https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_tariffs.md#31-tariff-object>)
#[instrument(skip_all)]
fn lint_v211(
    checked: &tariff::Checked<'_>,
    tariff: &schema::v211::Tariff<'_>,
    warnings: &mut dyn warning::Gather<Warning>,
) {
    if let Integrity::Ok(currency) = &tariff.currency {
        lint_currency(currency, warnings);
    }

    if let Integrity::Ok(elements) = &tariff.elements {
        // The IR element doesn't keep the JSON element it was built from, so a warning on one
        // anchors to the item at the same index in the `elements` array. Keeping it with
        // `ir_object!(@keep_element ...)` would copy each element's whole JSON subtree into the IR.
        // The item is looked up only to raise `ElementExcludesEverySession` and
        // `ElementPricesMoreThanOneDimension`, so the other lints in this loop don't depend on the
        // array.
        let items = elements.element().value().as_array().unwrap_or(&[]);
        let mut excluding_every_session = Vec::new();
        let mut others = OtherElements::NoneMayMatch;

        for (index, element) in elements.into_iter().enumerate() {
            let Integrity::Ok(element) = element else {
                continue;
            };

            // The check runs before the `restrictions` match, because an element with no
            // restrictions can price several dimensions too. A component that can't be read, or
            // whose `type` can't, adds no dimension, and the schema walk reports that component.
            let mut dimensions = Vec::new();

            if let Integrity::Ok(components) = &element.price_components {
                for component in components {
                    let Integrity::Ok(component) = component else {
                        continue;
                    };
                    let Integrity::Ok(dimension_type) = &component.dimension_type else {
                        continue;
                    };
                    dimensions.push(DimensionType::from(&dimension_type.value()));
                }
            }

            lint_more_than_one_dimension(items.get(index), &dimensions, warnings);

            let restrictions = match &element.restrictions {
                Integrity::Ok(Some(restrictions)) => restrictions,
                Integrity::Ok(None) => {
                    others = OtherElements::SomeMayMatch;
                    continue;
                }
                Integrity::Missing(_) | Integrity::Err(_) => continue,
            };

            lint_restrictions_empty(restrictions, warnings);

            let start_time = lower_time(&restrictions.start_time, warnings);
            let end_time = lower_time(&restrictions.end_time, warnings);
            let times = lint_times(start_time, end_time, warnings);
            lint_day_of_week(&restrictions.day_of_week, warnings);

            // `v2.1.1` restrictions have no `min_current` or `max_current`.
            let start_date = lower_date(&restrictions.start_date, warnings);
            let end_date = lower_date(&restrictions.end_date, warnings);
            let min_duration = lower_number::<Seconds>(&restrictions.min_duration, warnings);
            let max_duration = lower_number::<Seconds>(&restrictions.max_duration, warnings);
            let min_kwh = lower_number::<Kwh>(&restrictions.min_kwh, warnings);
            let max_kwh = lower_number::<Kwh>(&restrictions.max_kwh, warnings);
            let min_power = lower_number::<Kw>(&restrictions.min_power, warnings);
            let max_power = lower_number::<Kw>(&restrictions.max_power, warnings);

            lint_zero(max_duration, Warning::MaxZeroNeverMatch, warnings);
            lint_zero(max_kwh, Warning::MaxZeroNeverMatch, warnings);
            lint_zero(max_power, Warning::MaxZeroNeverMatch, warnings);
            lint_zero(
                min_duration,
                Warning::MinDurationZeroAllowsEverySession,
                warnings,
            );
            lint_min_zero(min_kwh, warnings);
            lint_min_zero(min_power, warnings);
            let dates = lint_lower_bound_at_or_above_upper(start_date, end_date, warnings);
            let durations =
                lint_lower_bound_at_or_above_upper(min_duration, max_duration, warnings);
            let kwh = lint_lower_bound_at_or_above_upper(min_kwh, max_kwh, warnings);

            // Of the bounds `lint_zero` checks, only a `max_duration` of `0` excludes every session.
            // Negative accumulated energy passes a `max_kwh` of `0`, and a charging period that
            // reports no power or current passes a `max_power` or `max_current` of `0`. #596 tracks
            // `MaxZeroNeverMatch`, which says otherwise.
            let exclusions = [
                max_duration_exclusion(max_duration),
                times,
                dates,
                durations,
                kwh,
            ];

            if exclusions.contains(&Exclusion::ExcludesEverySession) {
                if let Some(item) = items.get(index) {
                    excluding_every_session.push(item);
                }
            } else {
                others = OtherElements::SomeMayMatch;
            }
        }

        lint_elements_excluding_every_session(checked, &excluding_every_session, others, warnings);
    }
}

/// Lint a `restrictions` object that holds no restriction.
///
/// Every field of a `restrictions` object is optional, so an object written empty restricts
/// nothing. This has the same semantic meaning as leaving the object out.
#[instrument(skip_all)]
fn lint_restrictions_empty<'buf>(
    restrictions: &impl schema::HasElement<'buf>,
    warnings: &mut dyn warning::Gather<Warning>,
) {
    let elem = restrictions.element();

    let Some(fields) = elem.value().as_object_fields() else {
        return;
    };

    if fields.is_empty() {
        warnings.insert(elem, Warning::RestrictionsEmpty);
    }
}

/// Lint an element whose price components price more than one dimension.
///
/// `item` is the element's JSON, and `dimensions` holds the dimension of each of its components.
#[instrument(skip_all)]
fn lint_more_than_one_dimension(
    item: Option<&json::Element<'_>>,
    dimensions: &[DimensionType],
    warnings: &mut dyn warning::Gather<Warning>,
) {
    let Some(item) = item else {
        return;
    };

    let Some((first, rest)) = dimensions.split_first() else {
        return;
    };

    if rest.iter().any(|dimension| dimension != first) {
        warnings.insert(item, Warning::ElementPricesMoreThanOneDimension);
    }
}

/// Lint the `country_code` field.
///
/// An alpha-3 code is accepted and converted, but the caller is told to use alpha-2. The
/// remaining findings - a bad code, an unusable length, escapes, lower case - come from the
/// lowering rather than from this function.
#[instrument(skip_all)]
fn lint_country_code(source: &schema::Str<'_>, warnings: &mut dyn warning::Gather<Warning>) {
    let lowered = match country::CodeSet::from_schema(source, warnings) {
        Ok(lowered) => lowered,
        Err(error) => {
            warnings.deescalate(error);
            return;
        }
    };

    debug!("code_set: {lowered:?}");

    if let country::CodeSet::Alpha3(_) = lowered {
        warnings.insert(source.element(), Warning::CpoCountryCodeShouldBeAlpha2);
    }
}

/// The `party_id` is the three character ISO-15118 ID of the CPO.
type PartyId<'buf> = string::AsciiExactLen<'buf, 3>;

/// Lint the `party_id` field.
///
/// The length and lexical checks come from the lowering. The case advice is this layer's
/// own: `AsciiExactLen` is case-insensitive by definition, so it has no opinion on it.
#[instrument(skip_all)]
fn lint_party_id(source: &schema::Str<'_>, warnings: &mut dyn warning::Gather<Warning>) {
    let lowered = match PartyId::from_schema(source, warnings) {
        Ok(lowered) => lowered,
        Err(error) => {
            warnings.deescalate(error);
            return;
        }
    };

    // The value is held as written, so an escape sequence still reads as its own letters -
    // the `n` of a `\n` would otherwise be taken for lower case. A string carrying escapes
    // is already reported by the lowering, and its casing is not the useful thing to say
    // about it.
    if source.value().lexical_issues().escapes {
        return;
    }

    if lowered.chars().any(char::is_lowercase) {
        warnings.insert(
            source.element(),
            Warning::String(string::Warning::IncorrectCase),
        );
    }
}

/// Lint the `currency` field.
///
/// Every finding comes from the lowering: an unknown code, a code the ISO standard reserves,
/// and the case advice.
#[instrument(skip_all)]
fn lint_currency(source: &schema::Str<'_>, warnings: &mut dyn warning::Gather<Warning>) {
    let lowered = match currency::Code::from_schema(source, warnings) {
        Ok(lowered) => lowered,
        Err(error) => {
            warnings.deescalate(error);
            return;
        }
    };

    debug!("code: {lowered:?}");
}

/// The `min_price` should not be greater than the `max_price`.
///
/// Both bounds are lowered even when only one is present, so a problem with the value itself
/// is still reported; the comparison only happens when both are usable.
#[instrument(skip_all)]
fn lint_min_max_price(
    min_price: &Integrity<Option<schema::v221::Price<'_>>>,
    max_price: &Integrity<Option<schema::v221::Price<'_>>>,
    warnings: &mut dyn warning::Gather<Warning>,
) {
    let min = lower_price(min_price, warnings);
    let max = lower_price(max_price, warnings);

    let (Some((min, min_elem)), Some((max, _))) = (min, max) else {
        return;
    };

    if min.exceeds_on_either_value(max) {
        warnings.insert(min_elem, Warning::MinPriceIsGreaterThanMax);
    }
}

/// Lower an optional `Price` field, keeping the element its warnings anchor to.
fn lower_price<'a, 'buf>(
    price: &'a Integrity<Option<schema::v221::Price<'buf>>>,
    warnings: &mut dyn warning::Gather<Warning>,
) -> Option<(Price, &'a json::Element<'buf>)> {
    let Integrity::Ok(Some(price)) = price else {
        return None;
    };

    let lowered = match Price::from_schema(price, warnings) {
        Ok(lowered) => lowered,
        Err(error) => {
            warnings.deescalate(error);
            return None;
        }
    };

    Some((lowered, price.element()))
}

/// Lint both `start_date_time` and `end_date_time`.
///
/// The two may be equal - a tariff active for an instant is odd but not wrong - so only a
/// `start_date_time` strictly after the `end_date_time` is reported.
#[instrument(skip_all)]
fn lint_start_end_date_time(
    start_date_time: &Integrity<Option<schema::Str<'_>>>,
    end_date_time: &Integrity<Option<schema::Str<'_>>>,
    warnings: &mut dyn warning::Gather<Warning>,
) {
    let start = lower_date_time(start_date_time, warnings);
    let end = lower_date_time(end_date_time, warnings);

    let (Some((start, start_elem)), Some((end, _))) = (start, end) else {
        return;
    };

    if start > end {
        warnings.insert(start_elem, Warning::StartDateTimeIsAfterEndDateTime);
    }
}

/// Lower an optional `DateTime` field, keeping the element its warnings anchor to.
fn lower_date_time<'a, 'buf>(
    date_time: &'a Integrity<Option<schema::Str<'buf>>>,
    warnings: &mut dyn warning::Gather<Warning>,
) -> Option<(Timestamp, &'a json::Element<'buf>)> {
    let Integrity::Ok(Some(date_time)) = date_time else {
        return None;
    };

    let lowered = match Timestamp::from_schema(date_time, warnings) {
        Ok(lowered) => lowered,
        Err(error) => {
            warnings.deescalate(error);
            return None;
        }
    };

    Some((lowered, date_time.element()))
}

/// Lower an optional `YYYY-MM-DD` field, keeping the element its warnings anchor to.
fn lower_date<'a, 'buf>(
    date: &'a Integrity<Option<schema::Str<'buf>>>,
    warnings: &mut dyn warning::Gather<Warning>,
) -> Option<(civil::Date, &'a json::Element<'buf>)> {
    let Integrity::Ok(Some(date)) = date else {
        return None;
    };

    let lowered = match civil::Date::from_schema(date, warnings) {
        Ok(lowered) => lowered,
        Err(error) => {
            warnings.deescalate(error);
            return None;
        }
    };

    Some((lowered, date.element()))
}

/// The time of day as hour and minute.
///
/// Seconds are deliberately not compared: OCPI writes these restrictions as `HH:MM`, and the
/// spec's advice about the end of the day is phrased in those terms.
#[derive(Copy, Clone, Eq, PartialEq)]
struct HourMin {
    hour: i8,
    min: i8,
}

/// Midnight, which OCPI uses to mean both the start and the end of a day.
const DAY_BOUNDARY: HourMin = HourMin { hour: 0, min: 0 };

/// The spec asks for `00:00` to end a day, so `23:59` is a near miss worth flagging.
const NEAR_END_OF_DAY: HourMin = HourMin { hour: 23, min: 59 };

/// True if the time is at, or as good as at, the end of the day.
fn is_day_end(time: HourMin) -> bool {
    time == NEAR_END_OF_DAY || time == DAY_BOUNDARY
}

/// Lint the `start_time` and `end_time` restrictions.
///
/// Returns `Exclusion::ExcludesEverySession` when it raised `NeverValid`. A `00:00` pair raises
/// `ContainsEntireDay` instead, because the pricer reads it as the whole day.
///
/// * See: [OCPI spec 2.2.1: Tariff Restrictions](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariffrestrictions_class>)
#[instrument(skip_all)]
fn lint_times(
    start: Option<(HourMin, &json::Element<'_>)>,
    end: Option<(HourMin, &json::Element<'_>)>,
    warnings: &mut dyn warning::Gather<Warning>,
) -> Exclusion {
    // With both bounds present the pair is judged together; with only one, that bound alone
    // can still describe the whole day.
    if let (Some((start, start_elem)), Some((end, end_elem))) = (start, end) {
        if end == NEAR_END_OF_DAY {
            warnings.insert(end_elem, Warning::EndTimeIsNearEndOfDay);
        }

        if start == DAY_BOUNDARY && is_day_end(end) {
            warnings.insert(start_elem, Warning::ContainsEntireDay);
        } else if start == end {
            warnings.insert(start_elem, Warning::NeverValid);
            return Exclusion::ExcludesEverySession;
        }

        return Exclusion::MayMatch;
    }

    if let Some((start, start_elem)) = start {
        if start == DAY_BOUNDARY {
            warnings.insert(start_elem, Warning::ContainsEntireDay);
        }
    } else if let Some((end, end_elem)) = end
        && is_day_end(end)
    {
        warnings.insert(end_elem, Warning::ContainsEntireDay);
    }

    Exclusion::MayMatch
}

/// Lower an optional `HH:MM` field, keeping the element its warnings anchor to.
fn lower_time<'a, 'buf>(
    time: &'a Integrity<Option<schema::Str<'buf>>>,
    warnings: &mut dyn warning::Gather<Warning>,
) -> Option<(HourMin, &'a json::Element<'buf>)> {
    let Integrity::Ok(Some(time)) = time else {
        return None;
    };

    let lowered = match civil::Time::from_schema(time, warnings) {
        Ok(lowered) => lowered,
        Err(error) => {
            warnings.deescalate(error);
            return None;
        }
    };

    let hour_min = HourMin {
        hour: lowered.hour(),
        min: lowered.minute(),
    };

    Some((hour_min, time.element()))
}

/// Every day of the week; a list holding all of them says the same as no list at all.
const ALL_DAYS: usize = 7;

/// Lint the `day_of_week` restriction.
///
/// A day the schema could not read is skipped rather than abandoning the list, so the
/// ordering and duplicate checks still describe the days that are readable. Every warning
/// here is about the list as a whole, so all of them anchor to the array.
///
/// * See: [OCPI spec 2.2.1: Tariff DayOfWeek](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_dayofweek_enum>)
#[instrument(skip_all)]
fn lint_day_of_week<T>(
    day_of_week: &Integrity<Option<schema::List<'_, schema::Enum<'_, T>>>>,
    warnings: &mut dyn warning::Gather<Warning>,
) where
    T: OcpiEnum,
    Weekday: for<'a> From<&'a T>,
{
    let Integrity::Ok(Some(days)) = day_of_week else {
        return;
    };

    let elem = days.element();

    // An empty list restricts no day, so the checks below have nothing to describe.
    if days.is_empty() {
        warnings.insert(elem, Warning::DayOfWeekEmpty);
        return;
    }

    let mut lowered: Vec<Weekday> = Vec::with_capacity(days.len());

    for day in days {
        let Integrity::Ok(day) = day else {
            continue;
        };

        lowered.push(Weekday::from(&day.value()));
    }

    if !lowered.is_sorted() {
        warnings.insert(elem, Warning::DayOfWeekUnsorted);
    }

    let unique: std::collections::BTreeSet<_> = lowered.iter().copied().collect();

    if unique.len() != lowered.len() {
        warnings.insert(elem, Warning::DayOfWeekDuplicates);
    }

    if unique.len() == ALL_DAYS {
        warnings.insert(elem, Warning::ContainsEntireWeek);
    }
}

/// Lint a restriction whose bound makes it pointless when it is `0`, reporting `warning` if so.
///
/// A `max_*` restriction of `0` never matches anything.
///
/// A `min_duration` of `0` allows every session.
/// `price::tariff::Restriction::snapshot_validity_exclusive` compares the bound with `>=` against
/// how long the session has lasted. That duration is never negative, so a bound of `0` allows
/// every session, which is what leaving the field out does.
///
/// The zero test for a duration is exact because `number::IsZero for Seconds` is exact, where the
/// same trait allows a tolerance for `Kwh`, `Kw` and `Ampere`. `duration::Seconds::from_schema`
/// reads the digits as a `u64`, so a fractional or negative bound never lowers and the lowering
/// reports it as a `Duration` warning instead.
///
/// `min_kwh`, `min_power` and `min_current` go through `lint_min_zero` instead, because a bound of
/// `0` there excludes a negative value.
#[instrument(skip_all)]
fn lint_zero<T: number::IsZero>(
    bound: Option<(T, &json::Element<'_>)>,
    warning: Warning,
    warnings: &mut dyn warning::Gather<Warning>,
) {
    let Some((value, elem)) = bound else {
        return;
    };

    if value.is_zero() {
        warnings.insert(elem, warning);
    }
}

/// Whether a `max_duration` excludes every session, which a bound of `0` does because a duration is
/// never negative. The test is the exact `number::IsZero for Seconds` that `lint_zero` uses, so
/// this agrees with `MaxZeroNeverMatch` on `max_duration`.
fn max_duration_exclusion(max_duration: Option<(Seconds, &json::Element<'_>)>) -> Exclusion {
    let Some((max_duration, _)) = max_duration else {
        return Exclusion::MayMatch;
    };

    if number::IsZero::is_zero(&max_duration) {
        Exclusion::ExcludesEverySession
    } else {
        Exclusion::MayMatch
    }
}

/// Lint a `min_kwh`, `min_power` or `min_current` restriction of exactly `0`.
///
/// The pricer compares each bound with `>=`. It compares `min_kwh` with the energy the session has
/// consumed so far, in `price::tariff::Restriction::snapshot_validity_exclusive`. It compares
/// `min_power` and `min_current` with the highest power and current a charging period reports, in
/// `period_validity`. A CDR can report a negative value for each, and the library prices that CDR.
///
/// OCPI 2.2.1 says a negative `ENERGY`, `MIN_POWER` or `MIN_CURRENT` is flow from the vehicle to
/// the grid, so a period whose highest power or current is negative had that flow for its whole
/// length. OCPI 2.1.1 does not say whether any of these values can be negative.
///
/// An author who takes `0` to be the lowest value writes a bound of `0` expecting it to allow every
/// session. The bound excludes a negative value, so removing it changes what a session reporting
/// one costs. That is why `fix::Fixable` proposes no edit for this warning.
///
/// The zero test is exact. `number::IsZero` allows a tolerance of `0.001` for `Kwh`, `Kw` and
/// `Ampere`, which would report a `min_power` of `0.0005` as `0`. That bound excludes a value of
/// `0.0001` as well as a negative one, so `MinZeroExcludesOnlyNegative` would claim the bound
/// excludes only a negative value, which is false.
///
/// A negative bound is not reported. An author who writes one knows a value can be negative, where
/// a bound of `0` suggests the author took `0` to be the lowest value.
#[instrument(skip_all)]
fn lint_min_zero<T: Into<Decimal>>(
    bound: Option<(T, &json::Element<'_>)>,
    warnings: &mut dyn warning::Gather<Warning>,
) {
    let Some((value, elem)) = bound else {
        return;
    };

    let value: Decimal = value.into();

    if value.is_zero() {
        warnings.insert(elem, Warning::MinZeroExcludesOnlyNegative);
    }
}

/// Lint a pair of restriction bounds whose lower bound is at or above its upper bound.
///
/// `price::tariff::Restriction::snapshot_validity_exclusive` compares a session with the lower
/// bound using `>=` and with the upper bound using `<`. A pair whose bounds are equal therefore
/// doesn't match any session, which is why the comparison here is `>=` rather than the `>` that
/// `lint_start_end_date_time` uses.
///
/// `Warning::LowerBoundAtOrAboveUpper` names the pairs this checks and why the power and current
/// pairs are left out. The pricer compares those two pairs in `Restriction::period_validity`.
///
/// The comparison is exact, with none of the tolerance `number::IsZero` allows, because a pair
/// that is close but not reversed still matches a session.
///
/// Returns `Exclusion::ExcludesEverySession` when it raised `LowerBoundAtOrAboveUpper`.
#[instrument(skip_all)]
fn lint_lower_bound_at_or_above_upper<T: PartialOrd>(
    lower: Option<(T, &json::Element<'_>)>,
    upper: Option<(T, &json::Element<'_>)>,
    warnings: &mut dyn warning::Gather<Warning>,
) -> Exclusion {
    let (Some((lower, _)), Some((upper, upper_elem))) = (lower, upper) else {
        return Exclusion::MayMatch;
    };

    if lower < upper {
        return Exclusion::MayMatch;
    }

    warnings.insert(upper_elem, Warning::LowerBoundAtOrAboveUpper);
    Exclusion::ExcludesEverySession
}

/// Whether a restriction, or an element's restrictions together, exclude every session.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Exclusion {
    ExcludesEverySession,
    MayMatch,
}

/// Lint each element whose restrictions exclude every session.
///
/// `fix::Fixable` sees only the element a warning sits on, so it can't tell whether removing that
/// element would leave the tariff with none. The warning records it as an `OtherElements` instead.
///
/// The walk passes `SomeMayMatch` when some element isn't restricted to `reservation` and doesn't
/// exclude every session, and `NoneMayMatch` otherwise. This function then asks
/// `tariff::Checked::lower_to_v221`, the lowering pricing runs on a tariff, and states `TariffRejected`
/// if pricing rejects the tariff.
///
/// If `lint --fix` removed an element from a tariff pricing rejects, it could leave a tariff with no
/// element that matches a session. A `null` is the sharpest case, because `lint --fix` removes it in
/// the same pass, which would leave `elements` empty. Once the `null` is gone, the next pass sees a
/// tariff pricing accepts and can remove the element.
///
/// The check runs only when some element is reported. Only whether the tariff lowers matters, so
/// this function drops the lowering's warnings.
#[instrument(skip_all)]
fn lint_elements_excluding_every_session(
    tariff: &tariff::Checked<'_>,
    excluding_every_session: &[&json::Element<'_>],
    others: OtherElements,
    warnings: &mut dyn warning::Gather<Warning>,
) {
    if excluding_every_session.is_empty() {
        return;
    }

    let mut lowering_warnings = warning::Gatherer::new();
    let others = if tariff.lower_to_v221(&mut lowering_warnings).is_err() {
        OtherElements::TariffRejected
    } else {
        others
    };

    for elem in excluding_every_session {
        warnings.insert(elem, Warning::ElementExcludesEverySession(others));
    }
}

/// Lower an optional number field, keeping the element its warnings anchor to.
///
/// The walk lowers each bound once and passes the value to every check that reads it.
/// `warning::Gatherer` keeps every warning it is given, so a check that lowered the field
/// itself would report a bound that fails to lower once per check.
fn lower_number<'a, 'buf, T>(
    bound: &'a Integrity<Option<schema::Number<'buf>>>,
    warnings: &mut dyn warning::Gather<Warning>,
) -> Option<(T, &'a json::Element<'buf>)>
where
    T: FromSchema<'buf, schema::Number<'buf>>,
    T::Warning: Into<Warning>,
{
    let Integrity::Ok(Some(bound)) = bound else {
        return None;
    };

    let lowered = match T::from_schema(bound, warnings) {
        Ok(lowered) => lowered,
        Err(error) => {
            warnings.deescalate(error);
            return None;
        }
    };

    Some((lowered, bound.element()))
}