1#[cfg(test)]
4mod test;
5
6#[cfg(test)]
7mod test_clamp_date_time_span;
8
9#[cfg(test)]
10mod test_gen_time_events;
11
12#[cfg(test)]
13mod test_generate;
14
15#[cfg(test)]
16mod test_generate_from_single_elem_tariff;
17
18#[cfg(test)]
19mod test_local_to_utc;
20
21#[cfg(test)]
22mod test_periods;
23
24#[cfg(test)]
25mod test_power_to_time;
26
27#[cfg(test)]
28mod test_popular_tariffs;
29
30mod v2x;
31
32use std::{
33 cmp::{max, min},
34 fmt,
35 ops::Range,
36};
37
38use chrono::{DateTime, Datelike as _, NaiveDateTime, NaiveTime, TimeDelta, Utc};
39use rust_decimal::Decimal;
40use rust_decimal_macros::dec;
41use tracing::{debug, instrument, warn};
42
43use crate::{
44 country, currency,
45 duration::{AsHms as _, ToHoursDecimal},
46 energy::{Ampere, Kw, Kwh},
47 from_warning_all,
48 json::FromJson as _,
49 number::{FromDecimal as _, RoundDecimal as _},
50 price, tariff,
51 warning::{self, GatherWarnings as _, IntoCaveat as _, WithElement as _},
52 Price, SaturatingAdd as _, ToDuration as _, Version, Versioned as _,
53};
54
55const MIN_CS_DURATION_SECS: i64 = 120;
57
58type DateTimeSpan = Range<DateTime<Utc>>;
59pub type Verdict<T> = crate::Verdict<T, Warning>;
60pub type Caveat<T> = warning::Caveat<T, Warning>;
61
62macro_rules! some_dec_or_bail {
64 ($elem:expr, $opt:expr, $warnings:expr, $msg:literal) => {
65 match $opt {
66 Some(v) => v,
67 None => {
68 return $warnings.bail(Warning::Decimal($msg), $elem.as_element());
69 }
70 }
71 };
72}
73
74macro_rules! some_time_delta_or_bail {
76 ($elem:expr, $opt:expr, $warnings:expr, $msg:literal) => {
77 match $opt {
78 Some(v) => v,
79 None => {
80 return $warnings.bail(Warning::TimeDelta($msg), $elem.as_element());
81 }
82 }
83 };
84}
85
86#[derive(Debug)]
88pub struct Report {
89 pub tariff_id: String,
91
92 pub tariff_currency_code: currency::Code,
94
95 pub partial_cdr: PartialCdr,
102}
103
104#[derive(Debug)]
112pub struct PartialCdr {
113 pub currency_code: currency::Code,
115
116 pub party_id: Option<CpoId>,
124
125 pub start_date_time: DateTime<Utc>,
127
128 pub end_date_time: DateTime<Utc>,
130
131 pub total_energy: Option<Kwh>,
133
134 pub total_charging_duration: Option<TimeDelta>,
138
139 pub total_idle_duration: Option<TimeDelta>,
143
144 pub total_cost: Option<Price>,
146
147 pub total_energy_cost: Option<Price>,
149
150 pub total_fixed_cost: Option<Price>,
152
153 pub total_idle_duration_cost: Option<Price>,
155
156 pub total_charging_duration_cost: Option<Price>,
158
159 pub charging_periods: Vec<ChargingPeriod>,
162}
163
164#[derive(Clone, Debug)]
169pub struct CpoId {
170 pub country_code: country::Code,
172
173 pub id: String,
175}
176
177impl<'buf> From<tariff::CpoId<'buf>> for CpoId {
178 fn from(value: tariff::CpoId<'buf>) -> Self {
179 let tariff::CpoId { country_code, id } = value;
180 CpoId {
181 country_code,
182 id: id.to_string(),
183 }
184 }
185}
186
187impl fmt::Display for CpoId {
189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190 write!(f, "{}{}", self.country_code.into_alpha_2_str(), self.id)
191 }
192}
193
194#[derive(Debug)]
198pub struct ChargingPeriod {
199 pub start_date_time: DateTime<Utc>,
202
203 pub dimensions: Vec<Dimension>,
205
206 pub tariff_id: Option<String>,
210}
211
212#[derive(Debug)]
216pub struct Dimension {
217 pub dimension_type: DimensionType,
218
219 pub volume: Decimal,
221}
222
223#[derive(Debug, Clone, PartialEq, Eq)]
227pub enum DimensionType {
228 Energy,
230
231 MaxCurrent,
233
234 MinCurrent,
236
237 MaxPower,
239
240 MinPower,
242
243 ParkingTime,
245
246 ReservationTime,
248
249 Time,
251}
252
253#[derive(Clone)]
255pub struct Config {
256 pub timezone: chrono_tz::Tz,
258
259 pub end_date_time: DateTime<Utc>,
261
262 pub max_current_supply_amp: Decimal,
264
265 pub requested_kwh: Decimal,
270
271 pub max_power_supply_kw: Decimal,
280
281 pub start_date_time: DateTime<Utc>,
283}
284
285pub fn cdr_from_tariff(tariff_elem: &tariff::Versioned<'_>, config: &Config) -> Verdict<Report> {
287 let mut warnings = warning::Set::new();
288 let (metrics, timezone) = metrics(tariff_elem, config)?.gather_warnings_into(&mut warnings);
296
297 let tariff = match tariff_elem.version() {
298 Version::V211 => {
299 let tariff = tariff::v211::Tariff::from_json(tariff_elem.as_element())?
300 .gather_warnings_into(&mut warnings);
301
302 tariff::v221::Tariff::from(tariff)
303 }
304 Version::V221 => tariff::v221::Tariff::from_json(tariff_elem.as_element())?
305 .gather_warnings_into(&mut warnings),
306 };
307
308 if !is_tariff_active(&metrics.start_date_time, &tariff) {
309 warnings.insert(tariff::Warning::NotActive.into(), tariff_elem.as_element());
310 }
311
312 let timeline = timeline(timezone, &metrics, &tariff);
313 let charging_periods = charge_periods(&metrics, timeline);
314
315 let report = price::periods(metrics.end_date_time, timezone, &tariff, charging_periods)
316 .with_element(tariff_elem.as_element())?
317 .gather_warnings_into(&mut warnings);
318
319 let price::PeriodsReport {
320 billable: _,
321 periods,
322 totals,
323 total_costs,
324 } = report;
325
326 let charging_periods = periods
327 .into_iter()
328 .map(|period| {
329 let price::PeriodReport {
330 start_date_time,
331 end_date_time: _,
332 dimensions,
333 } = period;
334 let duration_charging =
335 dimensions
336 .duration_charging
337 .volume
338 .as_ref()
339 .map(|dt| Dimension {
340 dimension_type: DimensionType::Time,
341 volume: ToHoursDecimal::to_hours_dec_in_ocpi_precision(dt),
342 });
343 let duration_idle = dimensions
344 .duration_idle
345 .volume
346 .as_ref()
347 .map(|dt| Dimension {
348 dimension_type: DimensionType::ParkingTime,
349 volume: ToHoursDecimal::to_hours_dec_in_ocpi_precision(dt),
350 });
351 let energy = dimensions.energy.volume.as_ref().map(|kwh| Dimension {
352 dimension_type: DimensionType::Energy,
353 volume: (*kwh).into(),
354 });
355 let dimensions = vec![energy, duration_idle, duration_charging]
356 .into_iter()
357 .flatten()
358 .collect();
359
360 ChargingPeriod {
361 start_date_time,
362 dimensions,
363 tariff_id: Some(tariff.id.to_string()),
364 }
365 })
366 .collect();
367
368 let mut total_cost = total_costs.total();
369
370 if let Some(total_cost) = total_cost.as_mut() {
371 if let Some(min_price) = tariff.min_price {
372 if *total_cost < min_price {
373 *total_cost = min_price;
374 warnings.insert(
375 tariff::Warning::TotalCostClampedToMin.into(),
376 tariff_elem.as_element(),
377 );
378 }
379 }
380
381 if let Some(max_price) = tariff.max_price {
382 if *total_cost > max_price {
383 *total_cost = max_price;
384 warnings.insert(
385 tariff::Warning::TotalCostClampedToMin.into(),
386 tariff_elem.as_element(),
387 );
388 }
389 }
390 }
391
392 let report = Report {
393 tariff_id: tariff.id.to_string(),
394 tariff_currency_code: tariff.currency,
395 partial_cdr: PartialCdr {
396 party_id: tariff.party_id.map(CpoId::from),
397 start_date_time: metrics.start_date_time,
398 end_date_time: metrics.end_date_time,
399 currency_code: tariff.currency,
400 total_energy: totals.energy.round_to_ocpi_scale(),
401 total_charging_duration: totals.duration_charging,
402 total_idle_duration: totals.duration_idle,
403 total_cost: total_cost.round_to_ocpi_scale(),
404 total_energy_cost: total_costs.energy.round_to_ocpi_scale(),
405 total_fixed_cost: total_costs.fixed.round_to_ocpi_scale(),
406 total_idle_duration_cost: total_costs.duration_idle.round_to_ocpi_scale(),
407 total_charging_duration_cost: total_costs.duration_charging.round_to_ocpi_scale(),
408 charging_periods,
409 },
410 };
411
412 Ok(report.into_caveat(warnings))
413}
414
415struct EventCollector {
417 session_duration: TimeDelta,
419
420 events: Vec<Event>,
422}
423
424impl EventCollector {
425 fn with_session_duration(session_duration: TimeDelta) -> Self {
427 Self {
428 session_duration,
429 events: vec![],
430 }
431 }
432
433 fn push(&mut self, duration_from_start: TimeDelta, event_kind: EventKind) {
435 if duration_from_start <= self.session_duration {
436 self.events.push(Event {
437 duration_from_start,
438 kind: event_kind,
439 });
440 }
441 }
442
443 fn push_with(&mut self, event_kind: EventKind) -> impl FnOnce(TimeDelta) + use<'_> {
445 move |dt| {
446 self.push(dt, event_kind);
447 }
448 }
449
450 fn into_inner(self) -> Vec<Event> {
452 self.events
453 }
454}
455
456fn timeline(
458 timezone: chrono_tz::Tz,
459 metrics: &Metrics,
460 tariff: &tariff::v221::Tariff<'_>,
461) -> Timeline {
462 let Metrics {
463 start_date_time: cdr_start,
464 end_date_time: cdr_end,
465 duration_charging,
466 duration_parking,
467 max_power_supply,
468 max_current_supply,
469
470 energy_supplied: _,
471 } = metrics;
472
473 let mut events = {
474 let session_duration = duration_parking.map(|d| duration_charging.saturating_add(d));
475 let mut events =
476 EventCollector::with_session_duration(session_duration.unwrap_or(*duration_charging));
477
478 events.push(TimeDelta::seconds(0), EventKind::SessionStart);
479 events.push(*duration_charging, EventKind::ChargingEnd);
480 session_duration.map(events.push_with(EventKind::ParkingEnd {
481 start: *duration_charging,
482 }));
483
484 events
485 };
486
487 let mut emit_current = false;
490
491 let mut emit_power = false;
494
495 for elem in &tariff.elements {
496 if let Some((time_restrictions, energy_restrictions)) = elem
497 .restrictions
498 .as_ref()
499 .map(tariff::v221::Restrictions::restrictions_by_category)
500 {
501 generate_time_events(
502 &mut events,
503 timezone,
504 *cdr_start..*cdr_end,
505 time_restrictions,
506 );
507
508 let v2x::EnergyRestrictions {
509 min_kwh,
510 max_kwh,
511 min_current,
512 max_current,
513 min_power,
514 max_power,
515 } = energy_restrictions;
516
517 if !emit_current {
518 emit_current = (min_current..=max_current).contains(&Some(*max_current_supply));
523 }
524
525 if !emit_power {
526 emit_power = (min_power..=max_power).contains(&Some(*max_power_supply));
531 }
532
533 generate_energy_events(
534 &mut events,
535 metrics.duration_charging,
536 metrics.energy_supplied,
537 min_kwh,
538 max_kwh,
539 );
540 }
541 }
542
543 let events = events.into_inner();
544
545 Timeline {
546 events,
547 emit_current,
548 emit_power,
549 }
550}
551
552fn generate_time_events(
554 events: &mut EventCollector,
555 timezone: chrono_tz::Tz,
556 cdr_span: DateTimeSpan,
557 restrictions: v2x::TimeRestrictions,
558) {
559 const MIDNIGHT: NaiveTime = NaiveTime::from_hms_opt(0, 0, 0)
560 .expect("The hour, minute and second values are correct and hardcoded");
561 const ONE_DAY: TimeDelta = TimeDelta::days(1);
562
563 let v2x::TimeRestrictions {
564 start_time,
565 end_time,
566 start_date,
567 end_date,
568 min_duration,
569 max_duration,
570 weekdays,
571 } = restrictions;
572
573 let cdr_duration = cdr_span.end.signed_duration_since(cdr_span.start);
574
575 min_duration
577 .filter(|dt| &cdr_duration < dt)
578 .map(events.push_with(EventKind::MinDuration));
579
580 max_duration
582 .filter(|dt| &cdr_duration < dt)
583 .map(events.push_with(EventKind::MaxDuration));
584
585 let (start_date_time, end_date_time) =
595 if let (Some(start_time), Some(end_time)) = (start_time, end_time) {
596 if end_time < start_time {
597 (
598 start_date.map(|d| d.and_time(start_time)),
599 end_date.map(|d| {
600 let (end_time, _) = end_time.overflowing_add_signed(ONE_DAY);
601 d.and_time(end_time)
602 }),
603 )
604 } else {
605 (
606 start_date.map(|d| d.and_time(start_time)),
607 end_date.map(|d| d.and_time(end_time)),
608 )
609 }
610 } else {
611 (
612 start_date.map(|d| d.and_time(start_time.unwrap_or(MIDNIGHT))),
613 end_date.map(|d| d.and_time(end_time.unwrap_or(MIDNIGHT))),
614 )
615 };
616
617 let event_span = clamp_date_time_span(
620 start_date_time.and_then(|d| local_to_utc(timezone, d)),
621 end_date_time.and_then(|d| local_to_utc(timezone, d)),
622 cdr_span,
623 );
624
625 if let Some(start_time) = start_time {
626 gen_naive_time_events(
627 events,
628 &event_span,
629 start_time,
630 &weekdays,
631 EventKind::StartTime,
632 );
633 }
634
635 if let Some(end_time) = end_time {
636 gen_naive_time_events(events, &event_span, end_time, &weekdays, EventKind::EndTime);
637 }
638}
639
640fn local_to_utc(timezone: chrono_tz::Tz, date_time: NaiveDateTime) -> Option<DateTime<Utc>> {
646 use chrono::offset::LocalResult;
647
648 let result = date_time.and_local_timezone(timezone);
649
650 let local_date_time = match result {
651 LocalResult::Single(d) => d,
652 LocalResult::Ambiguous(earliest, _latest) => earliest,
653 LocalResult::None => return None,
654 };
655
656 Some(local_date_time.to_utc())
657}
658
659fn gen_naive_time_events(
661 events: &mut EventCollector,
662 event_span: &Range<DateTime<Utc>>,
663 time: NaiveTime,
664 weekdays: &v2x::WeekdaySet,
665 kind: EventKind,
666) {
667 let time_delta = time.signed_duration_since(event_span.start.time());
668 let cdr_duration = event_span.end.signed_duration_since(event_span.start);
669
670 let time_delta = if time_delta.num_seconds().is_negative() {
673 let (time_delta, _) = time.overflowing_add_signed(TimeDelta::days(1));
674 time_delta.signed_duration_since(event_span.start.time())
675 } else {
676 time_delta
677 };
678
679 if time_delta.num_seconds().is_negative() {
681 return;
682 }
683
684 let Some(remainder) = cdr_duration.checked_sub(&time_delta) else {
686 warn!("TimeDelta overflow");
687 return;
688 };
689
690 if remainder.num_seconds().is_positive() {
691 let duration_from_start = time_delta;
692 let Some(date) = event_span.start.checked_add_signed(duration_from_start) else {
693 warn!("Date out of range");
694 return;
695 };
696
697 if weekdays.contains(date.weekday()) {
698 events.push(time_delta, kind);
700 }
701
702 for day in 1..=remainder.num_days() {
703 let Some(duration_from_start) = time_delta.checked_add(&TimeDelta::days(day)) else {
704 warn!("Date out of range");
705 break;
706 };
707 let Some(date) = event_span.start.checked_add_signed(duration_from_start) else {
708 warn!("Date out of range");
709 break;
710 };
711
712 if weekdays.contains(date.weekday()) {
713 events.push(duration_from_start, kind);
714 }
715 }
716 }
717}
718
719fn generate_energy_events(
721 events: &mut EventCollector,
722 duration_charging: TimeDelta,
723 energy_supplied: Kwh,
724 min_kwh: Option<Kwh>,
725 max_kwh: Option<Kwh>,
726) {
727 min_kwh
728 .and_then(|kwh| power_to_time(kwh, energy_supplied, duration_charging))
729 .map(events.push_with(EventKind::MinKwh));
730
731 max_kwh
732 .and_then(|kwh| power_to_time(kwh, energy_supplied, duration_charging))
733 .map(events.push_with(EventKind::MaxKwh));
734}
735
736#[instrument]
738fn power_to_time(power: Kwh, power_total: Kwh, duration_total: TimeDelta) -> Option<TimeDelta> {
739 if power == power_total {
742 return Some(duration_total);
743 }
744
745 let power = Decimal::from(power);
748 let power_total = Decimal::from(power_total);
750
751 let Some(factor) = power.checked_div(power_total) else {
753 return Some(TimeDelta::zero());
754 };
755
756 if factor.is_sign_negative() || factor > dec!(1.0) {
757 return None;
758 }
759
760 let hours_dec = duration_total.to_hours_dec();
761 let duration_from_start = factor.checked_mul(hours_dec)?;
762 Some(duration_from_start.to_duration_ceil_nanos())
763}
764
765fn charge_periods(metrics: &Metrics, timeline: Timeline) -> Vec<price::Period> {
767 enum ChargingPhase {
769 Charging,
770 Parking,
771 }
772
773 let Metrics {
774 start_date_time: cdr_start,
775 max_power_supply,
776 max_current_supply,
777
778 end_date_time: _,
779 duration_charging: _,
780 duration_parking: _,
781 energy_supplied: _,
782 } = metrics;
783
784 let Timeline {
785 mut events,
786 emit_current,
787 emit_power,
788 } = timeline;
789
790 events.sort_unstable_by_key(|e| e.duration_from_start);
791
792 let mut periods = vec![];
793 let emit_current = emit_current.then_some(*max_current_supply);
794 let emit_power = emit_power.then_some(*max_power_supply);
795 let mut charging_phase = ChargingPhase::Charging;
797
798 for items in events.windows(2) {
799 let [event, event_next] = items else {
800 unreachable!("The window size is 2");
801 };
802
803 let Event {
804 duration_from_start,
805 kind,
806 } = event;
807
808 if let EventKind::ChargingEnd = kind {
809 charging_phase = ChargingPhase::Parking;
810 }
811
812 let Some(duration) = event_next
813 .duration_from_start
814 .checked_sub(duration_from_start)
815 else {
816 warn!("TimeDelta overflow");
817 break;
818 };
819
820 let Some(start_date_time) = cdr_start.checked_add_signed(*duration_from_start) else {
821 warn!("TimeDelta overflow");
822 break;
823 };
824
825 let consumed = if let ChargingPhase::Charging = charging_phase {
826 let Some(energy) =
827 Decimal::from(*max_power_supply).checked_mul(duration.to_hours_dec())
828 else {
829 warn!("Decimal overflow");
830 break;
831 };
832 price::Consumed {
833 duration_charging: Some(duration),
834 duration_idle: None,
835 energy: Some(Kwh::from_decimal(energy)),
836 current_max: emit_current,
837 current_min: emit_current,
838 power_max: emit_power,
839 power_min: emit_power,
840 }
841 } else {
842 price::Consumed {
843 duration_charging: None,
844 duration_idle: Some(duration),
845 energy: None,
846 current_max: None,
847 current_min: None,
848 power_max: None,
849 power_min: None,
850 }
851 };
852
853 let period = price::Period {
854 start_date_time,
855 consumed,
856 };
857
858 periods.push(period);
859 }
860
861 periods
862}
863
864fn clamp_date_time_span(
870 min_date: Option<DateTime<Utc>>,
871 max_date: Option<DateTime<Utc>>,
872 span: DateTimeSpan,
873) -> DateTimeSpan {
874 let (min_date, max_date) = (min(min_date, max_date), max(min_date, max_date));
876
877 let start = min_date.filter(|d| &span.start < d).unwrap_or(span.start);
878 let end = max_date.filter(|d| &span.end > d).unwrap_or(span.end);
879
880 DateTimeSpan { start, end }
881}
882
883struct Timeline {
885 events: Vec<Event>,
887
888 emit_current: bool,
890
891 emit_power: bool,
893}
894
895struct Event {
897 duration_from_start: TimeDelta,
899
900 kind: EventKind,
902}
903
904impl fmt::Debug for Event {
905 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
906 f.debug_struct("Event")
907 .field("duration_from_start", &self.duration_from_start.as_hms())
908 .field("kind", &self.kind)
909 .finish()
910 }
911}
912
913#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
915enum EventKind {
916 SessionStart,
922
923 ChargingEnd,
928
929 ParkingEnd {
934 start: TimeDelta,
936 },
937
938 StartTime,
939
940 EndTime,
941
942 MinDuration,
947
948 MaxDuration,
953
954 MinKwh,
956
957 MaxKwh,
959}
960
961impl fmt::Debug for EventKind {
962 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
963 match self {
964 Self::SessionStart => write!(f, "SessionStart"),
965 Self::ChargingEnd => write!(f, "ChargingEnd"),
966 Self::ParkingEnd { start } => f
967 .debug_struct("ParkingEnd")
968 .field("start", &start.as_hms())
969 .finish(),
970 Self::StartTime => write!(f, "StartTime"),
971 Self::EndTime => write!(f, "EndTime"),
972 Self::MinDuration => write!(f, "MinDuration"),
973 Self::MaxDuration => write!(f, "MaxDuration"),
974 Self::MinKwh => write!(f, "MinKwh"),
975 Self::MaxKwh => write!(f, "MaxKwh"),
976 }
977 }
978}
979
980#[derive(Debug)]
982struct Metrics {
983 end_date_time: DateTime<Utc>,
985
986 start_date_time: DateTime<Utc>,
988
989 duration_charging: TimeDelta,
994
995 duration_parking: Option<TimeDelta>,
999
1000 energy_supplied: Kwh,
1002
1003 max_current_supply: Ampere,
1005
1006 max_power_supply: Kw,
1008}
1009
1010#[instrument(skip_all)]
1012fn metrics(elem: &tariff::Versioned<'_>, config: &Config) -> Verdict<(Metrics, chrono_tz::Tz)> {
1013 let warnings = warning::Set::new();
1014
1015 let Config {
1016 start_date_time,
1017 end_date_time,
1018 max_power_supply_kw,
1019 requested_kwh: max_energy_battery_kwh,
1020 max_current_supply_amp,
1021 timezone,
1022 } = config;
1023 let duration_session = end_date_time.signed_duration_since(start_date_time);
1024
1025 debug!("duration_session: {}", duration_session.as_hms());
1026
1027 if duration_session.abs() != duration_session {
1029 return warnings.bail(Warning::StartDateTimeIsAfterEndDateTime, elem.as_element());
1030 }
1031
1032 if duration_session.num_seconds() < MIN_CS_DURATION_SECS {
1033 return warnings.bail(Warning::DurationBelowMinimum, elem.as_element());
1034 }
1035
1036 let duration_full_charge = some_dec_or_bail!(
1038 elem,
1039 max_energy_battery_kwh.checked_div(*max_power_supply_kw),
1040 warnings,
1041 "Unable to calculate changing time"
1042 )
1043 .to_duration_ceil_nanos();
1044 debug!("duration_full_charge: {}", duration_full_charge.as_hms());
1045
1046 let duration_charging = TimeDelta::min(duration_full_charge, duration_session);
1048
1049 let energy_supplied_kwh = some_dec_or_bail!(
1050 elem,
1051 max_energy_battery_kwh.checked_div(duration_charging.to_hours_dec()),
1052 warnings,
1053 "Unable to calculate the power supplied during the charging time"
1054 );
1055
1056 let duration_parking = some_time_delta_or_bail!(
1057 elem,
1058 duration_session.checked_sub(&duration_charging),
1059 warnings,
1060 "Unable to calculate `idle_duration`"
1061 );
1062
1063 debug!(
1064 "duration_charging: {}, duration_parking: {}",
1065 duration_charging.as_hms(),
1066 duration_parking.as_hms()
1067 );
1068
1069 let metrics = Metrics {
1070 end_date_time: *end_date_time,
1071 start_date_time: *start_date_time,
1072 duration_charging,
1073 duration_parking: Some(duration_parking).filter(|dt| dt.num_seconds().is_positive()),
1074 energy_supplied: Kwh::from_decimal(energy_supplied_kwh),
1075 max_current_supply: Ampere::from_decimal(*max_current_supply_amp),
1076 max_power_supply: Kw::from_decimal(*max_power_supply_kw),
1077 };
1078
1079 Ok((metrics, *timezone).into_caveat(warnings))
1080}
1081
1082fn is_tariff_active(cdr_start: &DateTime<Utc>, tariff: &tariff::v221::Tariff<'_>) -> bool {
1083 match (tariff.start_date_time, tariff.end_date_time) {
1084 (None, None) => true,
1085 (None, Some(end)) => (..end).contains(cdr_start),
1086 (Some(start), None) => (start..).contains(cdr_start),
1087 (Some(start), Some(end)) => (start..end).contains(cdr_start),
1088 }
1089}
1090
1091#[derive(Debug)]
1092pub enum Warning {
1093 Decimal(&'static str),
1095
1096 DurationBelowMinimum,
1098
1099 Price(price::Warning),
1100
1101 StartDateTimeIsAfterEndDateTime,
1103
1104 Tariff(tariff::Warning),
1105
1106 TimeDelta(&'static str),
1108}
1109
1110impl crate::Warning for Warning {
1111 fn id(&self) -> warning::Id {
1112 match self {
1113 Self::Decimal(_) => warning::Id::from_static("decimal_error"),
1114 Self::DurationBelowMinimum => warning::Id::from_static("duration_below_minimum"),
1115 Self::Price(kind) => kind.id(),
1116 Self::StartDateTimeIsAfterEndDateTime => {
1117 warning::Id::from_static("start_time_after_end_time")
1118 }
1119 Self::TimeDelta(_) => warning::Id::from_static("timedelta_error"),
1120 Self::Tariff(kind) => kind.id(),
1121 }
1122 }
1123}
1124
1125impl fmt::Display for Warning {
1126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1127 match self {
1128 Self::Decimal(msg) | Self::TimeDelta(msg) => f.write_str(msg),
1129 Self::DurationBelowMinimum => write!(
1130 f,
1131 "The duration of the chargesession is below the minimum: {MIN_CS_DURATION_SECS}"
1132 ),
1133 Self::Price(warnings) => {
1134 write!(f, "Price warnings: {warnings:?}")
1135 }
1136 Self::StartDateTimeIsAfterEndDateTime => {
1137 write!(f, "The `start_date_time` is after the `end_date_time`")
1138 }
1139 Self::Tariff(warnings) => {
1140 write!(f, "Tariff warnings: {warnings:?}")
1141 }
1142 }
1143 }
1144}
1145
1146from_warning_all!(
1147 tariff::Warning => Warning::Tariff,
1148 price::Warning => Warning::Price
1149);