1#[cfg(test)]
5pub mod test;
6
7#[cfg(test)]
8mod test_periods;
9
10#[cfg(test)]
11mod test_real_world;
12
13#[cfg(test)]
14mod test_validate_cdr;
15
16#[cfg(test)]
17mod test_current_and_power_restrictions;
18
19#[cfg(test)]
20mod test_reservation_restriction;
21
22#[cfg(test)]
23mod test_time_of_day_restrictions;
24
25#[cfg(test)]
26mod test_min_max_price;
27
28#[cfg(test)]
29mod test_step_size;
30
31#[cfg(test)]
32mod test_failed_price;
33
34mod tariff;
35pub(crate) mod v211;
36pub(crate) mod v221;
37
38use std::fmt;
39
40use jiff::{SignedDuration, Timestamp, tz::TimeZone};
41use rust_decimal::Decimal;
42use tariff::Tariff;
43use tracing::{debug, instrument, trace};
44
45use crate::{
46 Ampere, Cost, DisplayOption, Kw, Kwh, Money, Price, SaturatingAdd as _, SaturatingSub,
47 currency,
48 duration::{self, AsHms as _, Hms},
49 from_warning_all, json,
50 money::VatOrigin,
51 number::RoundDecimal as _,
52 schema::{self, HasElement as _},
53 version::Versioned as _,
54 warning,
55};
56
57pub type Verdict<T> = crate::Verdict<T, Warning>;
59
60#[derive(Debug)]
65struct PeriodNormalized {
66 consumed: Consumed,
68
69 start_snapshot: TotalsSnapshot,
71
72 end_snapshot: TotalsSnapshot,
74}
75
76#[derive(Clone)]
78#[cfg_attr(test, derive(Default))]
79pub(crate) struct Consumed {
80 pub current_max: Option<Ampere>,
82
83 pub current_min: Option<Ampere>,
85
86 pub duration_charging: Option<SignedDuration>,
88
89 pub duration_idle: Option<SignedDuration>,
91
92 pub energy: Option<Kwh>,
94
95 pub power_max: Option<Kw>,
97
98 pub power_min: Option<Kw>,
100}
101
102impl fmt::Debug for Consumed {
103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 f.debug_struct("Consumed")
105 .field("current_max", &self.current_max)
106 .field("current_min", &self.current_min)
107 .field(
108 "duration_charging",
109 &self.duration_charging.map(|dt| dt.as_hms()),
110 )
111 .field("duration_idle", &self.duration_idle.map(|dt| dt.as_hms()))
112 .field("energy", &self.energy)
113 .field("power_max", &self.power_max)
114 .field("power_min", &self.power_min)
115 .finish()
116 }
117}
118
119#[derive(Clone)]
121struct TotalsSnapshot {
122 date_time: Timestamp,
124
125 energy: Kwh,
127
128 local_timezone: TimeZone,
130
131 duration_charging: SignedDuration,
133
134 duration_total: SignedDuration,
136}
137
138impl fmt::Debug for TotalsSnapshot {
139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140 f.debug_struct("TotalsSnapshot")
141 .field("date_time", &self.date_time)
142 .field("energy", &self.energy)
143 .field("local_timezone", &self.local_timezone)
144 .field("duration_charging", &self.duration_charging.as_hms())
145 .field("duration_total", &self.duration_total.as_hms())
146 .finish()
147 }
148}
149
150impl TotalsSnapshot {
151 fn zero(date_time: Timestamp, local_timezone: TimeZone) -> Self {
153 Self {
154 date_time,
155 energy: Kwh::zero(),
156 local_timezone,
157 duration_charging: SignedDuration::ZERO,
158 duration_total: SignedDuration::ZERO,
159 }
160 }
161
162 fn next(&self, consumed: &Consumed, date_time: Timestamp) -> Self {
164 let duration = date_time.duration_since(self.date_time);
165
166 let mut next = Self {
167 date_time,
168 energy: self.energy,
169 local_timezone: self.local_timezone.clone(),
170 duration_charging: self.duration_charging,
171 duration_total: self.duration_total.saturating_add(duration),
172 };
173
174 if let Some(duration) = consumed.duration_charging {
175 next.duration_charging = next.duration_charging.saturating_add(duration);
176 }
177
178 if let Some(energy) = consumed.energy {
179 next.energy = next.energy.saturating_add(energy);
180 }
181 next
182 }
183
184 fn local_time(&self) -> jiff::civil::Time {
186 self.local_timezone.to_datetime(self.date_time).time()
187 }
188
189 fn local_date(&self) -> jiff::civil::Date {
191 self.local_timezone.to_datetime(self.date_time).date()
192 }
193
194 fn local_weekday(&self) -> jiff::civil::Weekday {
196 self.local_timezone.to_datetime(self.date_time).weekday()
197 }
198}
199
200pub struct Report {
203 pub periods: Vec<PeriodReport>,
205
206 pub tariff_used: TariffOrigin,
208
209 pub timezone: TimeZone,
211
212 pub billed_charging_time: Option<SignedDuration>,
215
216 pub billed_energy: Option<Kwh>,
218
219 pub billed_idle_time: Option<SignedDuration>,
221
222 pub total_charging_time: Option<SignedDuration>,
228
229 pub total_energy: Total<Kwh, Option<Kwh>>,
231
232 pub total_idle_time: Total<Option<SignedDuration>>,
239
240 pub total_time: Total<SignedDuration>,
242
243 pub total_cost: Total<Price, Option<Price>>,
252
253 pub total_energy_cost: Total<Option<Price>>,
255
256 pub total_fixed_cost: Total<Option<Price>>,
259
260 pub total_idle_cost: Total<Option<Price>>,
267
268 pub total_charging_time_cost: Total<Option<Price>>,
273}
274
275impl fmt::Debug for Report {
276 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277 f.debug_struct("Report")
278 .field("periods", &self.periods)
279 .field("tariff_used", &self.tariff_used)
280 .field("timezone", &self.timezone)
281 .field(
282 "billed_charging_time",
283 &self.billed_charging_time.map(|dt| dt.as_hms()),
284 )
285 .field("billed_energy", &self.billed_energy)
286 .field(
287 "billed_idle_time",
288 &self.billed_idle_time.map(|dt| dt.as_hms()),
289 )
290 .field(
291 "total_charging_time",
292 &self.total_charging_time.map(|dt| dt.as_hms()),
293 )
294 .field("total_energy", &self.total_energy)
295 .field("total_idle_time", &self.total_idle_time)
296 .field("total_time", &self.total_time)
297 .field("total_cost", &self.total_cost)
298 .field("total_energy_cost", &self.total_energy_cost)
299 .field("total_fixed_cost", &self.total_fixed_cost)
300 .field("total_idle_cost", &self.total_idle_cost)
301 .field("total_charging_time_cost", &self.total_charging_time_cost)
302 .finish()
303 }
304}
305
306#[derive(Debug)]
308pub enum Warning {
309 Duration(duration::Warning),
311
312 MinPriceIsGreaterThanMax,
320
321 NoValidTariff,
334
335 PeriodsStateNoTime,
341
342 ReservationElementSkipped,
350
351 TotalCostClampedToMax,
355
356 TotalCostClampedToMin,
361
362 TotalCostInclusiveVatUnknown,
380}
381
382impl fmt::Display for Warning {
383 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384 match self {
385 Self::Duration(warning) => write!(f, "{warning}"),
386 Self::MinPriceIsGreaterThanMax => write!(
387 f,
388 "The given tariff has a `min_price` that is above its `max_price`, so no total \
389 can satisfy both."
390 ),
391 Self::NoValidTariff => {
392 f.write_str("No valid tariff has been found in the list of provided tariffs")
393 }
394 Self::PeriodsStateNoTime => f.write_str(
395 "No charging period has a `TIME` or `PARKING_TIME` dimension, but the tariff prices \
396 time",
397 ),
398 Self::ReservationElementSkipped => f.write_str(
399 "A tariff element has a `reservation` restriction and will not apply to regular \
400 charging sessions. Reservation pricing is not supported.",
401 ),
402 Self::TotalCostClampedToMax => write!(
403 f,
404 "The given tariff has a `max_price` set and the `total_cost` exceeded it."
405 ),
406 Self::TotalCostClampedToMin => write!(
407 f,
408 "The given tariff has a `min_price` set and the `total_cost` was below it, or no \
409 cost was calculated at all."
410 ),
411 Self::TotalCostInclusiveVatUnknown => write!(
412 f,
413 "The given tariff has a `min_price` that states no value including VAT, and it \
414 raised the total cost excluding VAT to a value implying a negative VAT rate \
415 against the total cost including VAT, so the total cost including VAT is no \
416 longer known."
417 ),
418 }
419 }
420}
421
422impl crate::Warning for Warning {
423 fn id(&self) -> warning::Id {
424 match self {
425 Self::Duration(warning) => warning.id(),
426 Self::MinPriceIsGreaterThanMax => {
427 warning::Id::from_static("min_price_is_greater_than_max")
428 }
429 Self::NoValidTariff => warning::Id::from_static("no_valid_tariff"),
430 Self::PeriodsStateNoTime => warning::Id::from_static("periods_state_no_time"),
431 Self::ReservationElementSkipped => {
432 warning::Id::from_static("reservation_element_skipped")
433 }
434 Self::TotalCostClampedToMax => warning::Id::from_static("total_cost_clamped_to_max"),
435 Self::TotalCostClampedToMin => warning::Id::from_static("total_cost_clamped_to_min"),
436 Self::TotalCostInclusiveVatUnknown => {
437 warning::Id::from_static("total_cost_inclusive_vat_unknown")
438 }
439 }
440 }
441
442 fn is_rejected(&self) -> bool {
443 match self {
444 Self::Duration(_)
445 | Self::MinPriceIsGreaterThanMax
446 | Self::NoValidTariff
447 | Self::PeriodsStateNoTime
448 | Self::ReservationElementSkipped
449 | Self::TotalCostClampedToMax
450 | Self::TotalCostClampedToMin
451 | Self::TotalCostInclusiveVatUnknown => false,
452 }
453 }
454}
455
456from_warning_all!(duration::Warning => Warning::Duration);
457
458#[derive(Clone, Debug)]
460pub struct TariffOrigin {
461 pub index: usize,
463
464 pub id: String,
466
467 pub currency: currency::Code,
469}
470
471#[derive(Debug)]
473pub(crate) struct Period {
474 pub start_date_time: Timestamp,
476
477 pub consumed: Consumed,
479}
480
481#[derive(Debug)]
484pub struct Dimensions {
485 pub energy: Option<Dimension<Kwh>>,
487
488 pub flat: Dimension<()>,
490
491 pub duration_charging: Option<Dimension<SignedDuration>>,
493
494 pub duration_idle: Option<Dimension<SignedDuration>>,
496}
497
498impl Dimensions {
499 fn new(components: ComponentSet, consumed: &Consumed) -> Self {
501 let ComponentSet {
502 energy: energy_price,
503 flat: flat_price,
504 duration_charging: duration_charging_price,
505 duration_idle: duration_idle_price,
506 } = components;
507
508 let Consumed {
509 duration_charging,
510 duration_idle,
511 energy,
512 current_max: _,
513 current_min: _,
514 power_max: _,
515 power_min: _,
516 } = consumed;
517
518 Self {
519 energy: (*energy).map(|e| Dimension {
520 price: energy_price,
521 volume: e,
522 billed_volume: e,
523 }),
524 flat: Dimension {
525 price: flat_price,
526 volume: (),
527 billed_volume: (),
528 },
529 duration_charging: (*duration_charging).map(|dc| Dimension {
530 price: duration_charging_price,
531 volume: dc,
532 billed_volume: dc,
533 }),
534 duration_idle: (*duration_idle).map(|di| Dimension {
535 price: duration_idle_price,
536 volume: di,
537 billed_volume: di,
538 }),
539 }
540 }
541}
542
543#[derive(Debug)]
544pub struct Dimension<V> {
546 pub price: Option<Component>,
550
551 pub volume: V,
553
554 pub billed_volume: V,
562}
563
564impl<V: Cost> Dimension<V> {
565 pub fn cost(&self) -> Option<Price> {
567 let Some(price_component) = &self.price else {
568 return None;
569 };
570
571 let excl_vat = self.billed_volume.cost(price_component.price);
572
573 let incl_vat = match price_component.vat {
574 VatOrigin::Provided(vat) => Some(excl_vat.apply_vat(vat)),
575 VatOrigin::NotProvided => Some(excl_vat),
576 VatOrigin::Unknown => None,
577 };
578
579 Some(Price { excl_vat, incl_vat })
580 }
581}
582
583#[derive(Debug)]
588pub struct ComponentSet {
589 pub energy: Option<Component>,
591
592 pub flat: Option<Component>,
594
595 pub duration_charging: Option<Component>,
597
598 pub duration_idle: Option<Component>,
600}
601
602impl ComponentSet {
603 fn has_all_components(&self) -> bool {
605 let Self {
606 energy,
607 flat,
608 duration_charging,
609 duration_idle,
610 } = self;
611
612 flat.is_some() && energy.is_some() && duration_idle.is_some() && duration_charging.is_some()
613 }
614}
615
616#[derive(Clone, Debug)]
621pub struct Component {
622 price: Money,
624
625 vat: VatOrigin,
628
629 step_size: u64,
637}
638
639impl Component {
640 fn new(component: &crate::tariff::v221::PriceComponent) -> Self {
642 let crate::tariff::v221::PriceComponent {
643 price,
644 vat,
645 step_size,
646 dimension_type: _,
647 } = component;
648
649 Self {
650 price: *price,
651 vat: *vat,
652 step_size: *step_size,
653 }
654 }
655
656 pub fn price(&self) -> Money {
658 self.price
659 }
660}
661
662#[derive(Debug)]
675pub struct Total<TCdr, TCalc = TCdr> {
676 pub cdr: TCdr,
678
679 pub calculated: TCalc,
681}
682
683#[instrument(skip_all)]
687pub(super) fn cdr(
688 cdr: &crate::cdr::Cdr<'_>,
689 tariffs: &[crate::tariff::Tariff<'_>],
690 timezone: &TimeZone,
691) -> Verdict<Report> {
692 let mut warnings = warning::Gatherer::new();
693 let report = price_v221_cdr_with_tariffs(cdr, tariffs, timezone, &mut warnings);
694 warnings.into_verdict(report)
695}
696
697fn price_v221_cdr_with_tariffs(
706 cdr: &crate::cdr::Cdr<'_>,
707 tariffs: &[crate::tariff::Tariff<'_>],
708 timezone: &TimeZone,
709 warnings: &mut dyn warning::Gather<Warning>,
710) -> Result<Report, warning::Error<Warning>> {
711 let cdr_elem = cdr.as_checked();
712 let cdr = cdr.as_v221();
713 debug!(?timezone, version = ?cdr_elem.version(), "Pricing CDR");
714 let v221::Cdr {
715 start_date_time,
716 end_date_time,
717 charging_periods,
718 kind,
719 totals: cdr_totals,
720 } = cdr;
721
722 debug!(tariffs = ?tariffs.iter().map(|t| t.as_v221().id).collect::<Vec<_>>(), "Pricing with tariffs(by id)");
723
724 let tariffs_normalized = tariff::normalize_all(tariffs);
725 let Some((tariff_index, tariff)) =
726 tariff::find_first_active(tariffs_normalized, *start_date_time)
727 else {
728 return Err(warning::Error::new(
729 cdr_elem.as_element(),
730 Warning::NoValidTariff,
731 ));
732 };
733
734 debug!(tariff_index, id = ?tariff.id(), "Found active tariff");
735 debug!(timezone = timezone.iana_name(), "Found timezone");
736
737 let periods_state_time = charging_periods.iter().any(|period| {
738 period.dimensions.iter().any(|dimension| {
739 matches!(
740 dimension.dimension_type,
741 v221::cdr::DimensionType::Time | v221::cdr::DimensionType::ParkingTime
742 )
743 })
744 });
745
746 if !periods_state_time && tariff.has_time_components() {
747 let charging_periods_elem = match cdr_elem.schema() {
750 crate::cdr::Version::V211(ir) => match &ir.charging_periods {
751 schema::Integrity::Ok(list) => list.element(),
752 schema::Integrity::Missing(_) | schema::Integrity::Err(_) => cdr_elem.as_element(),
753 },
754 crate::cdr::Version::V221(ir) => match &ir.charging_periods {
755 schema::Integrity::Ok(list) => list.element(),
756 schema::Integrity::Missing(_) | schema::Integrity::Err(_) => cdr_elem.as_element(),
757 },
758 };
759
760 warnings.insert(charging_periods_elem, Warning::PeriodsStateNoTime);
761 }
762
763 let periods = charging_periods.iter().map(Period::from).collect();
765
766 let periods = normalize_periods(periods, *end_date_time, timezone);
767 let price_cdr_report = price_periods(&periods, &tariff, cdr_elem.as_element(), warnings)?;
768
769 let mut report = generate_report(
770 cdr_totals,
771 timezone,
772 price_cdr_report,
773 TariffOrigin {
774 index: tariff_index,
775 id: tariff.id().to_owned(),
776 currency: tariff.currency(),
777 },
778 );
779
780 let clamped = clamp_total_cost(
781 &mut report.total_cost.calculated,
782 tariff.min_price(),
783 tariff.max_price(),
784 );
785
786 if clamped.to_min {
787 warnings.insert(cdr_elem.as_element(), Warning::TotalCostClampedToMin);
788 }
789
790 if clamped.to_max {
791 warnings.insert(cdr_elem.as_element(), Warning::TotalCostClampedToMax);
792 }
793
794 if clamped.incl_vat_unknown {
795 warnings.insert(cdr_elem.as_element(), Warning::TotalCostInclusiveVatUnknown);
796 }
797
798 if clamped.min_above_max {
799 warnings.insert(cdr_elem.as_element(), Warning::MinPriceIsGreaterThanMax);
800 }
801
802 if *kind == v221::cdr::Kind::Credit {
806 report.total_cost.calculated = report.total_cost.calculated.map(Price::negate);
807 }
808
809 Ok(report)
810}
811
812pub(crate) fn clamp_total_cost(
848 total_cost: &mut Option<Price>,
849 min_price: Option<Price>,
850 max_price: Option<Price>,
851) -> Clamped {
852 let min_above_max = match (min_price, max_price) {
857 (Some(min_price), Some(max_price)) => min_price.exceeds_on_either_value(max_price),
858 _ => false,
859 };
860
861 let mut clamped = Clamped {
862 to_min: false,
863 to_max: false,
864 incl_vat_unknown: false,
865 min_above_max,
866 };
867
868 if let Some(min_price) = min_price {
869 match total_cost.as_mut() {
870 None => {
871 *total_cost = Some(min_price);
872 clamped.to_min = true;
873 }
874 Some(total_cost) => {
875 if total_cost.excl_vat < min_price.excl_vat {
876 total_cost.excl_vat = min_price.excl_vat;
877 clamped.to_min = true;
878
879 if min_price.incl_vat.is_none() && !total_cost.vat_is_consistent() {
884 total_cost.incl_vat = None;
885 clamped.incl_vat_unknown = true;
886 }
887 }
888
889 let below_incl = match (total_cost.incl_vat, min_price.incl_vat) {
890 (Some(total_incl), Some(min_incl)) => total_incl < min_incl,
891 _ => false,
892 };
893
894 if below_incl {
895 total_cost.incl_vat = min_price.incl_vat;
896 clamped.to_min = true;
897 }
898 }
899 }
900 }
901
902 if let Some(max_price) = max_price
903 && let Some(total_cost) = total_cost.as_mut()
904 {
905 if total_cost.excl_vat > max_price.excl_vat {
906 total_cost.excl_vat = max_price.excl_vat;
907 clamped.to_max = true;
908 }
909
910 let above_incl = match (total_cost.incl_vat, max_price.incl_vat) {
911 (Some(total_incl), Some(max_incl)) => total_incl > max_incl,
912 _ => false,
913 };
914
915 if above_incl {
916 total_cost.incl_vat = max_price.incl_vat;
917 clamped.to_max = true;
918 }
919 }
920
921 clamped
922}
923
924pub(crate) struct Clamped {
930 pub to_min: bool,
934
935 pub to_max: bool,
937
938 pub incl_vat_unknown: bool,
945
946 pub min_above_max: bool,
951}
952
953pub(crate) fn periods(
958 end_date_time: Timestamp,
959 timezone: &TimeZone,
960 tariff_elem: &crate::tariff::v221::Tariff<'_>,
961 mut periods: Vec<Period>,
962 elem: &json::Element<'_>,
963 warnings: &mut dyn warning::Gather<Warning>,
964) -> Result<PeriodsReport, warning::Error<Warning>> {
965 periods.sort_by_key(|p| p.start_date_time);
968 let tariff = Tariff::from_v221(tariff_elem);
969 let periods = normalize_periods(periods, end_date_time, timezone);
970 price_periods(&periods, &tariff, elem, warnings)
971}
972
973fn normalize_periods(
974 periods: Vec<Period>,
975 end_date_time: Timestamp,
976 local_timezone: &TimeZone,
977) -> Vec<PeriodNormalized> {
978 debug!("Normalizing CDR periods");
979
980 let mut previous_end_snapshot = Option::<TotalsSnapshot>::None;
982
983 let end_dates = {
985 let mut end_dates = periods
986 .iter()
987 .skip(1)
988 .map(|p| p.start_date_time)
989 .collect::<Vec<_>>();
990
991 end_dates.push(end_date_time);
993 end_dates
994 };
995
996 periods
997 .into_iter()
998 .zip(end_dates)
999 .enumerate()
1000 .map(|(index, (period, end_date_time))| {
1001 trace!(index, "processing\n{period:#?}");
1002 let Period {
1003 start_date_time,
1004 mut consumed,
1005 } = period;
1006
1007 let period_length = end_date_time.duration_since(start_date_time);
1008 consumed.duration_charging = consumed
1009 .duration_charging
1010 .map(|duration| snap_to_period_length(duration, period_length));
1011 consumed.duration_idle = consumed
1012 .duration_idle
1013 .map(|duration| snap_to_period_length(duration, period_length));
1014
1015 let period = if let Some(prev_end_snapshot) = previous_end_snapshot.take() {
1016 let start_snapshot = prev_end_snapshot;
1017 let end_snapshot = start_snapshot.next(&consumed, end_date_time);
1018
1019 let period = PeriodNormalized {
1020 consumed,
1021 start_snapshot,
1022 end_snapshot,
1023 };
1024 trace!("Adding new period based on the last added\n{period:#?}");
1025 period
1026 } else {
1027 let start_snapshot = TotalsSnapshot::zero(start_date_time, local_timezone.clone());
1028 let end_snapshot = start_snapshot.next(&consumed, end_date_time);
1029
1030 let period = PeriodNormalized {
1031 consumed,
1032 start_snapshot,
1033 end_snapshot,
1034 };
1035 trace!("Adding new period\n{period:#?}");
1036 period
1037 };
1038
1039 previous_end_snapshot.replace(period.end_snapshot.clone());
1040 period
1041 })
1042 .collect::<Vec<_>>()
1043}
1044
1045fn snap_to_period_length(
1057 duration: SignedDuration,
1058 period_length: SignedDuration,
1059) -> SignedDuration {
1060 const HALF_OF_OCPI_HOURS_RESOLUTION: SignedDuration = SignedDuration::from_millis(180);
1061
1062 if duration.is_zero() {
1067 return duration;
1068 }
1069
1070 let difference = SaturatingSub::saturating_sub(duration, period_length).abs();
1073
1074 if difference <= HALF_OF_OCPI_HOURS_RESOLUTION {
1075 period_length
1076 } else {
1077 duration
1078 }
1079}
1080
1081fn price_periods(
1086 periods: &[PeriodNormalized],
1087 tariff: &Tariff,
1088 elem: &json::Element<'_>,
1089 warnings: &mut dyn warning::Gather<Warning>,
1090) -> Result<PeriodsReport, warning::Error<Warning>> {
1091 debug!(count = periods.len(), "Pricing CDR periods");
1092
1093 if tracing::enabled!(tracing::Level::TRACE) {
1094 trace!("# CDR period list:");
1095 for period in periods {
1096 trace!("{period:#?}");
1097 }
1098 }
1099
1100 let period_totals = period_totals(periods, tariff);
1101 let billed = period_totals
1102 .calculate_billed()
1103 .map_err(|warning| warning::Error::new(elem, warning))?;
1104
1105 if tariff.has_reservation_elements() {
1106 warnings.insert(elem, Warning::ReservationElementSkipped);
1107 }
1108
1109 let (billable, periods, totals) = billed;
1110 let total_costs = total_costs(&periods, tariff);
1111 let report = PeriodsReport {
1112 billable,
1113 periods,
1114 totals,
1115 total_costs,
1116 };
1117
1118 Ok(report)
1119}
1120
1121pub(crate) struct PeriodsReport {
1123 pub billable: Billable,
1125
1126 pub periods: Vec<PeriodReport>,
1128
1129 pub totals: Totals,
1131
1132 pub total_costs: TotalCosts,
1134}
1135
1136#[derive(Debug)]
1142pub struct PeriodReport {
1143 pub start_date_time: Timestamp,
1145
1146 pub end_date_time: Timestamp,
1148
1149 pub dimensions: Dimensions,
1151}
1152
1153impl PeriodReport {
1154 pub fn cost(&self) -> Option<Price> {
1156 [
1157 self.dimensions
1158 .duration_charging
1159 .as_ref()
1160 .and_then(Dimension::cost),
1161 self.dimensions
1162 .duration_idle
1163 .as_ref()
1164 .and_then(Dimension::cost),
1165 self.dimensions.flat.cost(),
1166 self.dimensions.energy.as_ref().and_then(Dimension::cost),
1167 ]
1168 .into_iter()
1169 .fold(None, |accum, next| {
1170 if accum.is_none() && next.is_none() {
1171 None
1172 } else {
1173 Some(
1174 accum
1175 .unwrap_or_default()
1176 .saturating_add(next.unwrap_or_default()),
1177 )
1178 }
1179 })
1180 }
1181}
1182
1183#[derive(Debug)]
1188struct PeriodReportScratch {
1189 start_date_time: Timestamp,
1190 end_date_time: Timestamp,
1191 dimensions: Dimensions,
1192 step_size_duration_charging: Option<Component>,
1193 step_size_duration_idle: Option<Component>,
1194 step_size_energy: Option<Component>,
1195}
1196
1197impl From<PeriodReportScratch> for PeriodReport {
1198 fn from(scratch: PeriodReportScratch) -> Self {
1199 Self {
1200 start_date_time: scratch.start_date_time,
1201 end_date_time: scratch.end_date_time,
1202 dimensions: scratch.dimensions,
1203 }
1204 }
1205}
1206
1207#[derive(Debug)]
1209struct PeriodTotals {
1210 periods: Vec<PeriodReportScratch>,
1212
1213 totals: Totals,
1215}
1216
1217#[derive(Debug, Default)]
1219pub(crate) struct Totals {
1220 pub energy: Option<Kwh>,
1222
1223 pub duration_charging: Option<SignedDuration>,
1227
1228 pub duration_idle: Option<SignedDuration>,
1232}
1233
1234impl PeriodTotals {
1235 fn calculate_billed(self) -> Result<(Billable, Vec<PeriodReport>, Totals), Warning> {
1237 let Self {
1238 mut periods,
1239 totals,
1240 } = self;
1241
1242 let billable = apply_step_sizes(&mut periods, &totals)?;
1243
1244 let periods = periods.into_iter().map(PeriodReport::from).collect();
1245
1246 Ok((billable, periods, totals))
1247 }
1248}
1249
1250#[derive(Debug)]
1252pub(crate) struct Billable {
1253 duration_charging: Option<SignedDuration>,
1255
1256 duration_idle: Option<SignedDuration>,
1258
1259 energy: Option<Kwh>,
1261}
1262
1263fn period_totals(periods: &[PeriodNormalized], tariff: &Tariff) -> PeriodTotals {
1266 let mut has_flat_fee = false;
1267 let mut totals = Totals::default();
1268
1269 debug!(
1270 tariff_id = tariff.id(),
1271 period_count = periods.len(),
1272 "Accumulating dimension totals for each period"
1273 );
1274
1275 let periods = periods
1276 .iter()
1277 .enumerate()
1278 .map(|(index, period)| {
1279 let mut component_set = tariff.active_components(period);
1280 trace!(
1281 index,
1282 "Creating charge period with Dimension\n{period:#?}\n{component_set:#?}"
1283 );
1284
1285 if component_set.flat.is_some() {
1286 if has_flat_fee {
1287 component_set.flat = None;
1288 } else {
1289 has_flat_fee = true;
1290 }
1291 }
1292
1293 let step_size_duration_charging = if period.consumed.duration_charging.is_some() {
1295 component_set.duration_charging.clone()
1296 } else {
1297 None
1298 };
1299 let step_size_duration_idle = if period.consumed.duration_idle.is_some() {
1300 component_set.duration_idle.clone()
1301 } else {
1302 None
1303 };
1304 let step_size_energy = if period.consumed.energy.is_some() {
1305 component_set.energy.clone()
1306 } else {
1307 None
1308 };
1309
1310 let dimensions = Dimensions::new(component_set, &period.consumed);
1311
1312 trace!(period_index = index, "Dimensions created\n{dimensions:#?}");
1313
1314 if let Some(dim) = &dimensions.duration_charging {
1315 let acc = totals.duration_charging.get_or_insert_default();
1316 *acc = acc.saturating_add(dim.volume);
1317 }
1318
1319 if let Some(dim) = &dimensions.energy {
1320 let acc = totals.energy.get_or_insert_default();
1321 *acc = acc.saturating_add(dim.volume);
1322 }
1323
1324 if let Some(dim) = &dimensions.duration_idle {
1325 let acc = totals.duration_idle.get_or_insert_default();
1326 *acc = acc.saturating_add(dim.volume);
1327 }
1328
1329 trace!(period_index = index, ?totals, "Update totals");
1330
1331 PeriodReportScratch {
1332 start_date_time: period.start_snapshot.date_time,
1333 end_date_time: period.end_snapshot.date_time,
1334 dimensions,
1335 step_size_duration_charging,
1336 step_size_duration_idle,
1337 step_size_energy,
1338 }
1339 })
1340 .collect::<Vec<_>>();
1341
1342 PeriodTotals { periods, totals }
1343}
1344
1345#[derive(Debug, Default)]
1347pub(crate) struct TotalCosts {
1348 pub energy: Option<Price>,
1350
1351 pub fixed: Option<Price>,
1353
1354 pub duration_charging: Option<Price>,
1356
1357 pub duration_idle: Option<Price>,
1359}
1360
1361impl TotalCosts {
1362 pub(crate) fn total(&self) -> Option<Price> {
1366 let Self {
1367 energy,
1368 fixed,
1369 duration_charging,
1370 duration_idle,
1371 } = self;
1372 debug!(
1373 energy = %DisplayOption(*energy),
1374 fixed = %DisplayOption(*fixed),
1375 duration_charging = %DisplayOption(*duration_charging),
1376 duration_idle = %DisplayOption(*duration_idle),
1377 "Calculating total costs."
1378 );
1379 [energy, fixed, duration_charging, duration_idle]
1380 .into_iter()
1381 .fold(None, |accum: Option<Price>, next| match (accum, next) {
1382 (None, None) => None,
1383 _ => Some(
1384 accum
1385 .unwrap_or_default()
1386 .saturating_add(next.unwrap_or_default()),
1387 ),
1388 })
1389 }
1390}
1391
1392fn total_costs(periods: &[PeriodReport], tariff: &Tariff) -> TotalCosts {
1394 let mut total_costs = TotalCosts::default();
1395
1396 debug!(
1397 tariff_id = tariff.id(),
1398 period_count = periods.len(),
1399 "Accumulating dimension costs for each period"
1400 );
1401 for (index, period) in periods.iter().enumerate() {
1402 let dimensions = &period.dimensions;
1403
1404 trace!(period_index = index, "Processing period");
1405
1406 let energy_cost = dimensions.energy.as_ref().and_then(Dimension::cost);
1407 let fixed_cost = dimensions.flat.cost();
1408 let duration_charging_cost = dimensions
1409 .duration_charging
1410 .as_ref()
1411 .and_then(Dimension::cost);
1412 let duration_idle_cost = dimensions.duration_idle.as_ref().and_then(Dimension::cost);
1413
1414 trace!(?total_costs.energy, ?energy_cost, "Energy cost");
1415 trace!(?total_costs.duration_charging, ?duration_charging_cost, "Charging cost");
1416 trace!(?total_costs.duration_idle, ?duration_idle_cost, "Idle cost");
1417 trace!(?total_costs.fixed, ?fixed_cost, "Fixed cost");
1418
1419 total_costs.energy = match (total_costs.energy, energy_cost) {
1420 (None, None) => None,
1421 (total, period) => Some(
1422 total
1423 .unwrap_or_default()
1424 .saturating_add(period.unwrap_or_default()),
1425 ),
1426 };
1427
1428 total_costs.duration_charging =
1429 match (total_costs.duration_charging, duration_charging_cost) {
1430 (None, None) => None,
1431 (total, period) => Some(
1432 total
1433 .unwrap_or_default()
1434 .saturating_add(period.unwrap_or_default()),
1435 ),
1436 };
1437
1438 total_costs.duration_idle = match (total_costs.duration_idle, duration_idle_cost) {
1439 (None, None) => None,
1440 (total, period) => Some(
1441 total
1442 .unwrap_or_default()
1443 .saturating_add(period.unwrap_or_default()),
1444 ),
1445 };
1446
1447 total_costs.fixed = match (total_costs.fixed, fixed_cost) {
1448 (None, None) => None,
1449 (total, period) => Some(
1450 total
1451 .unwrap_or_default()
1452 .saturating_add(period.unwrap_or_default()),
1453 ),
1454 };
1455
1456 trace!(period_index = index, ?total_costs, "Update totals");
1457 }
1458
1459 total_costs
1460}
1461
1462fn generate_report(
1463 cdr_totals: &v221::cdr::Totals,
1464 timezone: &TimeZone,
1465 price_periods_report: PeriodsReport,
1466 tariff_used: TariffOrigin,
1467) -> Report {
1468 let PeriodsReport {
1469 billable,
1470 periods,
1471 totals,
1472 total_costs,
1473 } = price_periods_report;
1474 trace!("Update billed totals {billable:#?}");
1475
1476 let total_cost = total_costs.total();
1477
1478 debug!(total_cost = %DisplayOption(total_cost.as_ref()));
1479
1480 let total_time = {
1481 debug!(
1482 period_start = %DisplayOption(periods.first().map(|p| p.start_date_time)),
1483 period_end = %DisplayOption(periods.last().map(|p| p.end_date_time)),
1484 "Calculating `total_time`"
1485 );
1486
1487 periods
1488 .first()
1489 .zip(periods.last())
1490 .map(|(first, last)| last.end_date_time.duration_since(first.start_date_time))
1491 .unwrap_or(SignedDuration::ZERO)
1492 };
1493 debug!(total_time = %Hms(total_time));
1494
1495 let report = Report {
1496 periods,
1497 tariff_used,
1498 timezone: timezone.clone(),
1499 billed_idle_time: billable.duration_idle,
1500 billed_energy: billable.energy.round_to_ocpi_scale(),
1501 billed_charging_time: billable.duration_charging,
1502 total_charging_time: totals.duration_charging,
1503 total_cost: Total {
1504 cdr: cdr_totals.cost.round_to_ocpi_scale(),
1505 calculated: total_cost.round_to_ocpi_scale(),
1506 },
1507 total_charging_time_cost: Total {
1508 cdr: cdr_totals.duration_charging_cost.round_to_ocpi_scale(),
1509 calculated: total_costs.duration_charging.round_to_ocpi_scale(),
1510 },
1511 total_time: Total {
1512 cdr: cdr_totals.duration_total,
1513 calculated: total_time,
1514 },
1515 total_idle_cost: Total {
1516 cdr: cdr_totals.duration_idle_cost.round_to_ocpi_scale(),
1517 calculated: total_costs.duration_idle.round_to_ocpi_scale(),
1518 },
1519 total_idle_time: Total {
1520 cdr: cdr_totals.duration_idle,
1521 calculated: totals.duration_idle,
1522 },
1523 total_energy_cost: Total {
1524 cdr: cdr_totals.energy_cost.round_to_ocpi_scale(),
1525 calculated: total_costs.energy.round_to_ocpi_scale(),
1526 },
1527 total_energy: Total {
1528 cdr: cdr_totals.energy.round_to_ocpi_scale(),
1529 calculated: totals.energy.round_to_ocpi_scale(),
1530 },
1531 total_fixed_cost: Total {
1532 cdr: cdr_totals.fixed_cost.round_to_ocpi_scale(),
1533 calculated: total_costs.fixed.round_to_ocpi_scale(),
1534 },
1535 };
1536
1537 trace!("{report:#?}");
1538
1539 report
1540}
1541
1542fn apply_step_sizes(
1559 periods: &mut [PeriodReportScratch],
1560 totals: &Totals,
1561) -> Result<Billable, Warning> {
1562 let has_idle_step_size = periods.iter().any(|p| p.step_size_duration_idle.is_some());
1563
1564 let duration_charging = if let Some(total) = totals.duration_charging {
1565 let mut result = Some(total);
1566 for period in periods.iter_mut().rev() {
1567 let Some(step) = period
1568 .step_size_duration_charging
1569 .as_ref()
1570 .map(|c| c.step_size)
1571 else {
1572 continue;
1573 };
1574 if has_idle_step_size {
1575 result = Some(total);
1576 } else if let Some(dim) = period.dimensions.duration_charging.as_mut() {
1577 let dt = duration_step_size(total, &mut dim.billed_volume, step)?;
1578 result = Some(dt);
1579 }
1580 break;
1581 }
1582 result
1583 } else {
1584 None
1585 };
1586
1587 let duration_idle = if let Some(total) = totals.duration_idle {
1588 let mut result = Some(total);
1589 for period in periods.iter_mut().rev() {
1590 let Some(step) = period.step_size_duration_idle.as_ref().map(|c| c.step_size) else {
1591 continue;
1592 };
1593 if let Some(dim) = period.dimensions.duration_idle.as_mut() {
1594 let dt = duration_step_size(total, &mut dim.billed_volume, step)?;
1595 result = Some(dt);
1596 }
1597 break;
1598 }
1599 result
1600 } else {
1601 None
1602 };
1603
1604 let energy = if let Some(total) = totals.energy {
1605 let mut result = Some(total);
1606 for period in periods.iter_mut().rev() {
1607 let Some(step) = period.step_size_energy.as_ref().map(|c| c.step_size) else {
1608 continue;
1609 };
1610 if step == 0 {
1611 result = Some(total);
1612 } else {
1613 let step_dec = Decimal::from(step);
1614 if let Some(dim) = period.dimensions.energy.as_mut() {
1615 let Some(watt_hours) = total.watt_hours().checked_div(step_dec) else {
1616 return Err(duration::Warning::Overflow.into());
1617 };
1618 let total_billed_volume =
1619 Kwh::from_watt_hours(watt_hours.ceil().saturating_mul(step_dec));
1620 let period_delta_volume = total_billed_volume.saturating_sub(total);
1621 dim.billed_volume = dim.billed_volume.saturating_add(period_delta_volume);
1622 result = Some(total_billed_volume);
1623 }
1624 }
1625 break;
1626 }
1627 result
1628 } else {
1629 None
1630 };
1631
1632 Ok(Billable {
1633 duration_charging,
1634 duration_idle,
1635 energy,
1636 })
1637}
1638
1639fn delta_as_seconds_dec(delta: SignedDuration) -> Decimal {
1641 Decimal::try_from_i128_with_scale(delta.as_nanos(), 9).unwrap_or(Decimal::MAX)
1649}
1650
1651fn delta_from_seconds_dec(seconds: Decimal) -> Result<SignedDuration, Warning> {
1653 let millis = seconds.saturating_mul(Decimal::from(duration::MILLIS_IN_SEC));
1654 let Ok(millis) = i64::try_from(millis) else {
1655 return Err(duration::Warning::Overflow.into());
1656 };
1657 Ok(SignedDuration::from_millis(millis))
1658}
1659
1660fn duration_step_size(
1662 total_volume: SignedDuration,
1663 period_billed_volume: &mut SignedDuration,
1664 step_size: u64,
1665) -> Result<SignedDuration, Warning> {
1666 if step_size == 0 {
1667 return Ok(total_volume);
1668 }
1669
1670 let total_seconds = delta_as_seconds_dec(total_volume);
1671 let step_size = Decimal::from(step_size);
1672
1673 let Some(x) = total_seconds.checked_div(step_size) else {
1674 return Err(duration::Warning::Overflow.into());
1675 };
1676 let total_billed_volume = delta_from_seconds_dec(x.ceil().saturating_mul(step_size))?;
1677
1678 let period_delta_volume = total_billed_volume.saturating_sub(total_volume);
1679 *period_billed_volume = period_billed_volume.saturating_add(period_delta_volume);
1680
1681 Ok(total_billed_volume)
1682}