ocpi-tariffs 0.51.0

OCPI tariff calculations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
//! Produce a human-language explanation of a tariff.
//!
//! The explanation is rendered as Markdown, aimed at a person who wants to understand what a tariff
//! charges and when, without having to read the OCPI spec themselves.
//!
//! Rather than describing the tariff field-by-field, the explanation reads the tariff the way a
//! pricing engine does. It groups the price components by dimension (energy, charging
//! time, idle time, flat fee) and narrates how the rate changes as a session progresses.
//! A dimension with more than one tier is rendered as a bulleted list. The interpretation
//! folds in the spec knowledge that:
//!
//! - Tariff elements are matched from the top down, and for each dimension the first element whose
//!   restrictions match supplies the rate. This lets a list of elements express tiers, such as one
//!   rate "for the first 3 hours" and another for "the remaining time".
//! - `TIME` is time spent actively charging, while `PARKING_TIME` is time connected but idle (for
//!   example, after the car has finished charging).
//! - A `min_duration`/`max_duration` restriction bounds a tier by how long the session has lasted;
//!   a `min_kwh`/`max_kwh` restriction bounds it by how much energy has been consumed.
//! - An element with a `reservation` restriction never applies to a regular charging session.
//!
//! The work is split in two: [`build`] reads the tariff and produces a language-independent
//! [`Explanation`] that captures *what* to say, and the
//! [renderer](super::render) turns that into prose in a chosen [`Language`]. Every semantic
//! decision lives in `build`, so a new language only supplies vocabulary and formatting.
//!
//! * See: [OCPI spec 2.2.1: Tariff](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#131-tariff-object>)
//! * See: [OCPI spec 2.1.1: Tariff](<https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_tariffs.md#31-tariff-object>)

use chrono::{DateTime, Utc};
use rust_decimal::Decimal;

use crate::{
    explain::{
        ir::{
            Body, Bounds, Condition, ConditionPart, Dimension, Explanation, Fallback, Flat,
            FlatFee, FlatTier, Rate, Scope, Section, Tier, TimeWindow, Validity,
        },
        render::{render, Language},
    },
    json::FromJson as _,
    money::VatOrigin,
    tariff::{
        v221::{Element, Restrictions, Tariff},
        v2x::DimensionType,
        Warning,
    },
    warning::VerdictExt as _,
    Money, Price, Verdict, Version, Versioned as _,
};

/// Build a human-language explanation of the given tariff as Markdown, in the given language.
///
/// The tariff is parsed into the normalized `v2.2.1` form first, so a `v2.1.1` tariff is explained as
/// its `v2.2.1` equivalent. Any warnings raised while parsing are returned alongside the
/// explanation; a hard parse failure returns an [`ErrorSet`](crate::warning::ErrorSet) instead.
pub(crate) fn explain(
    tariff: &crate::tariff::Versioned<'_>,
    language: Language,
) -> Verdict<String, Warning> {
    let parsed = match tariff.version() {
        Version::V211 => {
            crate::tariff::v211::Tariff::from_json(tariff.as_element()).map_caveat(Tariff::from)
        }
        Version::V221 => Tariff::from_json(tariff.as_element()),
    };

    parsed.map_caveat(|tariff| render(&build(&tariff), language))
}

/// Read the parsed tariff into a language-independent explanation.
///
/// Dimensions are narrated energy first, then the time-based charges (charging then idle), then any
/// flat fee, followed by the session-level price bounds and validity window. When nothing produces
/// a section, a [`Fallback`] reason explains why in terms of the tariff.
pub(super) fn build(tariff: &Tariff<'_>) -> Explanation {
    let elements = &tariff.elements;
    let mut sections: Vec<Section> = Vec::new();

    for dimension in [
        DimensionType::Energy,
        DimensionType::Time,
        DimensionType::ParkingTime,
    ] {
        if let Some(section) = build_dimension(elements, dimension) {
            sections.push(Section::Dimension(section));
        }
    }
    if let Some(section) = build_flat(elements) {
        sections.push(Section::Flat(section));
    }
    if let Some(section) = build_bounds(tariff.min_price, tariff.max_price) {
        sections.push(Section::Bounds(section));
    }
    if let Some(section) = build_validity(tariff.start_date_time, tariff.end_date_time) {
        sections.push(Section::Validity(section));
    }

    let body = if sections.is_empty() {
        Body::Fallback(fallback_reason(tariff))
    } else {
        Body::Sections(sections)
    };

    Explanation {
        currency: tariff.currency,
        body,
    }
}

/// Explain why a tariff produces no charging narrative, in terms of what the tariff contains.
///
/// This is reached only when no dimension, price bound or validity window produced any content, so
/// the reason describes the cause in the tariff rather than any limitation of this tool.
fn fallback_reason(tariff: &Tariff<'_>) -> Fallback {
    let elements = &tariff.elements;

    // Every element is gated on reservations, so none apply to a regular charging session.
    if elements.iter().all(is_reservation_only) {
        return Fallback::ReservationOnly;
    }

    // None of the applicable elements define any price component to charge on.
    let has_components = elements
        .iter()
        .filter(|element| !is_reservation_only(element))
        .any(|element| !element.price_components.is_empty());

    if !has_components {
        return Fallback::NoPriceComponents;
    }

    // The only thing left that produces no content is a flat fee priced at zero.
    Fallback::FreeFlatOnly
}

/// Returns true when an element applies only to reservation sessions and so never applies to a
/// regular charging session.
fn is_reservation_only(element: &Element) -> bool {
    element
        .restrictions
        .as_ref()
        .is_some_and(|restrictions| restrictions.reservation.is_some())
}

/// A single priced tier of a dimension: a rate that applies under a set of restrictions.
struct Band<'a> {
    /// The rate for this tier.
    price: Money,

    /// The VAT applied to the rate.
    vat: VatOrigin,

    /// The smallest billable unit; consumption is rounded up to a multiple of this. The unit
    /// depends on the dimension: 1 Wh for energy, 1 second for charging or idle time.
    step_size: u64,

    /// The restrictions that bound this tier.
    restrictions: Option<&'a Restrictions>,
}

/// Collect the priced tiers for a single dimension, in matching order.
fn bands(elements: &[Element], dimension: DimensionType) -> Vec<Band<'_>> {
    let mut bands = Vec::new();

    for element in elements {
        // An element gated on reservations never applies to a regular charging session, so it
        // does not contribute a tier to the explanation.
        if is_reservation_only(element) {
            continue;
        }

        // Only the first price component per dimension in an element is used by the pricing
        // engine, so any later duplicates within the same element are ignored here too.
        if let Some(component) = element
            .price_components
            .iter()
            .find(|component| component.dimension_type == dimension)
        {
            bands.push(Band {
                price: component.price,
                vat: component.vat,
                step_size: component.step_size,
                restrictions: element.restrictions.as_ref(),
            });
        }
    }

    bands
}

/// Build the flat (per-session) fee section, or fees.
///
/// Like the metered dimensions, a tariff can have several flat tiers (one per matching element)
/// under different conditions, matched top-down. A flat fee can be gated by time of day, date, or a
/// consumption bound (`min/max_duration`, `min/max_kwh`), so the condition pulls in all of those.
fn build_flat(elements: &[Element]) -> Option<Flat> {
    let mut bands = bands(elements, DimensionType::Flat);

    // A tier with no condition always matches, so any flat tier after it is unreachable.
    let reachable = bands
        .iter()
        .position(|band| {
            band.restrictions
                .is_none_or(|restrictions| flat_condition(restrictions).is_empty())
        })
        .map(|index| index.saturating_add(1))
        .unwrap_or(bands.len());
    bands.truncate(reachable);

    let tiers: Vec<FlatTier> = bands
        .iter()
        .enumerate()
        .map(|(index, band)| {
            let parts = band.restrictions.map(flat_condition).unwrap_or_default();
            let condition = if !parts.is_empty() {
                Condition::When(parts)
            } else if index > 0 {
                Condition::Otherwise
            } else {
                Condition::Always
            };

            let fee = if is_free(band.price) {
                FlatFee::NoFee
            } else {
                FlatFee::Charged {
                    amount: band.price,
                    vat: band.vat,
                }
            };

            FlatTier { condition, fee }
        })
        .collect();

    // No flat tiers, or a lone zero fee, means there is no flat fee worth a sentence.
    match tiers.as_slice() {
        [] => None,
        [tier] if matches!(tier.fee, FlatFee::NoFee) => None,
        _ => Some(Flat { tiers }),
    }
}

/// The condition under which a flat tier applies: the qualifiers plus any consumption bounds.
fn flat_condition(restrictions: &Restrictions) -> Vec<ConditionPart> {
    let mut parts = qualifiers(restrictions);
    if let Some(scope) = duration_scope(restrictions) {
        parts.push(ConditionPart::DurationScope(scope));
    }
    if let Some(scope) = energy_scope(restrictions) {
        parts.push(ConditionPart::EnergyScope(scope));
    }
    parts
}

/// Build a metered dimension (energy, charging time or idle time) as a sequence of tiers.
///
/// A dimension can have several priced tiers, one per matching element, matched top-down: the first
/// matching element wins. Each tier carries the condition under which it applies, its rate, and
/// (when the billing step varies across tiers) its own billing step.
///
/// A trailing tier with no condition is the catch-all: it becomes [`Condition::Remaining`] when the
/// earlier tiers were purely consumption-bounded, and [`Condition::Otherwise`] when an earlier tier
/// was gated by something else (power, current, time of day). Tiers made unreachable by an earlier
/// catch-all are dropped and noted.
fn build_dimension(elements: &[Element], dimension: DimensionType) -> Option<Dimension> {
    let bands = bands(elements, dimension);
    if bands.is_empty() {
        return None;
    }

    // Compute each band's condition pieces: the dimension's own bound (primary), the other
    // consumption bound (secondary, which the spec also allows, e.g. an energy threshold on a
    // charging-time tier), and the non-consumption qualifiers (time of day, weekday, ...).
    let pieces: Vec<(
        Option<ConditionPart>,
        Option<ConditionPart>,
        Vec<ConditionPart>,
    )> = bands
        .iter()
        .map(|band| {
            let primary = band
                .restrictions
                .and_then(|restrictions| primary_scope(restrictions, dimension));
            let secondary = band
                .restrictions
                .and_then(|restrictions| secondary_scope(restrictions, dimension));
            let qualifiers = band.restrictions.map(qualifiers).unwrap_or_default();
            (primary, secondary, qualifiers)
        })
        .collect();

    // A tier with no consumption bound and no qualifiers always matches, so it is the catch-all:
    // every tier listed after it is unreachable. Keep the catch-all and drop the dead tiers.
    let reachable = pieces
        .iter()
        .position(|(primary, secondary, qualifiers)| {
            primary.is_none() && secondary.is_none() && qualifiers.is_empty()
        })
        .map(|index| index.saturating_add(1))
        .unwrap_or(pieces.len());
    let dropped = pieces.len().saturating_sub(reachable);

    // When every reachable tier shares the same billing step, describe it once for the dimension;
    // otherwise the step varies per tier and is noted inline on each.
    let first_step = bands.first().map(|band| band.step_size);
    let uniform = first_step.is_some_and(|step| {
        bands
            .iter()
            .take(reachable)
            .all(|band| band.step_size == step)
    });
    // A shared step of 1 (the smallest unit) is effectively continuous billing and not described.
    let uniform_step = first_step.filter(|&step| uniform && step != 1);

    // Track what earlier tiers looked like, to classify a trailing catch-all: "the remaining ..."
    // only follows purely consumption-bounded tiers; anything else makes it "otherwise".
    let mut seen_bound = false;
    let mut seen_qualifier = false;
    let mut tiers: Vec<Tier> = Vec::with_capacity(reachable);

    for (index, (band, (primary, secondary, qualifiers))) in
        bands.iter().zip(pieces).enumerate().take(reachable)
    {
        // A qualifier or a secondary bound is an extra gate (not the dimension's own tiering), so
        // it makes a trailing catch-all read "otherwise" rather than "the remaining ...".
        let has_qualifier = !qualifiers.is_empty() || secondary.is_some();
        let primary_present = primary.is_some();
        let is_catch_all = primary.is_none() && secondary.is_none() && qualifiers.is_empty();

        let condition = if !is_catch_all {
            // The qualifiers lead, then the dimension's own bound, then the secondary bound.
            let mut parts = qualifiers;
            if let Some(primary) = primary {
                parts.push(primary);
            }
            if let Some(secondary) = secondary {
                parts.push(secondary);
            }
            Condition::When(parts)
        } else if index == 0 {
            Condition::Always
        } else if seen_bound && !seen_qualifier {
            Condition::Remaining
        } else {
            Condition::Otherwise
        };

        let free = is_free(band.price);
        let rate = if free {
            Rate::Free
        } else {
            Rate::Priced {
                amount: band.price,
                vat: band.vat,
            }
        };

        // A step of 1 (the smallest unit) is effectively continuous billing, and a free tier has
        // nothing to bill in steps, so neither earns a note. When the step is shared across tiers
        // it is described once for the dimension instead of inline here.
        let step = if uniform || band.step_size == 1 || free {
            None
        } else {
            Some(band.step_size)
        };

        seen_bound |= primary_present;
        seen_qualifier |= has_qualifier;
        tiers.push(Tier {
            condition,
            rate,
            step,
        });
    }

    Some(Dimension {
        kind: dimension,
        tiers,
        uniform_step,
        dropped_unreachable: dropped > 0,
    })
}

/// The consumption bound that matches the dimension: duration for charging/idle time, energy for
/// the energy dimension. This is the tier's natural "for the first N" bound.
fn primary_scope(restrictions: &Restrictions, dimension: DimensionType) -> Option<ConditionPart> {
    match dimension {
        DimensionType::Time | DimensionType::ParkingTime => {
            duration_scope(restrictions).map(ConditionPart::DurationScope)
        }
        DimensionType::Energy => energy_scope(restrictions).map(ConditionPart::EnergyScope),
        DimensionType::Flat => None,
    }
}

/// The consumption bound of the other kind than the dimension's own. The spec allows, for example,
/// an energy threshold on a charging-time tier; this surfaces it as an extra condition.
fn secondary_scope(restrictions: &Restrictions, dimension: DimensionType) -> Option<ConditionPart> {
    match dimension {
        DimensionType::Time | DimensionType::ParkingTime => {
            energy_scope(restrictions).map(ConditionPart::EnergyScope)
        }
        DimensionType::Energy => duration_scope(restrictions).map(ConditionPart::DurationScope),
        DimensionType::Flat => None,
    }
}

/// Classify the duration restrictions of a tier as a scope. These bounds are on how long the
/// session has lasted, not a time of day.
fn duration_scope(restrictions: &Restrictions) -> Option<Scope<chrono::TimeDelta>> {
    match (restrictions.min_duration, restrictions.max_duration) {
        (None, Some(max)) => Some(Scope::UpTo(max)),
        (Some(min), None) => Some(Scope::After(min)),
        (Some(min), Some(max)) => Some(Scope::Between(min, max)),
        (None, None) => None,
    }
}

/// Classify the energy restrictions of a tier as a scope, bounded by consumed kWh.
fn energy_scope(restrictions: &Restrictions) -> Option<Scope<crate::Kwh>> {
    match (restrictions.min_kwh, restrictions.max_kwh) {
        (None, Some(max)) => Some(Scope::UpTo(max)),
        (Some(min), None) => Some(Scope::After(min)),
        (Some(min), Some(max)) => Some(Scope::Between(min, max)),
        (None, None) => None,
    }
}

/// Collect the non-tiering restrictions (time of day, weekday, date, power, current) into condition
/// parts, in the order they should be listed.
fn qualifiers(restrictions: &Restrictions) -> Vec<ConditionPart> {
    let mut parts = Vec::new();

    match (restrictions.start_time, restrictions.end_time) {
        // Equal start and end times describe an empty window, so the element never applies. The
        // spec uses 00:00 for "end of day", which is the only case where equal times would not be
        // degenerate, but that is the wrapping branch below, not this one.
        (Some(start), Some(end)) if start == end => {
            parts.push(ConditionPart::TimeWindow(TimeWindow::Empty { start, end }));
        }
        // An end time earlier than the start time means the window wraps past midnight.
        (Some(start), Some(end)) if end < start => {
            parts.push(ConditionPart::TimeWindow(TimeWindow::Wrapping {
                start,
                end,
            }));
        }
        (Some(start), Some(end)) => {
            parts.push(ConditionPart::TimeWindow(TimeWindow::Between {
                start,
                end,
            }));
        }
        (Some(start), None) => parts.push(ConditionPart::TimeWindow(TimeWindow::From { start })),
        (None, Some(end)) => parts.push(ConditionPart::TimeWindow(TimeWindow::Before { end })),
        (None, None) => {}
    }

    if let Some(days) = restrictions.day_of_week.as_ref().filter(|d| !d.is_empty()) {
        parts.push(ConditionPart::Weekdays(days.clone()));
    }

    match (restrictions.start_date, restrictions.end_date) {
        (None, None) => {}
        (start, end) => parts.push(ConditionPart::DateRange { start, end }),
    }

    if let Some(min) = restrictions.min_power {
        parts.push(ConditionPart::MinPower(min));
    }
    if let Some(max) = restrictions.max_power {
        parts.push(ConditionPart::MaxPower(max));
    }
    if let Some(min) = restrictions.min_current {
        parts.push(ConditionPart::MinCurrent(min));
    }
    if let Some(max) = restrictions.max_current {
        parts.push(ConditionPart::MaxCurrent(max));
    }

    parts
}

/// Build the overall `min_price`/`max_price` bounds section, if either bound is present.
fn build_bounds(min_price: Option<Price>, max_price: Option<Price>) -> Option<Bounds> {
    if min_price.is_none() && max_price.is_none() {
        None
    } else {
        Some(Bounds {
            min: min_price,
            max: max_price,
        })
    }
}

/// Build the validity-window section from the tariff's own start/end instants.
fn build_validity(
    start_date_time: Option<DateTime<Utc>>,
    end_date_time: Option<DateTime<Utc>>,
) -> Option<Validity> {
    match (start_date_time, end_date_time) {
        (Some(start), Some(end)) => Some(Validity::Between { start, end }),
        (Some(start), None) => Some(Validity::From { start }),
        (None, Some(end)) => Some(Validity::Until { end }),
        (None, None) => None,
    }
}

/// Return true when a rate is exactly zero, so it can be narrated as "free".
fn is_free(money: Money) -> bool {
    Decimal::from(money) == Decimal::ZERO
}