Skip to main content

ocpi_tariffs/
price.rs

1//! Price a CDR using a tariff and compare the prices embedded in the CDR with the prices computed here.
2
3/// Test support shared by this module's other test files.
4#[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
57/// A [`Verdict`](crate::Verdict) whose warnings are this module's [`Warning`].
58pub type Verdict<T> = crate::Verdict<T, Warning>;
59
60/// A normalized/expanded form of a charging period to make the pricing calculation simpler.
61///
62/// The simplicity comes through avoiding having to look up the next period to figure out the end
63/// of the current period.
64#[derive(Debug)]
65struct PeriodNormalized {
66    /// The set of quantities consumed across the duration of the `Period`.
67    consumed: Consumed,
68
69    /// A snapshot of the values of various quantities at the start of the charge period.
70    start_snapshot: TotalsSnapshot,
71
72    /// A snapshot of the values of various quantities at the end of the charge period.
73    end_snapshot: TotalsSnapshot,
74}
75
76/// The set of quantities consumed across the duration of the `Period`.
77#[derive(Clone)]
78#[cfg_attr(test, derive(Default))]
79pub(crate) struct Consumed {
80    /// The peak current during this period.
81    pub current_max: Option<Ampere>,
82
83    /// The lowest current during this period.
84    pub current_min: Option<Ampere>,
85
86    /// The charging time consumed in this period.
87    pub duration_charging: Option<SignedDuration>,
88
89    /// The parking/idle time consumed in this period.
90    pub duration_idle: Option<SignedDuration>,
91
92    /// The energy consumed in this period.
93    pub energy: Option<Kwh>,
94
95    /// The maximum power reached during this period.
96    pub power_max: Option<Kw>,
97
98    /// The minimum power reached during this period.
99    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/// A snapshot of the values of various quantities at the start and end of the charge period.
120#[derive(Clone)]
121struct TotalsSnapshot {
122    /// The `Timestamp` this snapshot of total quantities was taken.
123    date_time: Timestamp,
124
125    /// The total energy consumed during a charging period.
126    energy: Kwh,
127
128    /// The local timezone.
129    local_timezone: TimeZone,
130
131    /// The total charging duration during a charging period.
132    duration_charging: SignedDuration,
133
134    /// The total period duration during a charging period.
135    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    /// Create a snapshot where all quantities are zero.
152    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    /// Create a new snapshot based on the current snapshot with consumed quantities added.
163    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    /// Return the local time of this snapshot.
185    fn local_time(&self) -> jiff::civil::Time {
186        self.local_timezone.to_datetime(self.date_time).time()
187    }
188
189    /// Return the local date of this snapshot.
190    fn local_date(&self) -> jiff::civil::Date {
191        self.local_timezone.to_datetime(self.date_time).date()
192    }
193
194    /// Return the local `Weekday` of this snapshot.
195    fn local_weekday(&self) -> jiff::civil::Weekday {
196        self.local_timezone.to_datetime(self.date_time).weekday()
197    }
198}
199
200/// Structure containing the charge session priced according to the specified tariff.
201/// The fields prefixed `total` correspond to CDR fields with the same name.
202pub struct Report {
203    /// Charge session details per period.
204    pub periods: Vec<PeriodReport>,
205
206    /// The index of the tariff that was used for pricing.
207    pub tariff_used: TariffOrigin,
208
209    /// Time-zone that was either specified or detected.
210    pub timezone: TimeZone,
211
212    /* Billed Quantities */
213    /// The total charging time after applying step-size.
214    pub billed_charging_time: Option<SignedDuration>,
215
216    /// The total energy after applying step-size.
217    pub billed_energy: Option<Kwh>,
218
219    /// The total idle time after applying step-size.
220    pub billed_idle_time: Option<SignedDuration>,
221
222    /* Totals */
223    /// Total duration of the charging session (excluding not charging), in hours.
224    ///
225    /// This is a total that has no direct source field in the `CDR` as it is calculated in the
226    /// [`cdr::price`](crate::cdr::price) function.
227    pub total_charging_time: Option<SignedDuration>,
228
229    /// Total energy charged, in kWh.
230    pub total_energy: Total<Kwh, Option<Kwh>>,
231
232    /// Total duration of the charging session where the EV was not charging (no energy was transferred between EVSE and EV).
233    ///
234    /// See: `total_parking_time` field in <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc#mod_cdrs_cdr_object>.
235    /// Note: We use `total_idle_time` as it's clearer than `total_parking_time`.
236    /// Some people interpret `parking` to mean the total time that the vehicle is standing by the charge point.
237    /// The OCPI spec defines `parking` as the time spent not charging.
238    pub total_idle_time: Total<Option<SignedDuration>>,
239
240    /// Total duration of the charging session (including the duration of charging and idle phases).
241    pub total_time: Total<SignedDuration>,
242
243    /* Costs */
244    /// Total sum of all the costs of this transaction in the specified currency.
245    ///
246    /// For a Credit CDR, `calculated` holds the session's total cost negated, because a Credit CDR
247    /// states its `total_cost` negated and no other total. The other totals in the `Report`, such
248    /// as `total_energy_cost`, hold the session's amounts with their sign unchanged.
249    ///
250    /// See: [OCPI spec 2.2.1: Credit CDRs](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc#mod_cdrs_credit_cdrs>).
251    pub total_cost: Total<Price, Option<Price>>,
252
253    /// Total sum of all the cost of all the energy used, in the specified currency.
254    pub total_energy_cost: Total<Option<Price>>,
255
256    /// Total sum of all the fixed costs in the specified currency, except fixed price components of `parking` and `reservation`.
257    /// The cost not depending on amount of time/energy used etc. Can contain costs like a start tariff.
258    pub total_fixed_cost: Total<Option<Price>>,
259
260    /// Total sum of all the costs related to idleness during this transaction. This includes fixed price components, in the specified currency.
261    ///
262    /// See: `total_parking_cost` field in <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc#mod_cdrs_cdr_object>.
263    /// Note: We use `total_idle_cost` as it's clearer than `total_parking_cost`.
264    /// Some people interpret `parking` to mean the total time that the vehicle is standing by the charge point.
265    /// The OCPI spec defines `parking` as the time spent not charging.
266    pub total_idle_cost: Total<Option<Price>>,
267
268    /// Total sum of all the cost related to duration of charging during this transaction, in the specified currency.
269    ///
270    /// See: `total_time_cost` field in <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc#mod_cdrs_cdr_object>.
271    /// Note: We use `total_charging_time_cost` as it's clearer than `total_time_cost`.
272    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/// The warnings that happen when pricing a CDR.
307#[derive(Debug)]
308pub enum Warning {
309    /// Raised while calculating with a duration, such as a billed time that overflows.
310    Duration(duration::Warning),
311
312    /// The tariff's `min_price` is above its `max_price`, so no total satisfies both.
313    ///
314    /// `lint` reports the same fault, but pricing does not run the lint pass. Without this
315    /// warning a contradictory tariff prices quietly. The pricer clamps the total to `min_price`
316    /// and then to `max_price`, and neither clamp warning reports that no total satisfies both.
317    ///
318    /// * See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariff_object>
319    MinPriceIsGreaterThanMax,
320
321    /// None of the tariffs given to [`cdr::price`](crate::cdr::price) is active at the start of
322    /// the session.
323    ///
324    /// The tariffs are either the ones the CDR contains, which
325    /// [`Cdr::tariffs`](crate::cdr::Cdr::tariffs) builds, or tariffs the caller builds with
326    /// [`tariff::build`](crate::tariff::build).
327    ///
328    /// A tariff is active from its `start_date_time`, inclusive, until its `end_date_time`,
329    /// exclusive. A tariff without one of the two fields has no bound on that side.
330    ///
331    /// If the CDR does not contain any tariffs, consider building tariffs from their own
332    /// documents and passing them to `cdr::price`.
333    NoValidTariff,
334
335    /// None of the CDR's charging periods has a `TIME` or `PARKING_TIME` dimension, and the
336    /// selected tariff has a `TIME` or `PARKING_TIME` price component.
337    ///
338    /// The calculated cost then leaves out what the tariff charges for time, because pricing
339    /// reads a period's time only from those dimensions.
340    PeriodsStateNoTime,
341
342    /// A tariff element has a `reservation` restriction (`RESERVATION` or
343    /// `RESERVATION_EXPIRES`).
344    ///
345    /// Such elements apply only to reservation sessions, not to regular charging sessions. Because
346    /// reservation pricing is not supported, the element is treated as permanently inactive.
347    ///
348    /// * See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_reservation_restriction_type>
349    ReservationElementSkipped,
350
351    /// The given tariff has a `max_price` set and the `total_cost` exceeded it.
352    ///
353    /// * See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariff_object>
354    TotalCostClampedToMax,
355
356    /// The given tariff has a `min_price` set and the `total_cost` was below it, or was
357    /// never calculated because no element priced the session.
358    ///
359    /// * See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariff_object>
360    TotalCostClampedToMin,
361
362    /// The total cost including VAT is no longer known.
363    ///
364    /// The tariff's `min_price` states no `min_price.incl_vat`, and replacing
365    /// `total_cost.excl_vat` with it makes the two values imply a VAT rate below `0`. That is the
366    /// fault [`money::Warning::ImpliedVatIsNegative`] reports on a price a tariff states. Under a
367    /// `min_price.excl_vat` of 6.00, a session of 4.90 and 5.9290 is reported as 6.00 with no
368    /// `total_cost.incl_vat`. Under 5.00 the pricer keeps the 5.9290.
369    ///
370    /// The discarded value is not recomputed. A session has no single VAT rate to apply. Each
371    /// price component states its own rate, and the rate a session total implies is an average
372    /// of those weighted by what each component cost. `min_price` is a value the tariff asserts
373    /// about the session as a whole. No component produced that value, so no rate belongs to it.
374    ///
375    /// A calculated `total_cost.incl_vat` is also absent for a v2.1.1 tariff, which has no `vat`
376    /// field at all. This warning is what tells the two apart.
377    ///
378    /// [`money::Warning::ImpliedVatIsNegative`]: crate::money::Warning::ImpliedVatIsNegative
379    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/// The origin data for a tariff.
459#[derive(Clone, Debug)]
460pub struct TariffOrigin {
461    /// The index of the tariff in the tariffs given to [`cdr::price`](crate::cdr::price).
462    pub index: usize,
463
464    /// The value of the `id` field in the tariff JSON.
465    pub id: String,
466
467    /// The currency code of the tariff.
468    pub currency: currency::Code,
469}
470
471/// A CDR charge period in a normalized form ready for pricing.
472#[derive(Debug)]
473pub(crate) struct Period {
474    /// The start time of this period.
475    pub start_date_time: Timestamp,
476
477    /// The quantities consumed during this period.
478    pub consumed: Consumed,
479}
480
481/// A structure containing a report for each dimension of a CDRs charging period, held by
482/// [`PeriodReport`].
483#[derive(Debug)]
484pub struct Dimensions {
485    /// Energy consumed. `None` if the CDR period had no energy dimension.
486    pub energy: Option<Dimension<Kwh>>,
487
488    /// Flat fee without unit for `step_size`.
489    pub flat: Dimension<()>,
490
491    /// Duration of time charging. `None` if the CDR period had no time dimension.
492    pub duration_charging: Option<Dimension<SignedDuration>>,
493
494    /// Duration of time not charging. `None` if the CDR period had no parking-time dimension.
495    pub duration_idle: Option<Dimension<SignedDuration>>,
496}
497
498impl Dimensions {
499    /// Create a new `Dimensions` object.
500    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)]
544/// A report for a single dimension during a single charging period.
545pub struct Dimension<V> {
546    /// The price component that was active during this period for this dimension.
547    /// It could be that no price component was active during this period for this dimension in
548    /// which case `price` is `None`.
549    pub price: Option<Component>,
550
551    /// The volume of this dimension during this period, as received in the provided charge detail record.
552    pub volume: V,
553
554    /// The value of `volume` after a potential step size was applied.
555    /// Step size is applied over the total volume during the whole session of a dimension. But the
556    /// resulting additional volume should be billed according to the price component in this
557    /// period.
558    ///
559    /// If no step-size was applied for this period, the volume is exactly equal to the `volume`
560    /// field.
561    pub billed_volume: V,
562}
563
564impl<V: Cost> Dimension<V> {
565    /// The total cost of this dimension during a period.
566    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/// A set of price `Component`s, one for each dimension.
584///
585/// See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_pricecomponent_class>.
586/// See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariffdimensiontype_enum>.
587#[derive(Debug)]
588pub struct ComponentSet {
589    /// Energy consumed.
590    pub energy: Option<Component>,
591
592    /// Flat fee without unit for `step_size`.
593    pub flat: Option<Component>,
594
595    /// Duration of time charging.
596    pub duration_charging: Option<Component>,
597
598    /// Duration of time not charging.
599    pub duration_idle: Option<Component>,
600}
601
602impl ComponentSet {
603    /// Returns true if all components are `Some`.
604    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/// A price component prices one dimension: it turns the amount consumed into the money
617/// owed.
618///
619/// See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_pricecomponent_class>.
620#[derive(Clone, Debug)]
621pub struct Component {
622    /// Price per unit (excl. VAT) for this dimension.
623    price: Money,
624
625    /// Applicable VAT percentage for this tariff dimension. If omitted, no VAT is applicable.
626    /// Not providing a VAT is different from 0% VAT, which would be a value of 0.0 here.
627    vat: VatOrigin,
628
629    /// Minimum amount to be billed. That is, the dimension will be billed in this `step_size` blocks.
630    /// Consumed amounts are rounded up to the smallest multiple of `step_size` that is greater than
631    /// the consumed amount.
632    ///
633    /// For example: if type is TIME and `step_size` has a value of 300, then time will be billed in
634    /// blocks of 5 minutes. If 6 minutes were consumed, 10 minutes (2 blocks of `step_size`) will
635    /// be billed.
636    step_size: u64,
637}
638
639impl Component {
640    /// Create a new `Component` object.
641    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    /// Return the price of the `Component`.
657    pub fn price(&self) -> Money {
658        self.price
659    }
660}
661
662/// The amount a CDR states for one total, beside the amount the pricer calculated for it.
663///
664/// This is used to express the source and calculated amounts for the total fields of a `CDR`.
665///
666/// - `total_cost`
667/// - `total_fixed_cost`
668/// - `total_energy`
669/// - `total_energy_cost`
670/// - `total_time`
671/// - `total_time_cost`
672/// - `total_parking_time`
673/// - `total_parking_cost`
674#[derive(Debug)]
675pub struct Total<TCdr, TCalc = TCdr> {
676    /// The source value from the `CDR`.
677    pub cdr: TCdr,
678
679    /// The value calculated by the [`cdr::price`](crate::cdr::price) function.
680    pub calculated: TCalc,
681}
682
683/// Price a CDR.
684///
685/// See: [`crate::cdr::price`].
686#[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
697/// Price a single charge-session using the first tariff in `tariffs` that is active at the
698/// session's start.
699///
700/// Returns a report containing the totals, subtotals, and a breakdown of the calculation.
701///
702/// List order decides which tariff prices, since selection is the first active one and
703/// not the best match. A session no tariff was active for is refused with
704/// `Warning::NoValidTariff` rather than priced at zero.
705fn 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        // `cdr::build` refuses a CDR whose `charging_periods` the schema couldn't build, and
748        // pricing takes only a built `Cdr`, so only the `Ok` arms run.
749        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    // Convert the CDRs periods to the API input period.
764    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    // The negation follows the clamp because `min_price` and `max_price` bound what the credited
803    // CDR billed. Negating first would raise a negative total to a positive `min_price`, and no
804    // negated total would ever be above `max_price`.
805    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
812/// Bound a session's total cost by a tariff's `min_price` and `max_price`.
813///
814/// `excl_vat` and `incl_vat` are bounded separately. OCPI states each bound as two rules, one
815/// per value, and says of both that "as a rule, they both apply"
816/// (`specs/v221/mod_tariffs.asciidoc:295-303`). A bound whose own VAT rate differs from the
817/// session's therefore binds one value while the other stays in range. The total that results
818/// can imply a rate matching neither, which is the case the spec describes rather than an
819/// inconsistency to repair.
820///
821/// A bound does not take `incl_vat` into account if either side lacks it. The bound may omit the
822/// value, and a v2.1.1 session has no inclusive total at all.
823///
824/// A `min_price` that states no `min_price.incl_vat` replaces `total_cost.excl_vat` with a value
825/// that has no inclusive counterpart. The replacement and the session's `total_cost.incl_vat` can
826/// then imply a VAT rate below `0`, which `money::Warning::ImpliedVatIsNegative` reports on a
827/// price a tariff states. The clamp discards `total_cost.incl_vat` only in that case and sets
828/// `Clamped::incl_vat_unknown`. The discarded value cannot be recomputed, because the session's
829/// dimensions can have different VAT rates. `money::Price::vat_is_consistent` decides that rather
830/// than a comparison of the two values, for the reason its own documentation gives.
831///
832/// Discarding on every such replacement would be wrong. The argument for it is that a surviving
833/// `total_cost.incl_vat` was computed from the `total_cost.excl_vat` the clamp has just replaced,
834/// so the two no longer describe one cost. OCPI produces that same mismatch by itself: a
835/// `max_price` that clamps `total_cost.incl_vat` while `total_cost.excl_vat` stays in range
836/// reports the session's exclusive value beside the bound's inclusive one, which the rule quoted
837/// above requires. A total whose two values come from different sources is therefore the spec's
838/// own case rather than a fault. What this function repairs is narrower: a `min_price` that states
839/// no `min_price.incl_vat` where the two values then imply a rate below `0`. The check does not
840/// reach a `min_price` that states both values, and the `max_price` arm has no such check at all,
841/// which #538 tracks.
842///
843/// A `min_price` also seeds a total that was never calculated. OCPI says a session with the
844/// tariff "will at least cost this amount", which says nothing about whether an element priced
845/// it. `max_price` clamps only a total that exists, and `max_price` runs second, so a
846/// `min_price` above it is seeded and then clamped back down.
847pub(crate) fn clamp_total_cost(
848    total_cost: &mut Option<Price>,
849    min_price: Option<Price>,
850    max_price: Option<Price>,
851) -> Clamped {
852    // Deriving this from both clamps having fired would be wrong. A `min_price` can clamp
853    // `total_cost.excl_vat` while a `max_price` clamps `total_cost.incl_vat`, with neither bound
854    // above the other.
855    // The two bounds are compared directly instead, before either is applied.
856    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                    // The check reads the `excl_vat` just assigned against the `incl_vat` the
880                    // pricer calculated, which nothing has replaced yet. Ordered the other way
881                    // it would judge the pricer's own pair rather than the pair this clamp
882                    // produces.
883                    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
924/// What `clamp_total_cost` did to a session total, and what it found wrong with the tariff.
925///
926/// A `min_price` and a `max_price` can both clamp the total in one pass, so `to_min` and
927/// `to_max` are not exclusive. The two callers anchor their warnings on different elements, so
928/// `clamp_total_cost` reports what happened and the caller raises the warning.
929pub(crate) struct Clamped {
930    /// The total was raised to `min_price`, in one or both of its values.
931    ///
932    /// Also set when nothing was calculated and `min_price` seeded the total.
933    pub to_min: bool,
934
935    /// The total was lowered to `max_price`, in one or both of its values.
936    pub to_max: bool,
937
938    /// The clamp discarded `total_cost.incl_vat` rather than report two values implying a VAT
939    /// rate below `0`.
940    ///
941    /// Separate from `to_min`, because a `min_price` can replace `total_cost.excl_vat` while
942    /// `total_cost.incl_vat` survives. A `total_cost.incl_vat` of `None` otherwise reaches the
943    /// caller unexplained.
944    pub incl_vat_unknown: bool,
945
946    /// The tariff's `min_price` is above its `max_price`, so no total satisfies both.
947    ///
948    /// This is a property of the tariff, not of what happened to this session, so the field is
949    /// set before either bound is applied.
950    pub min_above_max: bool,
951}
952
953/// Price a list of [`Period`]s using a v2.2.1 tariff.
954///
955/// `periods` reports every warning it raises against `elem`. `generate` passes the element
956/// of the tariff it generates a CDR from.
957pub(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    // Make sure the periods are sorted by time as the start date of one period determines the end
966    // date of the previous period.
967    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    // Each new period is linked to the previous periods data.
981    let mut previous_end_snapshot = Option::<TotalsSnapshot>::None;
982
983    // The end-date of the first period is the start-date of the second and so on.
984    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        // The last end-date is the end-date of the CDR.
992        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
1045/// Read a period's `TIME` or `PARKING_TIME` volume as the period's length when the two differ by no
1046/// more than rounding the volume to OCPI's 4 decimals of an hour can move it.
1047///
1048/// OCPI states a volume in hours to 4 decimals, so 40 minutes has to be written as `0.6667`, which
1049/// is 2400.12 seconds. Billing that volume as stated would bill 41 minutes at a step size of 60
1050/// seconds. Rounding to 4 decimals moves a value by at most half of 0.0001 hours, which is 0.18
1051/// seconds. A volume further than that from the period's length, such as the charging part of a
1052/// period that also states `PARKING_TIME`, is returned as stated.
1053///
1054/// Rounding every volume to the whole second would also bill 40 minutes, but OCPI allows fractional
1055/// seconds in a timestamp, so a period of 60.4 seconds would be billed one step short.
1056fn 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    // A volume of `0` states that the session spent none of the period charging, for `TIME`, or
1063    // parked, for `PARKING_TIME`. Reading it as the length of a period shorter than 0.18 seconds
1064    // would bill a whole step for time the session never used, so a volume of `0` is returned as
1065    // stated.
1066    if duration.is_zero() {
1067        return duration;
1068    }
1069
1070    // `SignedDuration`'s own `saturating_sub` saturates to `SignedDuration::MIN`, and
1071    // `abs` panics on that value. This crate's `SaturatingSub` saturates to `0` instead.
1072    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
1081/// Price the given set of CDR periods using a normalized `Tariff`.
1082///
1083/// `price_periods` reports every warning it raises against `elem`. A caller pricing a CDR
1084/// passes the CDR's element, and `generate` passes the tariff's through [`periods`].
1085fn 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
1121/// The internal report generated from the [`periods`] fn.
1122pub(crate) struct PeriodsReport {
1123    /// The billable dimensions calculated by applying the step-size to each dimension.
1124    pub billable: Billable,
1125
1126    /// A list of reports for each charging period that occurred during a session.
1127    pub periods: Vec<PeriodReport>,
1128
1129    /// The totals for each dimension.
1130    pub totals: Totals,
1131
1132    /// The total costs for each dimension.
1133    pub total_costs: TotalCosts,
1134}
1135
1136/// A report for a single charging period that occurred during a session.
1137///
1138/// A charging period is a period of time that has relevance for the total costs of a CDR.
1139/// During a charging session, different parameters change all the time, like the amount of energy used,
1140/// or the time of day. These changes can result in another [`PriceComponent`](https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_pricecomponent_class) of the Tariff becoming active.
1141#[derive(Debug)]
1142pub struct PeriodReport {
1143    /// The start time of this period.
1144    pub start_date_time: Timestamp,
1145
1146    /// The end time of this period.
1147    pub end_date_time: Timestamp,
1148
1149    /// A structure that contains results per dimension.
1150    pub dimensions: Dimensions,
1151}
1152
1153impl PeriodReport {
1154    /// The total cost of all dimensions in this period.
1155    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/// A [`PeriodReport`] under construction during the step-size calculation.
1184///
1185/// After step sizes are applied the step-size fields are dropped and this converts into
1186/// a [`PeriodReport`].
1187#[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/// The result of normalizing the CDR charging periods.
1208#[derive(Debug)]
1209struct PeriodTotals {
1210    /// The list of periods under construction.
1211    periods: Vec<PeriodReportScratch>,
1212
1213    /// The totals for each dimension.
1214    totals: Totals,
1215}
1216
1217/// The totals for each dimension.
1218#[derive(Debug, Default)]
1219pub(crate) struct Totals {
1220    /// The total energy used during a session.
1221    pub energy: Option<Kwh>,
1222
1223    /// The total charging time used during a session.
1224    ///
1225    /// Some if the charging happened during the session.
1226    pub duration_charging: Option<SignedDuration>,
1227
1228    /// The total idle time during a session.
1229    ///
1230    /// Some if there was idle time during the session.
1231    pub duration_idle: Option<SignedDuration>,
1232}
1233
1234impl PeriodTotals {
1235    /// Apply step sizes and convert scratch periods into final [`PeriodReport`]s.
1236    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/// The billable dimensions calculated by applying the step-size to each dimension.
1251#[derive(Debug)]
1252pub(crate) struct Billable {
1253    /// The billable charging time.
1254    duration_charging: Option<SignedDuration>,
1255
1256    /// The billable idle time.
1257    duration_idle: Option<SignedDuration>,
1258
1259    /// The billable energy use.
1260    energy: Option<Kwh>,
1261}
1262
1263/// Map the `session::ChargePeriod`s to a normalized `Period` and calculate the step size and
1264/// totals for each dimension.
1265fn 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            // Extract step-size components before consuming the component_set.
1294            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/// The total costs for each dimension.
1346#[derive(Debug, Default)]
1347pub(crate) struct TotalCosts {
1348    /// The [`Price`] for all energy used during a session.
1349    pub energy: Option<Price>,
1350
1351    /// The [`Price`] for all flat rates applied during a session.
1352    pub fixed: Option<Price>,
1353
1354    /// The [`Price`] for all charging time used during a session.
1355    pub duration_charging: Option<Price>,
1356
1357    /// The [`Price`] for all idle time used during a session.
1358    pub duration_idle: Option<Price>,
1359}
1360
1361impl TotalCosts {
1362    /// Summate each dimension total into a single total.
1363    ///
1364    /// Return `None` if there are no cost dimensions otherwise return `Some`.
1365    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
1392/// Accumulate total costs per dimension across all periods.
1393fn 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
1542/// Apply step sizes by iterating in reverse over the scratch periods to find the last period
1543/// that had an active component for each dimension, then mutating its `billed_volume`.
1544///
1545/// A step size rounds up the session's total for a dimension rather than each period's volume.
1546/// This function bills the extra volume from rounding in that last period. For two charging
1547/// periods of 10 and 7 minutes and a `TIME` `step_size` of 300 seconds (5 minutes), it bills the
1548/// total of 17 minutes as 20:
1549///
1550/// ```text
1551///   periods     [ 10 min ------)[ 7 min --)
1552///   billed      [ 10 min ------)[ 7 + 3 min ---)
1553/// ```
1554///
1555/// OCPI takes a step size into account once for `TIME` and `PARKING_TIME` combined. So when a
1556/// `PARKING_TIME` component prices any idle period, this function rounds only the idle total, and
1557/// bills the charging total as the CDR states it.
1558fn 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
1639/// Return the duration as a `Decimal` amount of seconds.
1640fn delta_as_seconds_dec(delta: SignedDuration) -> Decimal {
1641    // The conversion keeps every nanosecond because `duration_step_size` rounds the result
1642    // up to a whole step. Converting from milliseconds would truncate a period of 300.0004 seconds
1643    // to 300, so a `step_size` of 300 would bill one step where rounding up asks for two.
1644    //
1645    // A `SignedDuration` lies within 2^63 seconds and 999,999,999 nanoseconds of zero,
1646    // in either direction, which is fewer than 2^93 nanoseconds. A `Decimal` holds a 96-bit
1647    // integer, so the conversion always succeeds and the `unwrap_or` is unreachable.
1648    Decimal::try_from_i128_with_scale(delta.as_nanos(), 9).unwrap_or(Decimal::MAX)
1649}
1650
1651/// Create a `SignedDuration` from a `Decimal` amount of seconds.
1652fn 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
1660/// Apply a duration based step size for either `time` or `idle_time`.
1661fn 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}