#[cfg(test)]
pub mod test;
#[cfg(test)]
mod test_periods;
#[cfg(test)]
mod test_real_world;
#[cfg(test)]
mod test_validate_cdr;
#[cfg(test)]
mod test_current_and_power_restrictions;
#[cfg(test)]
mod test_reservation_restriction;
#[cfg(test)]
mod test_time_of_day_restrictions;
#[cfg(test)]
mod test_min_max_price;
#[cfg(test)]
mod test_step_size;
#[cfg(test)]
mod test_failed_price;
mod tariff;
pub(crate) mod v211;
pub(crate) mod v221;
use std::fmt;
use jiff::{SignedDuration, Timestamp, tz::TimeZone};
use rust_decimal::Decimal;
use tariff::Tariff;
use tracing::{debug, instrument, trace};
use crate::{
Ampere, Cost, DisplayOption, Kw, Kwh, Money, Price, SaturatingAdd as _, SaturatingSub,
currency,
duration::{self, AsHms as _, Hms},
from_warning_all, json,
money::VatOrigin,
number::RoundDecimal as _,
schema::{self, HasElement as _},
version::Versioned as _,
warning,
};
pub type Verdict<T> = crate::Verdict<T, Warning>;
#[derive(Debug)]
struct PeriodNormalized {
consumed: Consumed,
start_snapshot: TotalsSnapshot,
end_snapshot: TotalsSnapshot,
}
#[derive(Clone)]
#[cfg_attr(test, derive(Default))]
pub(crate) struct Consumed {
pub current_max: Option<Ampere>,
pub current_min: Option<Ampere>,
pub duration_charging: Option<SignedDuration>,
pub duration_idle: Option<SignedDuration>,
pub energy: Option<Kwh>,
pub power_max: Option<Kw>,
pub power_min: Option<Kw>,
}
impl fmt::Debug for Consumed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Consumed")
.field("current_max", &self.current_max)
.field("current_min", &self.current_min)
.field(
"duration_charging",
&self.duration_charging.map(|dt| dt.as_hms()),
)
.field("duration_idle", &self.duration_idle.map(|dt| dt.as_hms()))
.field("energy", &self.energy)
.field("power_max", &self.power_max)
.field("power_min", &self.power_min)
.finish()
}
}
#[derive(Clone)]
struct TotalsSnapshot {
date_time: Timestamp,
energy: Kwh,
local_timezone: TimeZone,
duration_charging: SignedDuration,
duration_total: SignedDuration,
}
impl fmt::Debug for TotalsSnapshot {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TotalsSnapshot")
.field("date_time", &self.date_time)
.field("energy", &self.energy)
.field("local_timezone", &self.local_timezone)
.field("duration_charging", &self.duration_charging.as_hms())
.field("duration_total", &self.duration_total.as_hms())
.finish()
}
}
impl TotalsSnapshot {
fn zero(date_time: Timestamp, local_timezone: TimeZone) -> Self {
Self {
date_time,
energy: Kwh::zero(),
local_timezone,
duration_charging: SignedDuration::ZERO,
duration_total: SignedDuration::ZERO,
}
}
fn next(&self, consumed: &Consumed, date_time: Timestamp) -> Self {
let duration = date_time.duration_since(self.date_time);
let mut next = Self {
date_time,
energy: self.energy,
local_timezone: self.local_timezone.clone(),
duration_charging: self.duration_charging,
duration_total: self.duration_total.saturating_add(duration),
};
if let Some(duration) = consumed.duration_charging {
next.duration_charging = next.duration_charging.saturating_add(duration);
}
if let Some(energy) = consumed.energy {
next.energy = next.energy.saturating_add(energy);
}
next
}
fn local_time(&self) -> jiff::civil::Time {
self.local_timezone.to_datetime(self.date_time).time()
}
fn local_date(&self) -> jiff::civil::Date {
self.local_timezone.to_datetime(self.date_time).date()
}
fn local_weekday(&self) -> jiff::civil::Weekday {
self.local_timezone.to_datetime(self.date_time).weekday()
}
}
pub struct Report {
pub periods: Vec<PeriodReport>,
pub tariff_used: TariffOrigin,
pub timezone: TimeZone,
pub billed_charging_time: Option<SignedDuration>,
pub billed_energy: Option<Kwh>,
pub billed_idle_time: Option<SignedDuration>,
pub total_charging_time: Option<SignedDuration>,
pub total_energy: Total<Kwh, Option<Kwh>>,
pub total_idle_time: Total<Option<SignedDuration>>,
pub total_time: Total<SignedDuration>,
pub total_cost: Total<Price, Option<Price>>,
pub total_energy_cost: Total<Option<Price>>,
pub total_fixed_cost: Total<Option<Price>>,
pub total_idle_cost: Total<Option<Price>>,
pub total_charging_time_cost: Total<Option<Price>>,
}
impl fmt::Debug for Report {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Report")
.field("periods", &self.periods)
.field("tariff_used", &self.tariff_used)
.field("timezone", &self.timezone)
.field(
"billed_charging_time",
&self.billed_charging_time.map(|dt| dt.as_hms()),
)
.field("billed_energy", &self.billed_energy)
.field(
"billed_idle_time",
&self.billed_idle_time.map(|dt| dt.as_hms()),
)
.field(
"total_charging_time",
&self.total_charging_time.map(|dt| dt.as_hms()),
)
.field("total_energy", &self.total_energy)
.field("total_idle_time", &self.total_idle_time)
.field("total_time", &self.total_time)
.field("total_cost", &self.total_cost)
.field("total_energy_cost", &self.total_energy_cost)
.field("total_fixed_cost", &self.total_fixed_cost)
.field("total_idle_cost", &self.total_idle_cost)
.field("total_charging_time_cost", &self.total_charging_time_cost)
.finish()
}
}
#[derive(Debug)]
pub enum Warning {
Duration(duration::Warning),
MinPriceIsGreaterThanMax,
NoValidTariff,
PeriodsStateNoTime,
ReservationElementSkipped,
TotalCostClampedToMax,
TotalCostClampedToMin,
TotalCostInclusiveVatUnknown,
}
impl fmt::Display for Warning {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Duration(warning) => write!(f, "{warning}"),
Self::MinPriceIsGreaterThanMax => write!(
f,
"The given tariff has a `min_price` that is above its `max_price`, so no total \
can satisfy both."
),
Self::NoValidTariff => {
f.write_str("No valid tariff has been found in the list of provided tariffs")
}
Self::PeriodsStateNoTime => f.write_str(
"No charging period has a `TIME` or `PARKING_TIME` dimension, but the tariff prices \
time",
),
Self::ReservationElementSkipped => f.write_str(
"A tariff element has a `reservation` restriction and will not apply to regular \
charging sessions. Reservation pricing is not supported.",
),
Self::TotalCostClampedToMax => write!(
f,
"The given tariff has a `max_price` set and the `total_cost` exceeded it."
),
Self::TotalCostClampedToMin => write!(
f,
"The given tariff has a `min_price` set and the `total_cost` was below it, or no \
cost was calculated at all."
),
Self::TotalCostInclusiveVatUnknown => write!(
f,
"The given tariff has a `min_price` that states no value including VAT, and it \
raised the total cost excluding VAT to a value implying a negative VAT rate \
against the total cost including VAT, so the total cost including VAT is no \
longer known."
),
}
}
}
impl crate::Warning for Warning {
fn id(&self) -> warning::Id {
match self {
Self::Duration(warning) => warning.id(),
Self::MinPriceIsGreaterThanMax => {
warning::Id::from_static("min_price_is_greater_than_max")
}
Self::NoValidTariff => warning::Id::from_static("no_valid_tariff"),
Self::PeriodsStateNoTime => warning::Id::from_static("periods_state_no_time"),
Self::ReservationElementSkipped => {
warning::Id::from_static("reservation_element_skipped")
}
Self::TotalCostClampedToMax => warning::Id::from_static("total_cost_clamped_to_max"),
Self::TotalCostClampedToMin => warning::Id::from_static("total_cost_clamped_to_min"),
Self::TotalCostInclusiveVatUnknown => {
warning::Id::from_static("total_cost_inclusive_vat_unknown")
}
}
}
fn is_rejected(&self) -> bool {
match self {
Self::Duration(_)
| Self::MinPriceIsGreaterThanMax
| Self::NoValidTariff
| Self::PeriodsStateNoTime
| Self::ReservationElementSkipped
| Self::TotalCostClampedToMax
| Self::TotalCostClampedToMin
| Self::TotalCostInclusiveVatUnknown => false,
}
}
}
from_warning_all!(duration::Warning => Warning::Duration);
#[derive(Clone, Debug)]
pub struct TariffOrigin {
pub index: usize,
pub id: String,
pub currency: currency::Code,
}
#[derive(Debug)]
pub(crate) struct Period {
pub start_date_time: Timestamp,
pub consumed: Consumed,
}
#[derive(Debug)]
pub struct Dimensions {
pub energy: Option<Dimension<Kwh>>,
pub flat: Dimension<()>,
pub duration_charging: Option<Dimension<SignedDuration>>,
pub duration_idle: Option<Dimension<SignedDuration>>,
}
impl Dimensions {
fn new(components: ComponentSet, consumed: &Consumed) -> Self {
let ComponentSet {
energy: energy_price,
flat: flat_price,
duration_charging: duration_charging_price,
duration_idle: duration_idle_price,
} = components;
let Consumed {
duration_charging,
duration_idle,
energy,
current_max: _,
current_min: _,
power_max: _,
power_min: _,
} = consumed;
Self {
energy: (*energy).map(|e| Dimension {
price: energy_price,
volume: e,
billed_volume: e,
}),
flat: Dimension {
price: flat_price,
volume: (),
billed_volume: (),
},
duration_charging: (*duration_charging).map(|dc| Dimension {
price: duration_charging_price,
volume: dc,
billed_volume: dc,
}),
duration_idle: (*duration_idle).map(|di| Dimension {
price: duration_idle_price,
volume: di,
billed_volume: di,
}),
}
}
}
#[derive(Debug)]
pub struct Dimension<V> {
pub price: Option<Component>,
pub volume: V,
pub billed_volume: V,
}
impl<V: Cost> Dimension<V> {
pub fn cost(&self) -> Option<Price> {
let Some(price_component) = &self.price else {
return None;
};
let excl_vat = self.billed_volume.cost(price_component.price);
let incl_vat = match price_component.vat {
VatOrigin::Provided(vat) => Some(excl_vat.apply_vat(vat)),
VatOrigin::NotProvided => Some(excl_vat),
VatOrigin::Unknown => None,
};
Some(Price { excl_vat, incl_vat })
}
}
#[derive(Debug)]
pub struct ComponentSet {
pub energy: Option<Component>,
pub flat: Option<Component>,
pub duration_charging: Option<Component>,
pub duration_idle: Option<Component>,
}
impl ComponentSet {
fn has_all_components(&self) -> bool {
let Self {
energy,
flat,
duration_charging,
duration_idle,
} = self;
flat.is_some() && energy.is_some() && duration_idle.is_some() && duration_charging.is_some()
}
}
#[derive(Clone, Debug)]
pub struct Component {
price: Money,
vat: VatOrigin,
step_size: u64,
}
impl Component {
fn new(component: &crate::tariff::v221::PriceComponent) -> Self {
let crate::tariff::v221::PriceComponent {
price,
vat,
step_size,
dimension_type: _,
} = component;
Self {
price: *price,
vat: *vat,
step_size: *step_size,
}
}
pub fn price(&self) -> Money {
self.price
}
}
#[derive(Debug)]
pub struct Total<TCdr, TCalc = TCdr> {
pub cdr: TCdr,
pub calculated: TCalc,
}
#[instrument(skip_all)]
pub(super) fn cdr(
cdr: &crate::cdr::Cdr<'_>,
tariffs: &[crate::tariff::Tariff<'_>],
timezone: &TimeZone,
) -> Verdict<Report> {
let mut warnings = warning::Gatherer::new();
let report = price_v221_cdr_with_tariffs(cdr, tariffs, timezone, &mut warnings);
warnings.into_verdict(report)
}
fn price_v221_cdr_with_tariffs(
cdr: &crate::cdr::Cdr<'_>,
tariffs: &[crate::tariff::Tariff<'_>],
timezone: &TimeZone,
warnings: &mut dyn warning::Gather<Warning>,
) -> Result<Report, warning::Error<Warning>> {
let cdr_elem = cdr.as_checked();
let cdr = cdr.as_v221();
debug!(?timezone, version = ?cdr_elem.version(), "Pricing CDR");
let v221::Cdr {
start_date_time,
end_date_time,
charging_periods,
kind,
totals: cdr_totals,
} = cdr;
debug!(tariffs = ?tariffs.iter().map(|t| t.as_v221().id).collect::<Vec<_>>(), "Pricing with tariffs(by id)");
let tariffs_normalized = tariff::normalize_all(tariffs);
let Some((tariff_index, tariff)) =
tariff::find_first_active(tariffs_normalized, *start_date_time)
else {
return Err(warning::Error::new(
cdr_elem.as_element(),
Warning::NoValidTariff,
));
};
debug!(tariff_index, id = ?tariff.id(), "Found active tariff");
debug!(timezone = timezone.iana_name(), "Found timezone");
let periods_state_time = charging_periods.iter().any(|period| {
period.dimensions.iter().any(|dimension| {
matches!(
dimension.dimension_type,
v221::cdr::DimensionType::Time | v221::cdr::DimensionType::ParkingTime
)
})
});
if !periods_state_time && tariff.has_time_components() {
let charging_periods_elem = match cdr_elem.schema() {
crate::cdr::Version::V211(ir) => match &ir.charging_periods {
schema::Integrity::Ok(list) => list.element(),
schema::Integrity::Missing(_) | schema::Integrity::Err(_) => cdr_elem.as_element(),
},
crate::cdr::Version::V221(ir) => match &ir.charging_periods {
schema::Integrity::Ok(list) => list.element(),
schema::Integrity::Missing(_) | schema::Integrity::Err(_) => cdr_elem.as_element(),
},
};
warnings.insert(charging_periods_elem, Warning::PeriodsStateNoTime);
}
let periods = charging_periods.iter().map(Period::from).collect();
let periods = normalize_periods(periods, *end_date_time, timezone);
let price_cdr_report = price_periods(&periods, &tariff, cdr_elem.as_element(), warnings)?;
let mut report = generate_report(
cdr_totals,
timezone,
price_cdr_report,
TariffOrigin {
index: tariff_index,
id: tariff.id().to_owned(),
currency: tariff.currency(),
},
);
let clamped = clamp_total_cost(
&mut report.total_cost.calculated,
tariff.min_price(),
tariff.max_price(),
);
if clamped.to_min {
warnings.insert(cdr_elem.as_element(), Warning::TotalCostClampedToMin);
}
if clamped.to_max {
warnings.insert(cdr_elem.as_element(), Warning::TotalCostClampedToMax);
}
if clamped.incl_vat_unknown {
warnings.insert(cdr_elem.as_element(), Warning::TotalCostInclusiveVatUnknown);
}
if clamped.min_above_max {
warnings.insert(cdr_elem.as_element(), Warning::MinPriceIsGreaterThanMax);
}
if *kind == v221::cdr::Kind::Credit {
report.total_cost.calculated = report.total_cost.calculated.map(Price::negate);
}
Ok(report)
}
pub(crate) fn clamp_total_cost(
total_cost: &mut Option<Price>,
min_price: Option<Price>,
max_price: Option<Price>,
) -> Clamped {
let min_above_max = match (min_price, max_price) {
(Some(min_price), Some(max_price)) => min_price.exceeds_on_either_value(max_price),
_ => false,
};
let mut clamped = Clamped {
to_min: false,
to_max: false,
incl_vat_unknown: false,
min_above_max,
};
if let Some(min_price) = min_price {
match total_cost.as_mut() {
None => {
*total_cost = Some(min_price);
clamped.to_min = true;
}
Some(total_cost) => {
if total_cost.excl_vat < min_price.excl_vat {
total_cost.excl_vat = min_price.excl_vat;
clamped.to_min = true;
if min_price.incl_vat.is_none() && !total_cost.vat_is_consistent() {
total_cost.incl_vat = None;
clamped.incl_vat_unknown = true;
}
}
let below_incl = match (total_cost.incl_vat, min_price.incl_vat) {
(Some(total_incl), Some(min_incl)) => total_incl < min_incl,
_ => false,
};
if below_incl {
total_cost.incl_vat = min_price.incl_vat;
clamped.to_min = true;
}
}
}
}
if let Some(max_price) = max_price
&& let Some(total_cost) = total_cost.as_mut()
{
if total_cost.excl_vat > max_price.excl_vat {
total_cost.excl_vat = max_price.excl_vat;
clamped.to_max = true;
}
let above_incl = match (total_cost.incl_vat, max_price.incl_vat) {
(Some(total_incl), Some(max_incl)) => total_incl > max_incl,
_ => false,
};
if above_incl {
total_cost.incl_vat = max_price.incl_vat;
clamped.to_max = true;
}
}
clamped
}
pub(crate) struct Clamped {
pub to_min: bool,
pub to_max: bool,
pub incl_vat_unknown: bool,
pub min_above_max: bool,
}
pub(crate) fn periods(
end_date_time: Timestamp,
timezone: &TimeZone,
tariff_elem: &crate::tariff::v221::Tariff<'_>,
mut periods: Vec<Period>,
elem: &json::Element<'_>,
warnings: &mut dyn warning::Gather<Warning>,
) -> Result<PeriodsReport, warning::Error<Warning>> {
periods.sort_by_key(|p| p.start_date_time);
let tariff = Tariff::from_v221(tariff_elem);
let periods = normalize_periods(periods, end_date_time, timezone);
price_periods(&periods, &tariff, elem, warnings)
}
fn normalize_periods(
periods: Vec<Period>,
end_date_time: Timestamp,
local_timezone: &TimeZone,
) -> Vec<PeriodNormalized> {
debug!("Normalizing CDR periods");
let mut previous_end_snapshot = Option::<TotalsSnapshot>::None;
let end_dates = {
let mut end_dates = periods
.iter()
.skip(1)
.map(|p| p.start_date_time)
.collect::<Vec<_>>();
end_dates.push(end_date_time);
end_dates
};
periods
.into_iter()
.zip(end_dates)
.enumerate()
.map(|(index, (period, end_date_time))| {
trace!(index, "processing\n{period:#?}");
let Period {
start_date_time,
mut consumed,
} = period;
let period_length = end_date_time.duration_since(start_date_time);
consumed.duration_charging = consumed
.duration_charging
.map(|duration| snap_to_period_length(duration, period_length));
consumed.duration_idle = consumed
.duration_idle
.map(|duration| snap_to_period_length(duration, period_length));
let period = if let Some(prev_end_snapshot) = previous_end_snapshot.take() {
let start_snapshot = prev_end_snapshot;
let end_snapshot = start_snapshot.next(&consumed, end_date_time);
let period = PeriodNormalized {
consumed,
start_snapshot,
end_snapshot,
};
trace!("Adding new period based on the last added\n{period:#?}");
period
} else {
let start_snapshot = TotalsSnapshot::zero(start_date_time, local_timezone.clone());
let end_snapshot = start_snapshot.next(&consumed, end_date_time);
let period = PeriodNormalized {
consumed,
start_snapshot,
end_snapshot,
};
trace!("Adding new period\n{period:#?}");
period
};
previous_end_snapshot.replace(period.end_snapshot.clone());
period
})
.collect::<Vec<_>>()
}
fn snap_to_period_length(
duration: SignedDuration,
period_length: SignedDuration,
) -> SignedDuration {
const HALF_OF_OCPI_HOURS_RESOLUTION: SignedDuration = SignedDuration::from_millis(180);
if duration.is_zero() {
return duration;
}
let difference = SaturatingSub::saturating_sub(duration, period_length).abs();
if difference <= HALF_OF_OCPI_HOURS_RESOLUTION {
period_length
} else {
duration
}
}
fn price_periods(
periods: &[PeriodNormalized],
tariff: &Tariff,
elem: &json::Element<'_>,
warnings: &mut dyn warning::Gather<Warning>,
) -> Result<PeriodsReport, warning::Error<Warning>> {
debug!(count = periods.len(), "Pricing CDR periods");
if tracing::enabled!(tracing::Level::TRACE) {
trace!("# CDR period list:");
for period in periods {
trace!("{period:#?}");
}
}
let period_totals = period_totals(periods, tariff);
let billed = period_totals
.calculate_billed()
.map_err(|warning| warning::Error::new(elem, warning))?;
if tariff.has_reservation_elements() {
warnings.insert(elem, Warning::ReservationElementSkipped);
}
let (billable, periods, totals) = billed;
let total_costs = total_costs(&periods, tariff);
let report = PeriodsReport {
billable,
periods,
totals,
total_costs,
};
Ok(report)
}
pub(crate) struct PeriodsReport {
pub billable: Billable,
pub periods: Vec<PeriodReport>,
pub totals: Totals,
pub total_costs: TotalCosts,
}
#[derive(Debug)]
pub struct PeriodReport {
pub start_date_time: Timestamp,
pub end_date_time: Timestamp,
pub dimensions: Dimensions,
}
impl PeriodReport {
pub fn cost(&self) -> Option<Price> {
[
self.dimensions
.duration_charging
.as_ref()
.and_then(Dimension::cost),
self.dimensions
.duration_idle
.as_ref()
.and_then(Dimension::cost),
self.dimensions.flat.cost(),
self.dimensions.energy.as_ref().and_then(Dimension::cost),
]
.into_iter()
.fold(None, |accum, next| {
if accum.is_none() && next.is_none() {
None
} else {
Some(
accum
.unwrap_or_default()
.saturating_add(next.unwrap_or_default()),
)
}
})
}
}
#[derive(Debug)]
struct PeriodReportScratch {
start_date_time: Timestamp,
end_date_time: Timestamp,
dimensions: Dimensions,
step_size_duration_charging: Option<Component>,
step_size_duration_idle: Option<Component>,
step_size_energy: Option<Component>,
}
impl From<PeriodReportScratch> for PeriodReport {
fn from(scratch: PeriodReportScratch) -> Self {
Self {
start_date_time: scratch.start_date_time,
end_date_time: scratch.end_date_time,
dimensions: scratch.dimensions,
}
}
}
#[derive(Debug)]
struct PeriodTotals {
periods: Vec<PeriodReportScratch>,
totals: Totals,
}
#[derive(Debug, Default)]
pub(crate) struct Totals {
pub energy: Option<Kwh>,
pub duration_charging: Option<SignedDuration>,
pub duration_idle: Option<SignedDuration>,
}
impl PeriodTotals {
fn calculate_billed(self) -> Result<(Billable, Vec<PeriodReport>, Totals), Warning> {
let Self {
mut periods,
totals,
} = self;
let billable = apply_step_sizes(&mut periods, &totals)?;
let periods = periods.into_iter().map(PeriodReport::from).collect();
Ok((billable, periods, totals))
}
}
#[derive(Debug)]
pub(crate) struct Billable {
duration_charging: Option<SignedDuration>,
duration_idle: Option<SignedDuration>,
energy: Option<Kwh>,
}
fn period_totals(periods: &[PeriodNormalized], tariff: &Tariff) -> PeriodTotals {
let mut has_flat_fee = false;
let mut totals = Totals::default();
debug!(
tariff_id = tariff.id(),
period_count = periods.len(),
"Accumulating dimension totals for each period"
);
let periods = periods
.iter()
.enumerate()
.map(|(index, period)| {
let mut component_set = tariff.active_components(period);
trace!(
index,
"Creating charge period with Dimension\n{period:#?}\n{component_set:#?}"
);
if component_set.flat.is_some() {
if has_flat_fee {
component_set.flat = None;
} else {
has_flat_fee = true;
}
}
let step_size_duration_charging = if period.consumed.duration_charging.is_some() {
component_set.duration_charging.clone()
} else {
None
};
let step_size_duration_idle = if period.consumed.duration_idle.is_some() {
component_set.duration_idle.clone()
} else {
None
};
let step_size_energy = if period.consumed.energy.is_some() {
component_set.energy.clone()
} else {
None
};
let dimensions = Dimensions::new(component_set, &period.consumed);
trace!(period_index = index, "Dimensions created\n{dimensions:#?}");
if let Some(dim) = &dimensions.duration_charging {
let acc = totals.duration_charging.get_or_insert_default();
*acc = acc.saturating_add(dim.volume);
}
if let Some(dim) = &dimensions.energy {
let acc = totals.energy.get_or_insert_default();
*acc = acc.saturating_add(dim.volume);
}
if let Some(dim) = &dimensions.duration_idle {
let acc = totals.duration_idle.get_or_insert_default();
*acc = acc.saturating_add(dim.volume);
}
trace!(period_index = index, ?totals, "Update totals");
PeriodReportScratch {
start_date_time: period.start_snapshot.date_time,
end_date_time: period.end_snapshot.date_time,
dimensions,
step_size_duration_charging,
step_size_duration_idle,
step_size_energy,
}
})
.collect::<Vec<_>>();
PeriodTotals { periods, totals }
}
#[derive(Debug, Default)]
pub(crate) struct TotalCosts {
pub energy: Option<Price>,
pub fixed: Option<Price>,
pub duration_charging: Option<Price>,
pub duration_idle: Option<Price>,
}
impl TotalCosts {
pub(crate) fn total(&self) -> Option<Price> {
let Self {
energy,
fixed,
duration_charging,
duration_idle,
} = self;
debug!(
energy = %DisplayOption(*energy),
fixed = %DisplayOption(*fixed),
duration_charging = %DisplayOption(*duration_charging),
duration_idle = %DisplayOption(*duration_idle),
"Calculating total costs."
);
[energy, fixed, duration_charging, duration_idle]
.into_iter()
.fold(None, |accum: Option<Price>, next| match (accum, next) {
(None, None) => None,
_ => Some(
accum
.unwrap_or_default()
.saturating_add(next.unwrap_or_default()),
),
})
}
}
fn total_costs(periods: &[PeriodReport], tariff: &Tariff) -> TotalCosts {
let mut total_costs = TotalCosts::default();
debug!(
tariff_id = tariff.id(),
period_count = periods.len(),
"Accumulating dimension costs for each period"
);
for (index, period) in periods.iter().enumerate() {
let dimensions = &period.dimensions;
trace!(period_index = index, "Processing period");
let energy_cost = dimensions.energy.as_ref().and_then(Dimension::cost);
let fixed_cost = dimensions.flat.cost();
let duration_charging_cost = dimensions
.duration_charging
.as_ref()
.and_then(Dimension::cost);
let duration_idle_cost = dimensions.duration_idle.as_ref().and_then(Dimension::cost);
trace!(?total_costs.energy, ?energy_cost, "Energy cost");
trace!(?total_costs.duration_charging, ?duration_charging_cost, "Charging cost");
trace!(?total_costs.duration_idle, ?duration_idle_cost, "Idle cost");
trace!(?total_costs.fixed, ?fixed_cost, "Fixed cost");
total_costs.energy = match (total_costs.energy, energy_cost) {
(None, None) => None,
(total, period) => Some(
total
.unwrap_or_default()
.saturating_add(period.unwrap_or_default()),
),
};
total_costs.duration_charging =
match (total_costs.duration_charging, duration_charging_cost) {
(None, None) => None,
(total, period) => Some(
total
.unwrap_or_default()
.saturating_add(period.unwrap_or_default()),
),
};
total_costs.duration_idle = match (total_costs.duration_idle, duration_idle_cost) {
(None, None) => None,
(total, period) => Some(
total
.unwrap_or_default()
.saturating_add(period.unwrap_or_default()),
),
};
total_costs.fixed = match (total_costs.fixed, fixed_cost) {
(None, None) => None,
(total, period) => Some(
total
.unwrap_or_default()
.saturating_add(period.unwrap_or_default()),
),
};
trace!(period_index = index, ?total_costs, "Update totals");
}
total_costs
}
fn generate_report(
cdr_totals: &v221::cdr::Totals,
timezone: &TimeZone,
price_periods_report: PeriodsReport,
tariff_used: TariffOrigin,
) -> Report {
let PeriodsReport {
billable,
periods,
totals,
total_costs,
} = price_periods_report;
trace!("Update billed totals {billable:#?}");
let total_cost = total_costs.total();
debug!(total_cost = %DisplayOption(total_cost.as_ref()));
let total_time = {
debug!(
period_start = %DisplayOption(periods.first().map(|p| p.start_date_time)),
period_end = %DisplayOption(periods.last().map(|p| p.end_date_time)),
"Calculating `total_time`"
);
periods
.first()
.zip(periods.last())
.map(|(first, last)| last.end_date_time.duration_since(first.start_date_time))
.unwrap_or(SignedDuration::ZERO)
};
debug!(total_time = %Hms(total_time));
let report = Report {
periods,
tariff_used,
timezone: timezone.clone(),
billed_idle_time: billable.duration_idle,
billed_energy: billable.energy.round_to_ocpi_scale(),
billed_charging_time: billable.duration_charging,
total_charging_time: totals.duration_charging,
total_cost: Total {
cdr: cdr_totals.cost.round_to_ocpi_scale(),
calculated: total_cost.round_to_ocpi_scale(),
},
total_charging_time_cost: Total {
cdr: cdr_totals.duration_charging_cost.round_to_ocpi_scale(),
calculated: total_costs.duration_charging.round_to_ocpi_scale(),
},
total_time: Total {
cdr: cdr_totals.duration_total,
calculated: total_time,
},
total_idle_cost: Total {
cdr: cdr_totals.duration_idle_cost.round_to_ocpi_scale(),
calculated: total_costs.duration_idle.round_to_ocpi_scale(),
},
total_idle_time: Total {
cdr: cdr_totals.duration_idle,
calculated: totals.duration_idle,
},
total_energy_cost: Total {
cdr: cdr_totals.energy_cost.round_to_ocpi_scale(),
calculated: total_costs.energy.round_to_ocpi_scale(),
},
total_energy: Total {
cdr: cdr_totals.energy.round_to_ocpi_scale(),
calculated: totals.energy.round_to_ocpi_scale(),
},
total_fixed_cost: Total {
cdr: cdr_totals.fixed_cost.round_to_ocpi_scale(),
calculated: total_costs.fixed.round_to_ocpi_scale(),
},
};
trace!("{report:#?}");
report
}
fn apply_step_sizes(
periods: &mut [PeriodReportScratch],
totals: &Totals,
) -> Result<Billable, Warning> {
let has_idle_step_size = periods.iter().any(|p| p.step_size_duration_idle.is_some());
let duration_charging = if let Some(total) = totals.duration_charging {
let mut result = Some(total);
for period in periods.iter_mut().rev() {
let Some(step) = period
.step_size_duration_charging
.as_ref()
.map(|c| c.step_size)
else {
continue;
};
if has_idle_step_size {
result = Some(total);
} else if let Some(dim) = period.dimensions.duration_charging.as_mut() {
let dt = duration_step_size(total, &mut dim.billed_volume, step)?;
result = Some(dt);
}
break;
}
result
} else {
None
};
let duration_idle = if let Some(total) = totals.duration_idle {
let mut result = Some(total);
for period in periods.iter_mut().rev() {
let Some(step) = period.step_size_duration_idle.as_ref().map(|c| c.step_size) else {
continue;
};
if let Some(dim) = period.dimensions.duration_idle.as_mut() {
let dt = duration_step_size(total, &mut dim.billed_volume, step)?;
result = Some(dt);
}
break;
}
result
} else {
None
};
let energy = if let Some(total) = totals.energy {
let mut result = Some(total);
for period in periods.iter_mut().rev() {
let Some(step) = period.step_size_energy.as_ref().map(|c| c.step_size) else {
continue;
};
if step == 0 {
result = Some(total);
} else {
let step_dec = Decimal::from(step);
if let Some(dim) = period.dimensions.energy.as_mut() {
let Some(watt_hours) = total.watt_hours().checked_div(step_dec) else {
return Err(duration::Warning::Overflow.into());
};
let total_billed_volume =
Kwh::from_watt_hours(watt_hours.ceil().saturating_mul(step_dec));
let period_delta_volume = total_billed_volume.saturating_sub(total);
dim.billed_volume = dim.billed_volume.saturating_add(period_delta_volume);
result = Some(total_billed_volume);
}
}
break;
}
result
} else {
None
};
Ok(Billable {
duration_charging,
duration_idle,
energy,
})
}
fn delta_as_seconds_dec(delta: SignedDuration) -> Decimal {
Decimal::try_from_i128_with_scale(delta.as_nanos(), 9).unwrap_or(Decimal::MAX)
}
fn delta_from_seconds_dec(seconds: Decimal) -> Result<SignedDuration, Warning> {
let millis = seconds.saturating_mul(Decimal::from(duration::MILLIS_IN_SEC));
let Ok(millis) = i64::try_from(millis) else {
return Err(duration::Warning::Overflow.into());
};
Ok(SignedDuration::from_millis(millis))
}
fn duration_step_size(
total_volume: SignedDuration,
period_billed_volume: &mut SignedDuration,
step_size: u64,
) -> Result<SignedDuration, Warning> {
if step_size == 0 {
return Ok(total_volume);
}
let total_seconds = delta_as_seconds_dec(total_volume);
let step_size = Decimal::from(step_size);
let Some(x) = total_seconds.checked_div(step_size) else {
return Err(duration::Warning::Overflow.into());
};
let total_billed_volume = delta_from_seconds_dec(x.ceil().saturating_mul(step_size))?;
let period_delta_volume = total_billed_volume.saturating_sub(total_volume);
*period_billed_volume = period_billed_volume.saturating_add(period_delta_volume);
Ok(total_billed_volume)
}