ocpi-tariffs 0.54.0

OCPI tariff calculations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
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
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
//! Generate a CDR from a tariff.

#[cfg(test)]
mod test;

#[cfg(test)]
mod test_clamp_date_time_span;

#[cfg(test)]
mod test_gen_time_events;

#[cfg(test)]
mod test_generate;

#[cfg(test)]
mod test_generate_from_single_elem_tariff;

#[cfg(test)]
mod test_local_to_utc;

#[cfg(test)]
mod test_periods;

#[cfg(test)]
mod test_power_to_time;

#[cfg(test)]
mod test_popular_tariffs;

#[cfg(test)]
mod test_restricted_supply;

mod v2x;

use std::{
    cmp::{max, min},
    fmt,
    ops::Range,
};

use chrono::{DateTime, Datelike as _, NaiveDateTime, NaiveTime, TimeDelta, Utc};
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use tracing::{debug, instrument, warn};

use crate::{
    Price, SaturatingAdd as _, ToDuration as _, country, currency,
    duration::{AsHms as _, NANOS_IN_HOUR, ToHoursDecimal},
    energy::{Ampere, Kw, Kwh},
    from_warning_all,
    number::{FromDecimal as _, RoundDecimal as _},
    price, tariff,
    warning::{self, GatherWarnings as _, IntoCaveat as _, WithElement as _},
};

/// The minimum duration of a CDR. Anything below this will result in an Error.
const MIN_CS_DURATION_SECS: i64 = 120;

type DateTimeSpan = Range<DateTime<Utc>>;
/// A [`Verdict`](crate::Verdict) whose warnings are this module's [`Warning`].
pub type Verdict<T> = crate::Verdict<T, Warning>;
/// A [`Caveat`](warning::Caveat) whose warnings are this module's [`Warning`].
pub type Caveat<T> = warning::Caveat<T, Warning>;

/// Return the value if `Some`. Otherwise, bail(return) with an `Error::Internal` containing the giving message.
macro_rules! some_dec_or_bail {
    ($elem:expr, $opt:expr, $warnings:expr, $msg:literal) => {
        match $opt {
            Some(v) => v,
            None => {
                return $warnings.bail($elem.as_element(), Warning::Decimal($msg));
            }
        }
    };
}

/// Return the value if `Some`. Otherwise, bail(return) with an `Error::Internal` containing the giving message.
macro_rules! some_time_delta_or_bail {
    ($elem:expr, $opt:expr, $warnings:expr, $msg:literal) => {
        match $opt {
            Some(v) => v,
            None => {
                return $warnings.bail($elem.as_element(), Warning::TimeDelta($msg));
            }
        }
    };
}

/// The outcome of calling [`crate::cdr::generate_from_tariff`].
#[derive(Debug)]
pub struct Report {
    /// The ID of the parsed tariff.
    pub tariff_id: String,

    /// The currency code of the parsed tariff.
    pub tariff_currency_code: currency::Code,

    /// A partial CDR that can be fleshed out by the caller.
    ///
    /// See [`PartialCdr`] for which fields the caller has to supply.
    ///
    /// * See: [OCPI spec 2.2.1: CDR](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc>).
    pub partial_cdr: PartialCdr,
}

/// A CDR generated from a tariff, with the fields the generator cannot know left unset.
///
/// Some fields the OCPI spec requires of a CDR are absent here. The generator is given a
/// tariff and a [`Config`], and neither names the EVSE location or the token the session was
/// authenticated with, so the caller fills those in.
///
/// * See: [OCPI spec 2.2.1: CDR](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc>).
/// * See: [OCPI spec 2.1.1: CDR](<https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_cdrs.md>).
#[derive(Debug)]
pub struct PartialCdr {
    /// The ISO-4217 currency code every amount in this CDR is denominated in.
    ///
    /// Taken from the tariff the CDR was generated from, so it holds the same value as
    /// [`Report::tariff_currency_code`].
    pub currency_code: currency::Code,

    /// The five character ID of the CPO that 'owns' this CDR.
    ///
    /// The first two characters are the ISO-3166 alpha-2 country code of the CPO. The remaining three
    /// characters are the ISO-15118 ID of the CPO.
    ///
    /// None if a v211 tariff was used to generate the CDR.
    /// The v211 tariff does not define a country code or `party_id` field.
    pub party_id: Option<CpoId>,

    /// Start timestamp of the charging session.
    pub start_date_time: DateTime<Utc>,

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

    /// Total energy charged, in kWh.
    pub total_energy: Option<Kwh>,

    /// Total duration charging.
    ///
    /// Some if the charging happened during the session.
    pub total_charging_duration: Option<TimeDelta>,

    /// Total duration not charging.
    ///
    /// Some if there was idle time during the session.
    pub total_idle_duration: Option<TimeDelta>,

    /// Total cost of this transaction.
    pub total_cost: Option<Price>,

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

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

    /// Total cost related to the idle time dimension.
    pub total_idle_duration_cost: Option<Price>,

    /// Total cost related to the charging time dimension.
    pub total_charging_duration_cost: Option<Price>,

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

/// The five character ID of the CPO.
///
/// The first two characters are the ISO-3166 alpha-2 country code of the CPO.
/// The remaining three characters are the ISO-15118 ID of the CPO.
#[derive(Clone, Debug)]
pub struct CpoId {
    /// The ISO-3166 alpha-2 country code.
    pub country_code: country::Code,

    /// The ISO-15118 ID.
    pub id: String,
}

impl<'buf> From<tariff::CpoId<'buf>> for CpoId {
    fn from(value: tariff::CpoId<'buf>) -> Self {
        let tariff::CpoId { country_code, id } = value;
        CpoId {
            country_code,
            id: id.to_string(),
        }
    }
}

/// Display the CPO ID formatted like `NLENE`.
impl fmt::Display for CpoId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}", self.country_code.into_alpha_2_str(), self.id)
    }
}

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

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

    /// Unique identifier of the Tariff that is relevant for this Charging Period.
    /// In the OCPI spec the `tariff_id` field is optional but, we always know the tariff ID
    /// when generating a CDR.
    pub tariff_id: Option<String>,
}

/// The volume that has been consumed for a specific dimension during a charging period.
///
/// * See: [OCPI spec 2.2.1: CDR Dimension](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc#mod_cdrs_cdrdimension_class>).
#[derive(Debug)]
pub struct Dimension {
    /// Which quantity this dimension measures.
    pub dimension_type: DimensionType,

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

/// The quantity a [`Dimension`] measures during a charging period.
///
/// * See: [OCPI spec 2.2.1: CDR DimensionType](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc#mod_cdrs_cdrdimensiontype_enum>).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DimensionType {
    /// Consumed energy in `kWh`.
    Energy,

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

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

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

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

    /// The parking time, in hours, consumed in this period.
    ParkingTime,

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

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

/// The config for generating a CDR from a tariff.
#[derive(Clone)]
pub struct Config {
    /// The timezone of the EVSE: The timezone where the chargesession took place.
    pub timezone: chrono_tz::Tz,

    /// The end date of the generated CDR.
    pub end_date_time: DateTime<Utc>,

    /// The maximum DC current that can be delivered to the battery.
    pub max_current_supply_amp: Decimal,

    /// The energy the session is asked to deliver, in kWh.
    ///
    /// Charging runs at `max_power_supply_kw` until this much has been delivered or the session
    /// ends, whichever is first, so this is what decides when charging stops and idling begins.
    /// The battery's existing state of charge is not modelled: with no charging curve the power is
    /// constant, so only the amount asked for matters.
    pub requested_kwh: Decimal,

    /// The maximum DC power (kW) that can be delivered to the battery.
    ///
    /// This is modeled as a DC system as we don't care if the delivery medium is DC or one of the
    /// various AC forms. We only care what the effective DC power is. The caller of `cdr_from_tariff`
    /// should convert the delivery medium into a DC kW power by using a power factor.
    ///
    /// In practice the maximum power bottleneck is either the EVSE, the cable or the battery itself.
    /// But whatever the bottleneck is, the caller should work that out and set the maximum expected.
    pub max_power_supply_kw: Decimal,

    /// The start date of the generated CDR.
    pub start_date_time: DateTime<Utc>,
}

/// Generate a CDR from a given tariff.
pub fn cdr_from_tariff(tariff_elem: &tariff::Versioned<'_>, config: &Config) -> Verdict<Report> {
    let mut warnings = warning::Set::new();
    // To generate a CDR from a tariff first, the tariff is parsed into structured data.
    // Then some broad metrics are calculated that define limits on the chargesession.
    //
    // A Timeline of Events is then constructed by generating Events for each Element and each restriction.
    // Some restrictions are periodic and can result in many `Event`s.
    //
    // The `Timeline` of `Event`s are then sorted by time and converted into a list of `ChargePeriods`.
    let (metrics, timezone) = metrics(tariff_elem, config)?.gather_warnings_into(&mut warnings);

    let tariff = tariff_elem.to_v221()?.gather_warnings_into(&mut warnings);

    if !is_tariff_active(&metrics.start_date_time, &tariff) {
        warnings.insert(tariff_elem.as_element(), tariff::Warning::NotActive.into());
    }

    let timeline = timeline(timezone, &metrics, &tariff);

    // Read before the timeline is consumed, because the generated CDR states these
    // quantities too. Stating them only in the periods handed to the pricer would leave the
    // emitted CDR repricing to a different total than the one reported here.
    let emit_current = timeline.emit_current;
    let emit_power = timeline.emit_power;

    let charging_periods = charge_periods(&metrics, timeline);

    let report = price::periods(metrics.end_date_time, timezone, &tariff, charging_periods)
        .with_element(tariff_elem.as_element())?
        .gather_warnings_into(&mut warnings);

    let price::PeriodsReport {
        billable: _,
        periods,
        totals,
        total_costs,
    } = report;

    let charging_periods = periods
        .into_iter()
        .map(|period| {
            let price::PeriodReport {
                start_date_time,
                end_date_time: _,
                dimensions,
            } = period;
            let duration_charging = dimensions.duration_charging.as_ref().map(|dim| Dimension {
                dimension_type: DimensionType::Time,
                volume: ToHoursDecimal::to_hours_dec_in_ocpi_precision(&dim.volume),
            });
            let duration_idle = dimensions.duration_idle.as_ref().map(|dim| Dimension {
                dimension_type: DimensionType::ParkingTime,
                volume: ToHoursDecimal::to_hours_dec_in_ocpi_precision(&dim.volume),
            });
            let energy = dimensions.energy.as_ref().map(|dim| Dimension {
                dimension_type: DimensionType::Energy,
                volume: dim.volume.into(),
            });
            // Current and power are stated only while charging, matching the periods the
            // pricer was given. Neither is billable - `price::Dimensions` does not contain them and
            // the cost computation ignores them - so stating them adds no charge and only lets a
            // reader of this CDR decide a `min_current`, `max_current`, `min_power` or `max_power`
            // restriction on evidence. Both bounds are stated because the supply is constant, and
            // because the pricer reads the minimum for an upper-bound restriction and the maximum
            // for a lower-bound one.
            let charging = duration_charging.is_some();

            let mut dimensions: Vec<Dimension> = vec![energy, duration_idle, duration_charging]
                .into_iter()
                .flatten()
                .collect();

            if charging && emit_current {
                let volume = Decimal::from(metrics.max_current_supply);
                dimensions.push(Dimension {
                    dimension_type: DimensionType::MaxCurrent,
                    volume,
                });
                dimensions.push(Dimension {
                    dimension_type: DimensionType::MinCurrent,
                    volume,
                });
            }

            if charging && emit_power {
                let volume = Decimal::from(metrics.max_power_supply);
                dimensions.push(Dimension {
                    dimension_type: DimensionType::MaxPower,
                    volume,
                });
                dimensions.push(Dimension {
                    dimension_type: DimensionType::MinPower,
                    volume,
                });
            }

            ChargingPeriod {
                start_date_time,
                dimensions,
                tariff_id: Some(tariff.id.to_string()),
            }
        })
        .collect();

    let mut total_cost = total_costs.total();

    if total_cost.is_none() {
        warnings.insert(tariff_elem.as_element(), Warning::NoElementPricesSession);
    }

    // The bounds come from `clamp_total_cost`, the function the pricer uses. A second copy
    // of the comparison here would let `generate` emit a CDR that the pricer then reports as
    // breaching the tariff it came from.
    let clamped = price::clamp_total_cost(&mut total_cost, tariff.min_price, tariff.max_price);

    if clamped.to_min {
        warnings.insert(
            tariff_elem.as_element(),
            tariff::Warning::TotalCostClampedToMin.into(),
        );
    }

    if clamped.to_max {
        warnings.insert(
            tariff_elem.as_element(),
            tariff::Warning::TotalCostClampedToMax.into(),
        );
    }

    if clamped.incl_vat_unknown {
        warnings.insert(
            tariff_elem.as_element(),
            tariff::Warning::TotalCostInclusiveVatUnknown.into(),
        );
    }

    if clamped.min_above_max {
        warnings.insert(
            tariff_elem.as_element(),
            tariff::Warning::MinPriceIsGreaterThanMax.into(),
        );
    }

    let report = Report {
        tariff_id: tariff.id.to_string(),
        tariff_currency_code: tariff.currency,
        partial_cdr: PartialCdr {
            party_id: tariff.party_id.map(CpoId::from),
            start_date_time: metrics.start_date_time,
            end_date_time: metrics.end_date_time,
            currency_code: tariff.currency,
            total_energy: totals.energy.round_to_ocpi_scale(),
            total_charging_duration: totals.duration_charging,
            total_idle_duration: totals.duration_idle,
            total_cost: total_cost.round_to_ocpi_scale(),
            total_energy_cost: total_costs.energy.round_to_ocpi_scale(),
            total_fixed_cost: total_costs.fixed.round_to_ocpi_scale(),
            total_idle_duration_cost: total_costs.duration_idle.round_to_ocpi_scale(),
            total_charging_duration_cost: total_costs.duration_charging.round_to_ocpi_scale(),
            charging_periods,
        },
    };

    Ok(report.into_caveat(warnings))
}

/// An `Event` collector that filters any `Event`s that are after the `session_end_time`.
struct EventCollector {
    /// The duration of the session, there is no point in adding events that occur after this.
    session_duration: TimeDelta,

    /// The list of `Event`s generated from the tariff.
    events: Vec<Event>,
}

impl EventCollector {
    /// Create a new `Event` collector from the duration of a session.
    fn with_session_duration(session_duration: TimeDelta) -> Self {
        Self {
            session_duration,
            events: vec![],
        }
    }

    /// Add an `Event` to the list if the start duration is within the session duration.
    fn push(&mut self, duration_from_start: TimeDelta, event_kind: EventKind) {
        if duration_from_start <= self.session_duration {
            self.events.push(Event {
                duration_from_start,
                kind: event_kind,
            });
        }
    }

    /// Consume the collector and return the list of `Event`s.
    fn into_inner(self) -> Vec<Event> {
        self.events
    }
}

/// Make a `Timeline` of `Event`s using the `Metric`s and `Tariff`.
fn timeline(
    timezone: chrono_tz::Tz,
    metrics: &Metrics,
    tariff: &tariff::v221::Tariff<'_>,
) -> Timeline {
    let Metrics {
        start_date_time: cdr_start,
        end_date_time: cdr_end,
        duration_charging,
        duration_parking,

        // The supply no longer decides whether a quantity is stated in the CDR. Whether
        // an element restricts on it does, and that is a property of the tariff alone.
        max_power_supply: _,
        max_current_supply: _,
        energy_supplied: _,
    } = metrics;

    let mut events = {
        let session_duration = duration_parking.map(|d| duration_charging.saturating_add(d));
        let mut events =
            EventCollector::with_session_duration(session_duration.unwrap_or(*duration_charging));

        events.push(TimeDelta::seconds(0), EventKind::SessionStart);
        events.push(*duration_charging, EventKind::ChargingEnd);

        if let Some(dt) = session_duration {
            events.push(
                dt,
                EventKind::ParkingEnd {
                    start: *duration_charging,
                },
            );
        }

        events
    };

    // True if `min_current` or `max_current` restrictions are defined.
    // Then we set current to be consumed for each period.
    let mut emit_current = false;

    // True if `min_power` or `max_power` restrictions are defined.
    // Then we set power to be consumed for each period.
    let mut emit_power = false;

    for elem in &tariff.elements {
        // Elements with a `reservation` restriction set never apply.
        // Applying them could result in inaccurate pricing.
        if elem
            .restrictions
            .as_ref()
            .is_some_and(|r| r.reservation.is_some())
        {
            continue;
        }

        if let Some((time_restrictions, energy_restrictions)) = elem
            .restrictions
            .as_ref()
            .map(tariff::v221::Restrictions::restrictions_by_category)
        {
            generate_time_events(
                &mut events,
                timezone,
                *cdr_start..*cdr_end,
                time_restrictions,
            );

            let v2x::EnergyRestrictions {
                min_kwh,
                max_kwh,
                min_current,
                max_current,
                min_power,
                max_power,
            } = energy_restrictions;

            // A quantity is stated in the CDR whenever an element restricts on it, and not
            // only when the supply falls inside that element's window. An absent dimension is read
            // as satisfying the restriction, so a CDR that omits the quantity has the pricer apply
            // the very element whose window excludes the supply.
            //
            // Note: The generator supplies maximum current and maximum power.
            emit_current |= min_current.is_some() || max_current.is_some();
            emit_power |= min_power.is_some() || max_power.is_some();

            generate_energy_events(
                &mut events,
                metrics.duration_charging,
                metrics.energy_supplied,
                min_kwh,
                max_kwh,
            );
        }
    }

    let events = events.into_inner();

    Timeline {
        events,
        emit_current,
        emit_power,
    }
}

/// Generate a list of `Event`s based on the `TimeRestrictions` an `Element` has.
fn generate_time_events(
    events: &mut EventCollector,
    timezone: chrono_tz::Tz,
    cdr_span: DateTimeSpan,
    restrictions: v2x::TimeRestrictions,
) {
    const MIDNIGHT: NaiveTime = NaiveTime::from_hms_opt(0, 0, 0)
        .expect("The hour, minute and second values are correct and hardcoded");

    let v2x::TimeRestrictions {
        start_time,
        end_time,
        start_date,
        end_date,
        min_duration,
        max_duration,
        weekdays,
    } = restrictions;

    let cdr_duration = cdr_span.end.signed_duration_since(cdr_span.start);

    if let Some(dt) = min_duration
        && cdr_duration > dt
    {
        events.push(dt, EventKind::MinDuration);
    }

    if let Some(dt) = max_duration
        && cdr_duration > dt
    {
        events.push(dt, EventKind::MaxDuration);
    }

    // The pricer judges a date restriction by the local date alone. So an element's dates
    // allow it from 00:00 local time on its `start_date` until 00:00 local time on its
    // `end_date`, whatever its `start_time` and `end_time`. For a window of 22:00 to 06:00:
    //
    //                       day 1       | day 2 (start_date)        | day 3 (end_date)
    //   time restriction   22:00 -------+------- 06:00    22:00 ----+--- 06:00
    //   date restriction                [---------------------------)
    //   both                            [------- 06:00    22:00 ----)
    //
    // See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariffrestrictions_class>
    let start_date_time = start_date
        .map(|d| d.and_time(MIDNIGHT))
        .and_then(|d| local_to_utc(timezone, d));
    let end_date_time = end_date
        .map(|d| d.and_time(MIDNIGHT))
        .and_then(|d| local_to_utc(timezone, d));

    let session_start = cdr_span.start;
    let session_end = cdr_span.end;

    // A date bound at or outside either end of the session doesn't split any charging period,
    // so only a date bound strictly inside the session gets an event.
    if let Some(start_date_time) = start_date_time
        && session_start < start_date_time
        && start_date_time < session_end
    {
        events.push(
            start_date_time.signed_duration_since(session_start),
            EventKind::StartDate,
        );
    }

    if let Some(end_date_time) = end_date_time
        && session_start < end_date_time
        && end_date_time < session_end
    {
        events.push(
            end_date_time.signed_duration_since(session_start),
            EventKind::EndDate,
        );
    }

    // If `start_date` or `end_date` is set we clamp the cdr_span to those dates.
    // As we are not going to produce any events before `start_date` or after `end_date`.
    let event_span = clamp_date_time_span(start_date_time, end_date_time, cdr_span);

    if let Some(start_time) = start_time {
        gen_naive_time_events(
            events,
            session_start,
            &event_span,
            timezone,
            start_time,
            &weekdays,
            EventKind::StartTime,
        );
    }

    if let Some(end_time) = end_time {
        gen_naive_time_events(
            events,
            session_start,
            &event_span,
            timezone,
            end_time,
            &weekdays,
            EventKind::EndTime,
        );
    }
}

/// Convert a `NaiveDateTime` to a `DateTime<Utc>` using the local timezone.
///
/// Return Some `DateTime<Utc>` if the conversion from `NaiveDateTime` results in either a single
/// or ambiguous `DateTime`. If the conversion is _ambiguous_ due to a _fold_ in the local time,
/// then we return the earliest `DateTime`.
fn local_to_utc(timezone: chrono_tz::Tz, date_time: NaiveDateTime) -> Option<DateTime<Utc>> {
    use chrono::offset::LocalResult;

    let result = date_time.and_local_timezone(timezone);

    let local_date_time = match result {
        LocalResult::Single(d) => d,
        LocalResult::Ambiguous(earliest, _latest) => earliest,
        LocalResult::None => return None,
    };

    Some(local_date_time.to_utc())
}

/// Generate `Event`s for the `start_time` or `end_time` restriction.
fn gen_naive_time_events(
    events: &mut EventCollector,
    session_start: DateTime<Utc>,
    event_span: &Range<DateTime<Utc>>,
    timezone: chrono_tz::Tz,
    time: NaiveTime,
    weekdays: &v2x::WeekdaySet,
    kind: EventKind,
) {
    let local_start_time = event_span.start.with_timezone(&timezone).time();
    let time_delta = time.signed_duration_since(local_start_time);
    let cdr_duration = event_span.end.signed_duration_since(event_span.start);

    // This function measures each event from the start of `event_span`, and a `start_date`
    // can make `event_span` start later than the session does.
    // `EventCollector::push` takes a duration from the session start, so every event is shifted
    // by `span_offset` before it is pushed.
    //
    //   session          [-----------------------------------)
    //   event_span                 [-------------------------)
    //   event                                    |
    //                    |<------->|<----------->|
    //                    span_offset  time_delta
    let span_offset = event_span.start.signed_duration_since(session_start);

    // If the time is before the local session start, advance to the next day's occurrence.
    let time_delta = if time_delta.num_seconds().is_negative() {
        time_delta.saturating_add(TimeDelta::days(1))
    } else {
        time_delta
    };

    // If the start delta is still negative after moving it forward 24 hours
    if time_delta.num_seconds().is_negative() {
        return;
    }

    // The time is after the CDR start.
    let Some(remainder) = cdr_duration.checked_sub(&time_delta) else {
        warn!("TimeDelta overflow");
        return;
    };

    if remainder.num_seconds().is_positive() {
        let duration_from_span_start = time_delta;
        let Some(date) = event_span
            .start
            .checked_add_signed(duration_from_span_start)
        else {
            warn!("Date out of range");
            return;
        };

        // The pricer judges `day_of_week` by the day in the EVSE's timezone.
        // Taking the weekday of the UTC `date` would judge a boundary near midnight
        // by the day before or after.
        if weekdays.contains(date.with_timezone(&timezone).weekday()) {
            let Some(duration_from_session_start) = span_offset.checked_add(&time_delta) else {
                warn!("TimeDelta overflow");
                return;
            };
            // The time is before the CDR end.
            events.push(duration_from_session_start, kind);
        }

        for day in 1..=remainder.num_days() {
            let Some(duration_from_span_start) = time_delta.checked_add(&TimeDelta::days(day))
            else {
                warn!("Date out of range");
                break;
            };
            let Some(date) = event_span
                .start
                .checked_add_signed(duration_from_span_start)
            else {
                warn!("Date out of range");
                break;
            };

            if weekdays.contains(date.with_timezone(&timezone).weekday()) {
                let Some(duration_from_session_start) =
                    span_offset.checked_add(&duration_from_span_start)
                else {
                    warn!("TimeDelta overflow");
                    break;
                };
                events.push(duration_from_session_start, kind);
            }
        }
    }
}

/// Generate a list of `Event`s based on the `TimeRestrictions` an `Element` has.
fn generate_energy_events(
    events: &mut EventCollector,
    duration_charging: TimeDelta,
    energy_supplied: Kwh,
    min_kwh: Option<Kwh>,
    max_kwh: Option<Kwh>,
) {
    if let Some(dt) = min_kwh.and_then(|kwh| power_to_time(kwh, energy_supplied, duration_charging))
    {
        events.push(dt, EventKind::MinKwh);
    }

    if let Some(dt) = max_kwh.and_then(|kwh| power_to_time(kwh, energy_supplied, duration_charging))
    {
        events.push(dt, EventKind::MaxKwh);
    }
}

/// Map power usage to time presuming a linear power consumption.
#[instrument]
fn power_to_time(power: Kwh, power_total: Kwh, duration_total: TimeDelta) -> Option<TimeDelta> {
    // Handle power == power_total as a special case to avoid loss of precision
    // due to TimeDelta -> Decimal -> TimeDelta conversion.
    if power == power_total {
        return Some(duration_total);
    }

    // Find the time that the `min_kwh` amount of power was reached.
    // It has to be within the charging time.
    let power = Decimal::from(power);
    // The total power supplied during the chargesession
    let power_total = Decimal::from(power_total);

    // The factor minimum of the total power supplied.
    let Some(factor) = power.checked_div(power_total) else {
        return Some(TimeDelta::zero());
    };

    if factor.is_sign_negative() || factor > dec!(1.0) {
        return None;
    }

    let hours_dec = duration_total.to_hours_dec();
    let duration_from_start = factor.checked_mul(hours_dec)?;
    Some(duration_from_start.to_duration())
}

/// Generate a list of charging periods for the given tariffs timeline.
fn charge_periods(metrics: &Metrics, timeline: Timeline) -> Vec<price::Period> {
    /// Keep track of whether we are charging or parking.
    enum ChargingPhase {
        Charging,
        Parking,
    }

    /// The energy supplied from the start of charging until `elapsed`, rounded to the four
    /// decimals OCPI fixes for a number.
    fn energy_supplied_by(power: Kw, elapsed: TimeDelta) -> Option<Decimal> {
        // Computing the energy as the power times `elapsed.to_hours_dec()` would bill an extra
        // step. That call divides the duration by the length of an hour, and the division
        // rounds. 6000 seconds becomes 1.666...667 hours at the 28 significant digits a `Decimal`
        // holds, so 24 kW would give 40.000...001 kWh, which a step size of 1000 Wh bills as
        // 41 kWh. Dividing last, as below, gives 40 kWh exactly.
        let nanos = elapsed.num_nanoseconds()?;
        let power_by_nanos = Decimal::from(power).checked_mul(nanos.into())?;
        let energy = power_by_nanos.checked_div(NANOS_IN_HOUR)?;

        // `metrics` rounds the charging time to the nearest nanosecond, so the energy supplied by
        // the end of charging can exceed the requested energy by a residue far below the fourth
        // decimal. 1 kWh at 7 kW charges for 514285714286 ns, which gives 1.000000000000556 kWh.
        // A step size bills any residue as a whole step. Rounding to four decimals makes the
        // pricer bill the 1 kWh the generated CDR states.
        Some(energy.round_to_ocpi_scale())
    }

    let Metrics {
        start_date_time: cdr_start,
        max_power_supply,
        max_current_supply,

        end_date_time: _,
        duration_charging: _,
        duration_parking: _,
        energy_supplied: _,
    } = metrics;

    let Timeline {
        mut events,
        emit_current,
        emit_power,
    } = timeline;

    events.sort_unstable_by_key(|e| e.duration_from_start);

    let mut periods = vec![];
    let emit_current = emit_current.then_some(*max_current_supply);
    let emit_power = emit_power.then_some(*max_power_supply);
    // Charging starts instantly in this model.
    let mut charging_phase = ChargingPhase::Charging;
    let mut energy_at_start = Decimal::ZERO;

    // Each pair of consecutive events bounds one period, so every event that `timeline`
    // collected starts a period, except the last, which ends the session. The periods from
    // `ChargingEnd` on are idle.
    //
    // For a session that charges from 20:00 to 23:00 and is idle until 00:00, against a tariff
    // with a `min_duration` of 1 hour and a `start_time` of 22:00:
    //
    //               20:00           21:00           22:00           23:00           00:00
    //   events      SessionStart    MinDuration     StartTime       ChargingEnd     ParkingEnd
    //   periods     [ charging ----)[ charging ----)[ charging ----)[ idle --------)
    for items in events.windows(2) {
        let [event, event_next] = items else {
            unreachable!("The window size is 2");
        };

        let Event {
            duration_from_start,
            kind,
        } = event;

        if let EventKind::ChargingEnd = kind {
            charging_phase = ChargingPhase::Parking;
        }

        let Some(duration) = event_next
            .duration_from_start
            .checked_sub(duration_from_start)
        else {
            warn!("TimeDelta overflow");
            break;
        };

        let Some(start_date_time) = cdr_start.checked_add_signed(*duration_from_start) else {
            warn!("TimeDelta overflow");
            break;
        };

        let consumed = if let ChargingPhase::Charging = charging_phase {
            // Rounding each period's energy separately would let the sum of the periods drift
            // from the energy supplied by up to 0.00005 kWh per period. Three periods of
            // 0.666...7 kWh would each state 0.6667, which sum to 2.0001 kWh for a session
            // supplying 2 kWh. A period's energy is instead the difference between the rounded
            // energy supplied by its end and by its start, so the periods up to any boundary sum
            // to the energy supplied by then, rounded once.
            let Some(energy_at_end) =
                energy_supplied_by(*max_power_supply, event_next.duration_from_start)
            else {
                warn!("Overflow computing the energy supplied");
                break;
            };
            let Some(energy) = energy_at_end.checked_sub(energy_at_start) else {
                warn!("Overflow computing the energy supplied");
                break;
            };
            energy_at_start = energy_at_end;
            price::Consumed {
                duration_charging: Some(duration),
                duration_idle: None,
                energy: Some(Kwh::from_decimal(energy)),
                current_max: emit_current,
                current_min: emit_current,
                power_max: emit_power,
                power_min: emit_power,
            }
        } else {
            price::Consumed {
                duration_charging: None,
                duration_idle: Some(duration),
                energy: None,
                current_max: None,
                current_min: None,
                power_max: None,
                power_min: None,
            }
        };

        let period = price::Period {
            start_date_time,
            consumed,
        };

        periods.push(period);
    }

    periods
}

/// A `DateTimeSpan` bounded by a minimum and a maximum.
///
/// If the input `DateTimeSpan` is less than `min_date` then this returns `min_date`.
/// If input is greater than `max_date` then this returns `max_date`.
/// Otherwise, this returns input `DateTimeSpan`.
fn clamp_date_time_span(
    min_date: Option<DateTime<Utc>>,
    max_date: Option<DateTime<Utc>>,
    span: DateTimeSpan,
) -> DateTimeSpan {
    // Swap the bounds only when both are present and out of order.
    //
    // A lone `min_date`, such as an element's `start_date` with no `end_date`, stays the start
    // bound.
    //
    //   span                 [-----------------------------)
    //   min_date                       |
    //   clamped span                   [-------------------)
    //
    // A lone `max_date` stays the end bound.
    //
    //   span                 [-----------------------------)
    //   max_date                                 |
    //   clamped span         [-------------------)
    let (min_date, max_date) = match (min_date, max_date) {
        (Some(min_date), Some(max_date)) => {
            (Some(min(min_date, max_date)), Some(max(min_date, max_date)))
        }
        bounds => bounds,
    };

    let start = min_date.filter(|d| &span.start < d).unwrap_or(span.start);
    let end = max_date.filter(|d| &span.end > d).unwrap_or(span.end);

    DateTimeSpan { start, end }
}

/// A timeline of events that are used to generate the `ChargePeriods` of the CDR.
struct Timeline {
    /// The list of `Event`s generated from the tariff.
    events: Vec<Event>,

    /// Some element restricts on current, so every charging period states the current.
    emit_current: bool,

    /// Some element restricts on power, so every charging period states the power.
    emit_power: bool,
}

/// An event at a time along the timeline.
struct Event {
    /// The duration of the Event from the start of the timeline/chargesession.
    duration_from_start: TimeDelta,

    /// The kind of Event.
    kind: EventKind,
}

impl fmt::Debug for Event {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Event")
            .field("duration_from_start", &self.duration_from_start.as_hms())
            .field("kind", &self.kind)
            .finish()
    }
}

/// The kind of `Event`.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum EventKind {
    /// The moment a session starts.
    ///
    /// This is added to the list of `Event`s so that the algorithm to generate the `ChargingPeriods`
    /// can iterate over the `Event`s using a window of size 2. The first iteration will always have
    /// `SessionStart` as the first window element and the `Event` of interest as the second.
    SessionStart,

    /// The moment charging ends.
    ///
    /// Charging starts at time 0. When `ChargingEnd`s, parking starts.
    /// This could also be the last `Event` of the chargesession.
    ChargingEnd,

    /// The moment Parking ends.
    ///
    /// This could also be the last `Event` of the chargesession.
    /// If a `ParkingEnd` `Event` is present in the `Timeline` then a `ChargingEnd` `Event` will precede it.
    ParkingEnd {
        /// The parking started when `ChargingEnd`ed.
        start: TimeDelta,
    },

    StartTime,

    EndTime,

    /// 00:00 local time on an element's `start_date`, the first moment its dates allow.
    StartDate,

    /// 00:00 local time on an element's `end_date`, the first moment its dates exclude.
    EndDate,

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

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

    /// Minimum consumed energy in kWh, for example 20, valid from this amount of energy (inclusive) being used.
    MinKwh,

    /// Maximum consumed energy in kWh, for example 50, valid until this amount of energy (exclusive) being used.
    MaxKwh,
}

impl fmt::Debug for EventKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::SessionStart => write!(f, "SessionStart"),
            Self::ChargingEnd => write!(f, "ChargingEnd"),
            Self::ParkingEnd { start } => f
                .debug_struct("ParkingEnd")
                .field("start", &start.as_hms())
                .finish(),
            Self::StartTime => write!(f, "StartTime"),
            Self::EndTime => write!(f, "EndTime"),
            Self::StartDate => write!(f, "StartDate"),
            Self::EndDate => write!(f, "EndDate"),
            Self::MinDuration => write!(f, "MinDuration"),
            Self::MaxDuration => write!(f, "MaxDuration"),
            Self::MinKwh => write!(f, "MinKwh"),
            Self::MaxKwh => write!(f, "MaxKwh"),
        }
    }
}

/// Broad metrics calculated about the chargesession which is given as input for generating a `Timeline` of `Event`s.
#[derive(Debug)]
struct Metrics {
    /// The end date the generated CDR.
    end_date_time: DateTime<Utc>,

    /// The start date the generated CDR.
    start_date_time: DateTime<Utc>,

    /// The time spent charging the battery.
    ///
    /// Charging begins instantly and continues without interruption until the battery is full or the
    /// session time has elapsed.
    duration_charging: TimeDelta,

    /// The time spent parking after charging the battery.
    ///
    /// This duration may be `None` if the battery did not finish charging within the session time.
    duration_parking: Option<TimeDelta>,

    /// The energy that's supplied during the charging period.
    energy_supplied: Kwh,

    /// The maximum DC current that can be delivered to the battery.
    max_current_supply: Ampere,

    /// The maximum DC power that can be delivered to the battery.
    max_power_supply: Kw,
}

/// Validate the `Config` and compute various `Metrics` based on the `Config`s fields.
#[instrument(skip_all)]
fn metrics(elem: &tariff::Versioned<'_>, config: &Config) -> Verdict<(Metrics, chrono_tz::Tz)> {
    let warnings = warning::Set::new();

    let Config {
        start_date_time,
        end_date_time,
        max_power_supply_kw,
        requested_kwh: max_energy_battery_kwh,
        max_current_supply_amp,
        timezone,
    } = config;
    let duration_session = end_date_time.signed_duration_since(start_date_time);

    debug!("duration_session: {}", duration_session.as_hms());

    // Duration must be positive, if the end time is before the start the conversion will fail.
    if duration_session.abs() != duration_session {
        return warnings.bail(elem.as_element(), Warning::StartDateTimeIsAfterEndDateTime);
    }

    if duration_session.num_seconds() < MIN_CS_DURATION_SECS {
        return warnings.bail(elem.as_element(), Warning::DurationBelowMinimum);
    }

    if max_energy_battery_kwh.is_zero() {
        return warnings.bail(elem.as_element(), Warning::RequestedKwhIsZero);
    }

    // The time needed to charge the battery = battery_capacity (kWh) / power (kW)
    let duration_full_charge = some_dec_or_bail!(
        elem,
        max_energy_battery_kwh.checked_div(*max_power_supply_kw),
        warnings,
        "Unable to calculate charging time"
    )
    .to_duration();
    debug!("duration_full_charge: {}", duration_full_charge.as_hms());

    // The charge duration taking into account that the end of the session can occur before the battery is fully charged.
    let duration_charging = TimeDelta::min(duration_full_charge, duration_session);

    let energy_supplied_kwh = some_dec_or_bail!(
        elem,
        max_power_supply_kw.checked_mul(duration_charging.to_hours_dec()),
        warnings,
        "Unable to calculate the energy supplied during the charging time"
    );

    let duration_parking = some_time_delta_or_bail!(
        elem,
        duration_session.checked_sub(&duration_charging),
        warnings,
        "Unable to calculate `idle_duration`"
    );

    debug!(
        "duration_charging: {}, duration_parking: {}",
        duration_charging.as_hms(),
        duration_parking.as_hms()
    );

    let metrics = Metrics {
        end_date_time: *end_date_time,
        start_date_time: *start_date_time,
        duration_charging,
        duration_parking: Some(duration_parking).filter(|dt| dt.num_seconds().is_positive()),
        energy_supplied: Kwh::from_decimal(energy_supplied_kwh),
        max_current_supply: Ampere::from_decimal(*max_current_supply_amp),
        max_power_supply: Kw::from_decimal(*max_power_supply_kw),
    };

    Ok((metrics, *timezone).into_caveat(warnings))
}

fn is_tariff_active(cdr_start: &DateTime<Utc>, tariff: &tariff::v221::Tariff<'_>) -> bool {
    match (tariff.start_date_time, tariff.end_date_time) {
        (None, None) => true,
        (None, Some(end)) => (..end).contains(cdr_start),
        (Some(start), None) => (start..).contains(cdr_start),
        (Some(start), Some(end)) => (start..end).contains(cdr_start),
    }
}

#[derive(Debug)]
/// The warnings that happen when generating a CDR from a tariff.
pub enum Warning {
    /// A `Decimal` operation failed.
    Decimal(&'static str),

    /// The duration of the chargesession is below the minimum allowed.
    DurationBelowMinimum,

    /// No element of the tariff prices any part of the session. The generated `PartialCdr` has a
    /// `total_cost` of `None`, unless the tariff has a `min_price`, which then becomes the
    /// `total_cost`.
    NoElementPricesSession,

    /// Raised while pricing the generated CDR.
    Price(price::Warning),

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

    /// The `requested_kwh` in the `Config` is zero.
    RequestedKwhIsZero,

    /// Raised while reading the tariff to generate from.
    Tariff(tariff::Warning),

    /// A `TimeDelta` operation failed.
    TimeDelta(&'static str),
}

impl crate::Warning for Warning {
    fn id(&self) -> warning::Id {
        match self {
            Self::Decimal(_) => warning::Id::from_static("decimal_error"),
            Self::DurationBelowMinimum => warning::Id::from_static("duration_below_minimum"),
            Self::NoElementPricesSession => warning::Id::from_static("no_element_prices_session"),
            Self::Price(kind) => kind.id(),
            Self::StartDateTimeIsAfterEndDateTime => {
                warning::Id::from_static("start_time_after_end_time")
            }
            Self::RequestedKwhIsZero => warning::Id::from_static("requested_kwh_is_zero"),
            Self::TimeDelta(_) => warning::Id::from_static("timedelta_error"),
            Self::Tariff(kind) => kind.id(),
        }
    }
}

impl fmt::Display for Warning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Decimal(msg) | Self::TimeDelta(msg) => f.write_str(msg),
            Self::DurationBelowMinimum => write!(
                f,
                "The duration of the chargesession is below the minimum: {MIN_CS_DURATION_SECS}"
            ),
            Self::NoElementPricesSession => {
                write!(f, "No element of the tariff prices any part of the session")
            }
            Self::Price(warnings) => {
                write!(f, "Price warnings: {warnings:?}")
            }
            Self::StartDateTimeIsAfterEndDateTime => {
                write!(f, "The `start_date_time` is after the `end_date_time`")
            }
            Self::RequestedKwhIsZero => write!(f, "The `requested_kwh` in the `Config` is zero"),
            Self::Tariff(warnings) => {
                write!(f, "Tariff warnings: {warnings:?}")
            }
        }
    }
}

from_warning_all!(
    tariff::Warning => Warning::Tariff,
    price::Warning => Warning::Price
);