Skip to main content

ocpi_tariffs/explain/
render.rs

1//! Render an [`Explanation`] into Markdown prose in a chosen [`Language`].
2//!
3//! [`build`](super::tariff::build) has already made every semantic decision, so this module only
4//! chooses words, number formatting and word order. The Markdown skeleton (bold labels, bulleted
5//! tier lists, paragraph spacing) is shared across languages because the supported languages are
6//! all Germanic and phrase these structures alike; only the vocabulary carried by the [`Language`]
7//! methods differs. To add a language, add a variant and fill in each method's match arm.
8
9use jiff::{SignedDuration, Timestamp, civil};
10use rust_decimal::Decimal;
11
12use crate::{
13    Ampere, Kw, Kwh, Money, Price, Weekday, currency, money::VatOrigin, number,
14    tariff::v2x::DimensionType,
15};
16
17use super::ir::{
18    Body, Bounds, Condition, ConditionPart, Dimension, Explanation, Fallback, Flat, FlatFee, Rate,
19    Scope, Section, TimeWindow, Validity,
20};
21
22/// A language an explanation can be rendered in. All supported languages are Germanic.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum Language {
25    /// English (`en-US`).
26    EnUS,
27
28    /// Dutch (`nl-NL`).
29    NlNl,
30}
31
32/// Render a built explanation as Markdown in the given language.
33pub(super) fn render(explanation: &Explanation, language: Language) -> String {
34    let currency = explanation.currency;
35
36    match &explanation.body {
37        Body::Fallback(reason) => language.fallback(reason),
38        Body::Sections(sections) => sections
39            .iter()
40            .map(|section| render_section(section, currency, language))
41            .collect::<Vec<_>>()
42            .join("\n\n"),
43    }
44}
45
46/// Render one top-level section as its own paragraph (or bulleted block).
47fn render_section(section: &Section, currency: currency::Code, language: Language) -> String {
48    match section {
49        Section::Dimension(dimension) => render_dimension(dimension, currency, language),
50        Section::Flat(flat) => render_flat(flat, currency, language),
51        Section::Bounds(bounds) => language.bounds(bounds, currency),
52        Section::Validity(validity) => language.validity(validity),
53    }
54}
55
56/// Render a metered dimension: a single tier reads as one line, several tiers as a bulleted list,
57/// followed by any shared billing-step note and unreachable-tier note.
58fn render_dimension(dimension: &Dimension, currency: currency::Code, language: Language) -> String {
59    let subject = language.dimension_subject(dimension.kind);
60
61    // Each tier becomes (condition, rate body). A per-tier billing-step note is folded onto the
62    // body; it is only ever present when the dimension has several tiers, so it never shows on the
63    // single-line form.
64    let entries: Vec<(String, String)> = dimension
65        .tiers
66        .iter()
67        .map(|tier| {
68            let condition = render_condition(&tier.condition, dimension.kind, language);
69            let body = language.rate_body(&tier.rate, dimension.kind, currency);
70            let step = tier
71                .step
72                .map(|step| language.inline_step_note(step, dimension.kind))
73                .unwrap_or_default();
74            (condition, format!("{body}{step}"))
75        })
76        .collect();
77
78    let section = render_tier_list(subject, &entries);
79
80    let section = match dimension.uniform_step {
81        Some(step) => format!(
82            "{section}\n\n_{}_",
83            language.dimension_step_note(step, dimension.kind)
84        ),
85        None => section,
86    };
87
88    let section = if dimension.dropped_unreachable {
89        format!("{section}\n\n_{}_", language.dropped_tiers_note())
90    } else {
91        section
92    };
93
94    if dimension.dropped_shadowed {
95        format!("{section}\n\n_{}_", language.shadowed_tiers_note())
96    } else {
97        section
98    }
99}
100
101/// Render the flat fee: a single tier reads as one line, several as a bulleted list.
102fn render_flat(flat: &Flat, currency: currency::Code, language: Language) -> String {
103    let label = language.flat_fee_label();
104
105    let entries: Vec<(String, String)> = flat
106        .tiers
107        .iter()
108        .map(|tier| {
109            let condition = render_condition(&tier.condition, DimensionType::Flat, language);
110            let fee = language.flat_fee_body(&tier.fee, currency);
111            (condition, fee)
112        })
113        .collect();
114
115    let section = render_tier_list(label, &entries);
116
117    if flat.dropped_shadowed {
118        format!("{section}\n\n_{}_", language.shadowed_tiers_note())
119    } else {
120        section
121    }
122}
123
124/// Render a labelled list of `(condition, body)` tiers as a Markdown section.
125///
126/// A single unconditional tier reads as `**Label:** body.`; a single conditional tier as
127/// `**Label:** condition, body.`; and several tiers as a bulleted list, one `- Condition: body` per
128/// tier. Shared by the metered dimensions and the flat fee so they lay out identically.
129fn render_tier_list(label: &str, entries: &[(String, String)]) -> String {
130    match entries {
131        [(condition, body)] if condition.is_empty() => format!("**{label}:** {body}."),
132        [(condition, body)] => format!("**{label}:** {condition}, {body}."),
133        _ => {
134            let bullets: Vec<String> = entries
135                .iter()
136                .map(|(condition, body)| format!("- {}: {body}", capitalize_first(condition)))
137                .collect();
138            format!("**{label}:**\n\n{}", bullets.join("\n"))
139        }
140    }
141}
142
143/// Render a tier's condition. `kind` is only used by the "remaining ..." catch-all, which names the
144/// dimension's own quantity.
145fn render_condition(condition: &Condition, kind: DimensionType, language: Language) -> String {
146    match condition {
147        Condition::Always => String::new(),
148        Condition::Otherwise => language.otherwise().to_owned(),
149        Condition::Remaining => language.remaining(kind),
150        Condition::When(parts) => parts
151            .iter()
152            .map(|part| language.condition_part(part))
153            .collect::<Vec<_>>()
154            .join(", "),
155    }
156}
157
158/// The Dutch article for an `eerste <duration>` phrase, as in "het eerste 1 uur" or "de
159/// eerste 3 uur". Dutch agrees the article with the number of the amount the ordinal modifies, so
160/// exactly one hour, minute or second takes `het` and every other amount takes `de`.
161fn dutch_duration_article(duration: SignedDuration) -> &'static str {
162    match duration.as_secs() {
163        1 | 60 | 3600 => "het",
164        _ => "de",
165    }
166}
167
168/// The Dutch article for an `eerste <energy>` phrase, which agrees with the amount the
169/// same way [`dutch_duration_article`] does.
170fn dutch_kwh_article(value: Kwh) -> &'static str {
171    if Decimal::from(value) == Decimal::ONE {
172        "het"
173    } else {
174        "de"
175    }
176}
177
178/// Capitalize the first character of a string, leaving the rest untouched.
179fn capitalize_first(text: &str) -> String {
180    let mut chars = text.chars();
181    match chars.next() {
182        Some(first) => format!("{}{}", first.to_uppercase(), chars.as_str()),
183        None => String::new(),
184    }
185}
186
187impl Language {
188    /// The sentence subject / label for a metered dimension, e.g. "Charging time".
189    fn dimension_subject(self, kind: DimensionType) -> &'static str {
190        match kind {
191            DimensionType::Energy => match self {
192                Language::EnUS => "Energy",
193                Language::NlNl => "Energietarief",
194            },
195            DimensionType::Time => match self {
196                Language::EnUS => "Charging time",
197                Language::NlNl => "Tarief tijdens het laden",
198            },
199            DimensionType::ParkingTime => match self {
200                Language::EnUS => "Idle time (connected but not charging)",
201                Language::NlNl => "Parkeertijd (aangesloten maar niet aan het laden)",
202            },
203            // The flat fee is not a metered dimension; it has its own label.
204            DimensionType::Flat => "",
205        }
206    }
207
208    /// The per-unit rate phrase for a metered dimension, e.g. "per hour".
209    fn dimension_unit(self, kind: DimensionType) -> &'static str {
210        match kind {
211            DimensionType::Energy => "per kWh",
212            DimensionType::Time | DimensionType::ParkingTime => match self {
213                Language::EnUS => "per hour",
214                Language::NlNl => "per uur",
215            },
216            DimensionType::Flat => "",
217        }
218    }
219
220    /// The catch-all phrase naming the dimension's own remaining quantity, e.g. "for the remaining
221    /// charging time".
222    fn remaining(self, kind: DimensionType) -> String {
223        let phrase = match kind {
224            DimensionType::Energy => match self {
225                Language::EnUS => "for the remaining energy",
226                Language::NlNl => "de resterende energie",
227            },
228            DimensionType::Time => match self {
229                Language::EnUS => "for the remaining charging time",
230                Language::NlNl => "de resterende laadtijd",
231            },
232            DimensionType::ParkingTime => match self {
233                Language::EnUS => "for the remaining idle time",
234                Language::NlNl => "de resterende parkeertijd",
235            },
236            DimensionType::Flat => "",
237        };
238        phrase.to_owned()
239    }
240
241    /// The catch-all word used when an earlier tier was gated by a non-consumption qualifier.
242    fn otherwise(self) -> &'static str {
243        match self {
244            Language::EnUS => "otherwise",
245            Language::NlNl => "anders",
246        }
247    }
248
249    /// The label for the flat-fee section.
250    fn flat_fee_label(self) -> &'static str {
251        match self {
252            Language::EnUS => "Flat fee",
253            Language::NlNl => "Vast tarief",
254        }
255    }
256
257    /// The rate body of a metered tier: "free" or an amount with its per-unit phrase and VAT.
258    fn rate_body(self, rate: &Rate, kind: DimensionType, currency: currency::Code) -> String {
259        match rate {
260            Rate::Free => match self {
261                Language::EnUS => "free".to_owned(),
262                Language::NlNl => "gratis".to_owned(),
263            },
264            Rate::Priced { amount, vat } => format!(
265                "{} {}{}",
266                self.money(*amount, currency, Amount::Rate),
267                self.dimension_unit(kind),
268                self.vat_clause(*vat)
269            ),
270        }
271    }
272
273    /// The fee body of a flat tier: "no fee" or an amount charged per session, with VAT.
274    fn flat_fee_body(self, fee: &FlatFee, currency: currency::Code) -> String {
275        match fee {
276            FlatFee::NoFee => match self {
277                Language::EnUS => "no fee".to_owned(),
278                Language::NlNl => "geen kosten".to_owned(),
279            },
280            FlatFee::Charged { amount, vat } => {
281                let per_session = match self {
282                    Language::EnUS => "per session",
283                    Language::NlNl => "per sessie",
284                };
285                format!(
286                    "{} {per_session}{}",
287                    self.money(*amount, currency, Amount::Charge),
288                    self.vat_clause(*vat)
289                )
290            }
291        }
292    }
293
294    /// Render one clause of a tier's condition as a lowercase phrase.
295    fn condition_part(self, part: &ConditionPart) -> String {
296        match part {
297            ConditionPart::TimeWindow(window) => self.time_window(window),
298            ConditionPart::Weekdays(days) => {
299                let names: Vec<&str> = days.iter().copied().map(|day| self.weekday(day)).collect();
300                let on = match self {
301                    Language::EnUS => "on",
302                    Language::NlNl => "op",
303                };
304                format!("{on} {}", names.join(", "))
305            }
306            ConditionPart::DateRange { start, end } => self.date_range(*start, *end),
307            ConditionPart::MinPower(power) => match self {
308                Language::EnUS => format!("while charging at {} or more", self.kw(*power)),
309                Language::NlNl => format!("bij laadsnelheid van {} of meer", self.kw(*power)),
310            },
311            ConditionPart::MaxPower(power) => match self {
312                Language::EnUS => format!("while charging below {}", self.kw(*power)),
313                Language::NlNl => format!("bij laadsnelheid onder {}", self.kw(*power)),
314            },
315            ConditionPart::MinCurrent(current) => match self {
316                Language::EnUS => format!("at {} or more", self.ampere(*current)),
317                Language::NlNl => format!("bij {} of meer", self.ampere(*current)),
318            },
319            ConditionPart::MaxCurrent(current) => match self {
320                Language::EnUS => format!("below {}", self.ampere(*current)),
321                Language::NlNl => format!("onder {}", self.ampere(*current)),
322            },
323            ConditionPart::DurationScope(scope) => self.duration_scope(scope),
324            ConditionPart::EnergyScope(scope) => self.energy_scope(scope),
325        }
326    }
327
328    /// Render a time-of-day window clause.
329    fn time_window(self, window: &TimeWindow) -> String {
330        match (self, window) {
331            (Language::EnUS, TimeWindow::Empty { at }) => {
332                format!(
333                    "never applies (its window {} to {} is empty)",
334                    hm(*at),
335                    hm(*at)
336                )
337            }
338            (
339                Language::EnUS,
340                TimeWindow::Wrapping { start, end } | TimeWindow::Between { start, end },
341            ) => {
342                format!("between {} and {}", hm(*start), hm(*end))
343            }
344            (Language::EnUS, TimeWindow::From { start }) => {
345                format!("from {} onwards", hm(*start))
346            }
347            (Language::EnUS, TimeWindow::Before { end }) => format!("before {}", hm(*end)),
348            (Language::NlNl, TimeWindow::Empty { at }) => {
349                format!(
350                    "geldt nooit (het venster {} tot {} is leeg)",
351                    hm(*at),
352                    hm(*at)
353                )
354            }
355            (
356                Language::NlNl,
357                TimeWindow::Wrapping { start, end } | TimeWindow::Between { start, end },
358            ) => {
359                format!("tussen {} en {}", hm(*start), hm(*end))
360            }
361            (Language::NlNl, TimeWindow::From { start }) => format!("vanaf {}", hm(*start)),
362            (Language::NlNl, TimeWindow::Before { end }) => format!("voor {}", hm(*end)),
363        }
364    }
365
366    /// Render a calendar-date range clause. At least one of `start`/`end` is present.
367    fn date_range(self, start: Option<civil::Date>, end: Option<civil::Date>) -> String {
368        match (start, end) {
369            (Some(start), Some(end)) => match self {
370                Language::EnUS => format!("from {} until {}", date(start), date(end)),
371                Language::NlNl => format!("van {} tot {}", date(start), date(end)),
372            },
373            (Some(start), None) => match self {
374                Language::EnUS => format!("from {} onwards", date(start)),
375                Language::NlNl => format!("vanaf {}", date(start)),
376            },
377            (None, Some(end)) => match self {
378                Language::EnUS => format!("until {}", date(end)),
379                Language::NlNl => format!("tot {}", date(end)),
380            },
381            // Never built with both ends absent.
382            (None, None) => String::new(),
383        }
384    }
385
386    /// Render an elapsed-session-duration scope clause.
387    ///
388    /// Every arm anchors the bound to the start of the session, because that is what the bound is
389    /// measured against: a `min_duration`/`max_duration` restriction is compared against how long
390    /// the whole session has lasted. Under an "idle time" or "charging time" heading, a bare "the
391    /// first 15 minutes" would instead read as 15 minutes of that dimension.
392    ///
393    /// The anchor is worded as plugging in rather than as the session, which a driver reading the
394    /// explanation need not know the meaning of. The two coincide except for a session preceded by
395    /// a reservation, which OCPI dates from the start of the reservation
396    /// (`specs/v221/mod_cdrs.asciidoc:327`).
397    fn duration_scope(self, scope: &Scope<SignedDuration>) -> String {
398        match (self, scope) {
399            (Language::EnUS, Scope::UpTo(max)) => {
400                format!("for the first {} after plugging in", self.duration(*max))
401            }
402            (Language::EnUS, Scope::After(min)) => {
403                format!("more than {} after plugging in", self.duration(*min))
404            }
405            (Language::EnUS, Scope::Between(min, max)) => format!(
406                "between {} and {} after plugging in",
407                self.duration(*min),
408                self.duration(*max)
409            ),
410            (Language::NlNl, Scope::UpTo(max)) => format!(
411                "{} eerste {} na het aansluiten",
412                dutch_duration_article(*max),
413                self.duration(*max)
414            ),
415            (Language::NlNl, Scope::After(min)) => {
416                format!("meer dan {} na het aansluiten", self.duration(*min))
417            }
418            (Language::NlNl, Scope::Between(min, max)) => format!(
419                "tussen {} en {} na het aansluiten",
420                self.duration(*min),
421                self.duration(*max)
422            ),
423        }
424    }
425
426    /// Render a consumed-energy scope clause.
427    fn energy_scope(self, scope: &Scope<Kwh>) -> String {
428        match (self, scope) {
429            (Language::EnUS, Scope::UpTo(max)) => format!("for the first {}", self.kwh(*max)),
430            (Language::EnUS, Scope::After(min)) => format!("after the first {}", self.kwh(*min)),
431            (Language::EnUS, Scope::Between(min, max)) => {
432                format!("from {} to {}", self.kwh(*min), self.kwh(*max))
433            }
434            (Language::NlNl, Scope::UpTo(max)) => {
435                format!("{} eerste {}", dutch_kwh_article(*max), self.kwh(*max))
436            }
437            (Language::NlNl, Scope::After(min)) => {
438                format!("na {} eerste {}", dutch_kwh_article(*min), self.kwh(*min))
439            }
440            (Language::NlNl, Scope::Between(min, max)) => {
441                format!("van {} tot {}", self.kwh(*min), self.kwh(*max))
442            }
443        }
444    }
445
446    /// The overall `min_price`/`max_price` bounds, as one or two sentences.
447    fn bounds(self, bounds: &Bounds, currency: currency::Code) -> String {
448        let mut sentences = Vec::new();
449
450        if let Some(min) = bounds.min {
451            sentences.push(match self {
452                Language::EnUS => {
453                    format!(
454                        "A session always costs at least {}.",
455                        self.price(min, currency)
456                    )
457                }
458                Language::NlNl => {
459                    format!(
460                        "Een sessie kost altijd minstens {}.",
461                        self.price(min, currency)
462                    )
463                }
464            });
465        }
466        if let Some(max) = bounds.max {
467            sentences.push(match self {
468                Language::EnUS => {
469                    format!(
470                        "A session never costs more than {}.",
471                        self.price(max, currency)
472                    )
473                }
474                Language::NlNl => {
475                    format!(
476                        "Een sessie kost nooit meer dan {}.",
477                        self.price(max, currency)
478                    )
479                }
480            });
481        }
482
483        sentences.join(" ")
484    }
485
486    /// The validity window of the tariff itself.
487    fn validity(self, validity: &Validity) -> String {
488        match (self, validity) {
489            (Language::EnUS, Validity::Between { start, end }) => format!(
490                "This tariff is only valid from {} until {} (UTC).",
491                datetime(*start),
492                datetime(*end)
493            ),
494            (Language::EnUS, Validity::From { start }) => format!(
495                "This tariff only becomes active on {} (UTC).",
496                datetime(*start)
497            ),
498            (Language::EnUS, Validity::Until { end }) => format!(
499                "This tariff is no longer valid from {} (UTC).",
500                datetime(*end)
501            ),
502            (Language::NlNl, Validity::Between { start, end }) => format!(
503                "Dit tarief is alleen geldig van {} tot {} (UTC).",
504                datetime(*start),
505                datetime(*end)
506            ),
507            (Language::NlNl, Validity::From { start }) => {
508                format!("Dit tarief wordt pas actief op {} (UTC).", datetime(*start))
509            }
510            (Language::NlNl, Validity::Until { end }) => {
511                format!(
512                    "Dit tarief is niet langer geldig vanaf {} (UTC).",
513                    datetime(*end)
514                )
515            }
516        }
517    }
518
519    /// The reason a tariff produces no charging narrative.
520    fn fallback(self, reason: &Fallback) -> String {
521        match (self, reason) {
522            (Language::EnUS, Fallback::ReservationOnly) => {
523                "This tariff never charges a regular charging session: every element applies only \
524                 to reservation sessions."
525                    .to_owned()
526            }
527            (Language::EnUS, Fallback::NoPriceComponents) => {
528                "This tariff charges nothing: none of its applicable elements define a price \
529                 component."
530                    .to_owned()
531            }
532            (Language::EnUS, Fallback::FreeFlatOnly) => {
533                "This tariff is free: its only charge is a flat fee of zero.".to_owned()
534            }
535            (Language::NlNl, Fallback::ReservationOnly) => {
536                "Dit tarief brengt nooit kosten in rekening voor een gewone laadsessie: elk element \
537                 geldt alleen voor reserveringssessies."
538                    .to_owned()
539            }
540            (Language::NlNl, Fallback::NoPriceComponents) => {
541                "Dit tarief brengt niets in rekening: geen van de toepasselijke elementen \
542                 definieert een prijscomponent."
543                    .to_owned()
544            }
545            (Language::NlNl, Fallback::FreeFlatOnly) => {
546                "Dit tarief is gratis: er zijn geen kosten.".to_owned()
547            }
548        }
549    }
550
551    /// The note describing a billing step shared by every tier of a dimension (without the
552    /// surrounding italics).
553    fn dimension_step_note(self, step_size: u64, kind: DimensionType) -> String {
554        let magnitude = self.step_magnitude(step_size, kind);
555        match self {
556            Language::EnUS => format!("Billed in steps of {magnitude}, rounded up."),
557            Language::NlNl => format!("Berekend in stappen van {magnitude}, naar boven afgerond."),
558        }
559    }
560
561    /// The inline note describing a single tier's own billing step, as a trailing clause.
562    fn inline_step_note(self, step_size: u64, kind: DimensionType) -> String {
563        let magnitude = self.step_magnitude(step_size, kind);
564        match self {
565            Language::EnUS => format!(" (billed in steps of {magnitude}, rounded up)"),
566            Language::NlNl => {
567                format!(" (berekend in stappen van {magnitude}, naar boven afgerond)")
568            }
569        }
570    }
571
572    /// The note that unreachable tiers were dropped (without the surrounding italics).
573    fn dropped_tiers_note(self) -> &'static str {
574        match self {
575            Language::EnUS => {
576                "Any later tiers never apply, because an earlier rate already matches every session."
577            }
578            Language::NlNl => {
579                "Latere niveaus gelden nooit, omdat een eerder tarief al op elke sessie van toepassing is."
580            }
581        }
582    }
583
584    /// Add a note dropping shadowed tiers. Where a previous tier's date range already covered the current tiers range.
585    fn shadowed_tiers_note(self) -> &'static str {
586        match self {
587            Language::EnUS => {
588                "Tiers that never apply are not listed, because an earlier rate already covers the same dates."
589            }
590            Language::NlNl => {
591                "Niveaus die nooit gelden zijn niet vermeld, omdat een eerder tarief dezelfde periode al dekt."
592            }
593        }
594    }
595
596    /// The magnitude of a billing step in the unit appropriate to the dimension, e.g. "0.1 kWh" or
597    /// "1 minute".
598    ///
599    /// The energy `step_size` is given in Wh by the spec, but it is shown in kWh because readers
600    /// expect energy in kWh and tend to read "Wh" as a typo. Time steps are humanized (60 -> "1
601    /// minute", 900 -> "15 minutes") rather than shown as a raw second count.
602    fn step_magnitude(self, step_size: u64, kind: DimensionType) -> String {
603        match kind {
604            DimensionType::Energy => {
605                let kwh = Kwh::from_watt_hours(Decimal::from(step_size));
606                format!("{} kWh", self.decimal(Decimal::from(kwh).normalize()))
607            }
608            DimensionType::Time | DimensionType::ParkingTime => {
609                self.duration_seconds(i64::try_from(step_size).unwrap_or(i64::MAX))
610            }
611            DimensionType::Flat => String::new(),
612        }
613    }
614
615    /// Format a `Money` amount with its currency symbol, to the precision its [`Amount`] warrants.
616    fn money(self, money: Money, currency: currency::Code, amount: Amount) -> String {
617        let value = Decimal::from(money);
618
619        let symbol =
620            if let currency::Code::Eur | currency::Code::Gbp | currency::Code::Usd = currency {
621                currency.into_symbol()
622            } else {
623                currency.into_str()
624            };
625
626        // Print the value as given when two decimals cannot state it, and reduce it to two
627        // otherwise. Reducing to `number::SCALE` first would understate a value carrying more
628        // decimals than the scale, so the exact branch formats the value itself.
629        let rounded = value.round_dp_with_strategy(2, number::ROUNDING_STRATEGY);
630        let exact = match amount {
631            Amount::Rate => rounded != value,
632            Amount::Charge => rounded == Decimal::ZERO && value != Decimal::ZERO,
633        };
634
635        let digits = if exact {
636            self.decimal(value.normalize())
637        } else {
638            self.decimal_fixed(value)
639        };
640
641        match self {
642            Language::EnUS => format!("{symbol}{digits}"),
643            Language::NlNl => format!("{symbol} {digits}"),
644        }
645    }
646
647    /// Format a `Price` (which may carry a VAT-inclusive value) with its currency symbol.
648    ///
649    /// A `Price` only ever reaches here as a `min_price`/`max_price` bound, which is a sum
650    /// a session is billed rather than a rate, so both halves render as [`Amount::Charge`].
651    fn price(self, price: Price, currency: currency::Code) -> String {
652        let incl_vat = match self {
653            Language::EnUS => "incl. VAT",
654            Language::NlNl => "incl. btw",
655        };
656        match price.incl_vat {
657            Some(incl) => format!(
658                "{} ({} {incl_vat})",
659                self.money(price.excl_vat, currency, Amount::Charge),
660                self.money(incl, currency, Amount::Charge)
661            ),
662            None => self.money(price.excl_vat, currency, Amount::Charge),
663        }
664    }
665
666    /// A trailing clause describing the VAT applied to a rate, or an empty string when none applies.
667    fn vat_clause(self, vat: VatOrigin) -> String {
668        match vat {
669            // `v2.1.1` tariffs carry no VAT information, so saying nothing is the honest choice.
670            VatOrigin::Unknown | VatOrigin::NotProvided => String::new(),
671            VatOrigin::Provided(vat) => {
672                let percent = self.decimal(Decimal::from(vat).normalize());
673                match self {
674                    Language::EnUS => format!(" (excl. {percent} VAT)"),
675                    Language::NlNl => format!(" (excl. {percent} btw)"),
676                }
677            }
678        }
679    }
680
681    /// Format a `Kwh` value without trailing zeros, e.g. "20 kWh".
682    fn kwh(self, value: Kwh) -> String {
683        format!("{} kWh", self.decimal(Decimal::from(value).normalize()))
684    }
685
686    /// Format a `Kw` value without trailing zeros, e.g. "11 kW".
687    fn kw(self, value: Kw) -> String {
688        format!("{} kW", self.decimal(Decimal::from(value).normalize()))
689    }
690
691    /// Format an `Ampere` value without trailing zeros, e.g. "16 A".
692    fn ampere(self, value: Ampere) -> String {
693        format!("{} A", self.decimal(Decimal::from(value).normalize()))
694    }
695
696    /// Render a duration as a friendly phrase such as "3 hours" or "1 hour 30 minutes".
697    fn duration(self, duration: SignedDuration) -> String {
698        self.duration_seconds(duration.as_secs().max(0))
699    }
700
701    /// Render a whole number of seconds as a friendly phrase such as "3 hours" or "1 minute".
702    fn duration_seconds(self, total_seconds: i64) -> String {
703        let total_seconds = total_seconds.max(0);
704        let hours = total_seconds / 3600;
705        let minutes = (total_seconds % 3600) / 60;
706        let seconds = total_seconds % 60;
707
708        let mut parts = Vec::new();
709
710        if hours > 0 {
711            parts.push(self.time_unit(hours, TimeUnit::Hour));
712        }
713        if minutes > 0 {
714            parts.push(self.time_unit(minutes, TimeUnit::Minute));
715        }
716        if seconds > 0 {
717            parts.push(self.time_unit(seconds, TimeUnit::Second));
718        }
719
720        if parts.is_empty() {
721            self.time_unit(0, TimeUnit::Second)
722        } else {
723            parts.join(" ")
724        }
725    }
726
727    /// Format a count with a singular/plural time unit, e.g. "1 hour" / "3 hours".
728    fn time_unit(self, count: i64, unit: TimeUnit) -> String {
729        let noun = match (self, unit) {
730            (Language::EnUS, TimeUnit::Hour) if count == 1 => "hour",
731            (Language::EnUS, TimeUnit::Hour) => "hours",
732            (Language::EnUS, TimeUnit::Minute) if count == 1 => "minute",
733            (Language::EnUS, TimeUnit::Minute) => "minutes",
734            (Language::EnUS, TimeUnit::Second) if count == 1 => "second",
735            (Language::EnUS, TimeUnit::Second) => "seconds",
736            // Dutch "uur" does not inflect for number: "1 uur", "2 uur".
737            (Language::NlNl, TimeUnit::Hour) => "uur",
738            (Language::NlNl, TimeUnit::Minute) if count == 1 => "minuut",
739            (Language::NlNl, TimeUnit::Minute) => "minuten",
740            (Language::NlNl, TimeUnit::Second) if count == 1 => "seconde",
741            (Language::NlNl, TimeUnit::Second) => "seconden",
742        };
743        format!("{count} {noun}")
744    }
745
746    /// The English name of a weekday; Dutch names are lowercase, as Dutch does not capitalize them.
747    fn weekday(self, day: Weekday) -> &'static str {
748        match (self, day) {
749            (Language::EnUS, Weekday::Monday) => "Monday",
750            (Language::EnUS, Weekday::Tuesday) => "Tuesday",
751            (Language::EnUS, Weekday::Wednesday) => "Wednesday",
752            (Language::EnUS, Weekday::Thursday) => "Thursday",
753            (Language::EnUS, Weekday::Friday) => "Friday",
754            (Language::EnUS, Weekday::Saturday) => "Saturday",
755            (Language::EnUS, Weekday::Sunday) => "Sunday",
756            (Language::NlNl, Weekday::Monday) => "maandag",
757            (Language::NlNl, Weekday::Tuesday) => "dinsdag",
758            (Language::NlNl, Weekday::Wednesday) => "woensdag",
759            (Language::NlNl, Weekday::Thursday) => "donderdag",
760            (Language::NlNl, Weekday::Friday) => "vrijdag",
761            (Language::NlNl, Weekday::Saturday) => "zaterdag",
762            (Language::NlNl, Weekday::Sunday) => "zondag",
763        }
764    }
765
766    /// Render a normalized decimal, using the language's decimal separator.
767    fn decimal(self, value: Decimal) -> String {
768        let text = value.to_string();
769        match self {
770            Language::EnUS => text,
771            Language::NlNl => text.replace('.', ","),
772        }
773    }
774
775    /// Render a decimal fixed to two places, using the language's decimal separator.
776    fn decimal_fixed(self, value: Decimal) -> String {
777        // `{:.2}` truncates rather than rounds, which understates a rate: a price of
778        // `0.2083` reads as "0.20". Round with the strategy stated at `number::SCALE`, so two
779        // places here resolve a tie the same way four places do elsewhere.
780        let value = value.round_dp_with_strategy(2, number::ROUNDING_STRATEGY);
781        let text = format!("{value:.2}");
782        match self {
783            Language::EnUS => text,
784            Language::NlNl => text.replace('.', ","),
785        }
786    }
787}
788
789/// What an amount stands for, which decides how many decimals it is printed with.
790///
791/// A rate and a charge are both money, but a reader does different things with them, so they are
792/// not written alike.
793#[derive(Clone, Copy)]
794enum Amount {
795    /// A unit rate, per kWh or per hour.
796    ///
797    /// A rate is a multiplier rather than a payment, so it is printed at its own precision.
798    /// Nobody hands over a tenth of a cent, but `0.4167` per kWh written as `0.42` states a
799    /// deal 0.79% away from the one the session is billed under, and a rate is what a reader
800    /// compares between tariffs and checks a bill against.
801    Rate,
802
803    /// A sum a session is billed: a flat fee, or a `min_price`/`max_price` bound.
804    ///
805    /// Printed to two decimals, because that is what can be paid. A once-off fee of `0.165` is
806    /// half a cent no one can hand over, and writing it in full states a payment that cannot be
807    /// made. Sub-cent precision on a charge is a fault in the tariff, not something to render
808    /// faithfully. A nonzero charge too small to survive two decimals is still printed as given,
809    /// so it cannot read as free.
810    Charge,
811}
812
813/// A unit of elapsed time, used to select the right singular/plural noun.
814#[derive(Clone, Copy)]
815enum TimeUnit {
816    Hour,
817    Minute,
818    Second,
819}
820
821/// Format a time of day as `HH:MM`. Shared across languages.
822fn hm(time: civil::Time) -> String {
823    time.strftime("%H:%M").to_string()
824}
825
826/// Format a date as an ISO `YYYY-MM-DD` date. Shared across languages for to mitigate ambiguity.
827fn date(value: civil::Date) -> String {
828    value.to_string()
829}
830
831/// Format a UTC instant as `YYYY-MM-DD HH:MM`. Shared across languages.
832fn datetime(value: Timestamp) -> String {
833    value.strftime("%Y-%m-%d %H:%M").to_string()
834}