Skip to main content

ocpi_tariffs/
money.rs

1//! Various monetary types.
2
3#[cfg(test)]
4mod test;
5
6#[cfg(test)]
7mod test_from_schema;
8
9use std::fmt;
10
11use rust_decimal::Decimal;
12use rust_decimal_macros::dec;
13
14use crate::{
15    FromSchema as _, LowerSchema, SaturatingAdd as _, currency, from_warning_all, impl_dec_newtype,
16    number::{self, FromDecimal as _, IsZero, RoundDecimal, approx_eq_dec},
17    schema::{self, HasElement as _},
18    warning,
19};
20
21/// An item that has a cost.
22pub trait Cost: Copy {
23    /// The cost of this dimension at a certain price.
24    fn cost(&self, money: Money) -> Money;
25}
26
27impl Cost for () {
28    fn cost(&self, money: Money) -> Money {
29        money
30    }
31}
32
33/// The warnings that can happen when parsing or linting a `Price`.
34#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
35pub enum Warning {
36    /// The `excl_vat` and `incl_vat` fields imply a VAT rate less than `0`.
37    ///
38    /// The two values imply a rate, and `Price::vat_is_consistent` says which pairs imply a
39    /// rate less than `0`. The same bound covers a rate stated by a tariff, reported as
40    /// `Warning::NegativeVat`.
41    ImpliedVatIsNegative,
42
43    /// The `vat` field states a rate less than `0`.
44    ///
45    /// A rate less than `0` is not VAT. `Price::vat_is_consistent` reads a pair as though no such
46    /// rate exists, since that rule holds only while `1 + vat/100` is a multiplier greater than or
47    /// equal to `1`. This warning reports the rate rather than refusing it, so the component is
48    /// still priced at the stated rate. OCPI doesn't bound the `vat` field of the `PriceComponent`
49    /// class
50    /// (<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_pricecomponent_class>),
51    /// so the bound is this library's rather than the spec's.
52    NegativeVat,
53
54    /// A number this module lowered is not valid: `excl_vat`, `incl_vat` or `vat`.
55    Number(number::Warning),
56
57    /// A feature rejected the schema IR for a `Price` because a required field was missing or
58    /// invalid. The located cause is reported by the schema validation warnings; this is a
59    /// content-free marker (see [`warning::Rejected`]).
60    Rejected,
61}
62
63impl fmt::Display for Warning {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        match self {
66            Self::ImpliedVatIsNegative => write!(
67                f,
68                "The `excl_vat` and `incl_vat` fields imply a VAT rate less than `0`"
69            ),
70            Self::NegativeVat => {
71                write!(
72                    f,
73                    "The `vat` field states a rate less than `0`, which is not VAT"
74                )
75            }
76            Self::Number(kind) => fmt::Display::fmt(kind, f),
77            Self::Rejected => f.write_str(
78                "The schema IR for a `Price` was rejected; see the schema validation warnings.",
79            ),
80        }
81    }
82}
83
84impl crate::Warning for Warning {
85    fn id(&self) -> warning::Id {
86        match self {
87            Self::ImpliedVatIsNegative => warning::Id::from_static("implied_vat_is_negative"),
88            Self::NegativeVat => warning::Id::from_static("negative_vat"),
89            Self::Number(kind) => kind.id(),
90            Self::Rejected => warning::Id::from_static("rejected"),
91        }
92    }
93
94    fn is_rejected(&self) -> bool {
95        matches!(self, Self::Rejected)
96    }
97}
98
99impl From<warning::Rejected> for Warning {
100    fn from(_: warning::Rejected) -> Self {
101        Self::Rejected
102    }
103}
104
105from_warning_all!(number::Warning => Warning::Number);
106
107/// A price consisting of a value including VAT, and a value excluding VAT.
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109#[cfg_attr(test, derive(serde::Deserialize))]
110pub struct Price {
111    /// The price excluding VAT.
112    pub excl_vat: Money,
113
114    /// The price including VAT.
115    ///
116    /// If no vat is applicable this value will be equal to the `excl_vat`.
117    ///
118    /// If no vat could be determined this value will be `None`.
119    /// The v211 tariffs can't determine VAT.
120    #[cfg_attr(test, serde(default))]
121    pub incl_vat: Option<Money>,
122}
123
124impl RoundDecimal for Price {
125    fn round_to_ocpi_scale(self) -> Self {
126        let Self { excl_vat, incl_vat } = self;
127        Self {
128            excl_vat: excl_vat.round_to_ocpi_scale(),
129            incl_vat: incl_vat.round_to_ocpi_scale(),
130        }
131    }
132}
133
134impl fmt::Display for Price {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        if let Some(incl_vat) = self.incl_vat {
137            if f.alternate() {
138                write!(f, "{{ -vat: {:#}, +vat: {:#} }}", self.excl_vat, incl_vat)
139            } else {
140                write!(f, "{{ -vat: {}, +vat: {} }}", self.excl_vat, incl_vat)
141            }
142        } else {
143            fmt::Display::fmt(&self.excl_vat, f)
144        }
145    }
146}
147
148impl<'buf> LowerSchema<'buf, schema::v221::Price<'buf>> for Price {
149    type Warning = Warning;
150
151    fn lower_schema(
152        source: &schema::v221::Price<'buf>,
153        warnings: &mut dyn warning::Gather<Warning>,
154    ) -> Result<Self, warning::Error<Warning>> {
155        // A bare-number price (the 2.1.1 shape) is just `excl_vat`: there is no `incl_vat`
156        // and thus no excl-vs-incl comparison to make.
157        let (elem, excl_vat, incl_vat) = match source {
158            schema::v221::Price::Number(number) => {
159                let excl_vat = Money::from_schema(number, warnings)?;
160                let price = Self {
161                    excl_vat,
162                    incl_vat: None,
163                };
164                return Ok(price);
165            }
166            schema::v221::Price::Object {
167                elem,
168                excl_vat,
169                incl_vat,
170            } => (elem, excl_vat, incl_vat),
171        };
172
173        // `excl_vat` is required, because a `Price` can't be built without a usable
174        // value. The schema walk has already reported a missing or wrong-kind field, so the
175        // rejection here is the content-free `Rejected` signal.
176        let excl_vat = warnings.ok_or_reject(excl_vat)?;
177        let excl_vat = Money::from_schema(excl_vat, warnings)?;
178
179        // `incl_vat` is optional, so an absent or `null` value leaves the price without
180        // VAT info. The schema walk has already reported a wrong-kind value, and
181        // `Price::lower_schema` treats it as no VAT rather than failing the whole price.
182        let incl_vat = match incl_vat {
183            schema::Integrity::Ok(Some(incl_vat)) => {
184                let incl_vat = Money::from_schema(incl_vat, warnings)?;
185                Some(incl_vat)
186            }
187            schema::Integrity::Ok(None)
188            | schema::Integrity::Missing(_)
189            | schema::Integrity::Err(_) => None,
190        };
191
192        let price = Self { excl_vat, incl_vat };
193
194        if !price.vat_is_consistent() {
195            warnings.insert(elem, Warning::ImpliedVatIsNegative);
196        }
197
198        Ok(price)
199    }
200}
201
202impl IsZero for Price {
203    fn is_zero(&self) -> bool {
204        self.excl_vat.is_zero() && self.incl_vat.is_none_or(|v| v.is_zero())
205    }
206}
207
208impl Price {
209    /// A `Price` of zero, with a zero `incl_vat` rather than an absent one.
210    pub fn zero() -> Self {
211        Self {
212            excl_vat: Money::zero(),
213            incl_vat: Some(Money::zero()),
214        }
215    }
216
217    /// Negate both amounts, which is how a Credit CDR states the `total_cost` of the CDR it credits.
218    #[must_use]
219    pub(crate) fn negate(self) -> Self {
220        Self {
221            excl_vat: Money(self.excl_vat.0.saturating_mul(Decimal::NEGATIVE_ONE)),
222            incl_vat: self
223                .incl_vat
224                .map(|incl_vat| Money(incl_vat.0.saturating_mul(Decimal::NEGATIVE_ONE))),
225        }
226    }
227
228    /// Saturating addition.
229    #[must_use]
230    pub(crate) fn saturating_add(self, rhs: Self) -> Self {
231        let incl_vat = self
232            .incl_vat
233            .zip(rhs.incl_vat)
234            .map(|(lhs, rhs)| lhs.saturating_add(rhs));
235
236        Self {
237            excl_vat: self.excl_vat.saturating_add(rhs.excl_vat),
238            incl_vat,
239        }
240    }
241
242    /// True when the two values imply a VAT rate greater than or equal to `0`.
243    ///
244    /// `incl_vat` divided by `excl_vat` is the multiplier that produced one from the other, and
245    /// that multiplier is `1 + vat/100`. A rate greater than or equal to `0` puts the
246    /// multiplier greater than or equal to `1`, which grows a magnitude and leaves a sign alone.
247    ///
248    /// Read back from a pair, the implied rate is less than `0` in two shapes and no others. Values
249    /// with different signs give a negative multiplier. Values sharing a sign, with
250    /// `incl_vat` the smaller in magnitude, give a multiplier between `0` and `1`. Those are one
251    /// fault rather than two, and the same bound covers a rate stated by a tariff.
252    ///
253    /// An `excl_vat` of `0` implies no rate at all, because no multiplier turns `0` into a
254    /// non-zero `incl_vat`. Such a pair is accepted rather than reported, which is a gap in the
255    /// rule rather than a case it decides.
256    ///
257    /// Stating the rule as `excl_vat` less than or equal to `incl_vat` describes the implication
258    /// for a non-negative amount only. `specs/v221/mod_cdrs.asciidoc:39` says only a Credit CDR's
259    /// `total_cost` contains the negative amounts, and both of its values are negative, so the
260    /// larger in magnitude is the more negative and the ordering reverses.
261    ///
262    /// A `Price` stating no `incl_vat` implies nothing.
263    pub(crate) fn vat_is_consistent(self) -> bool {
264        let Some(incl_vat) = self.incl_vat else {
265            return true;
266        };
267
268        let excl = Decimal::from(self.excl_vat);
269        let incl = Decimal::from(incl_vat);
270
271        excl.is_sign_negative() == incl.is_sign_negative() && incl.abs() >= excl.abs()
272    }
273
274    /// True when `excl_vat` is above `other`'s `excl_vat`, or `incl_vat` is above `other`'s
275    /// `incl_vat`.
276    ///
277    /// OCPI states `min_price` and `max_price` as two independent rules, one per value, and both
278    /// apply (`specs/v221/mod_tariffs.asciidoc:295-303`). A `min_price` above a `max_price` on
279    /// either value is therefore a pair no total satisfies. An `incl_vat` absent on either side
280    /// drops the inclusive comparison, because a bound that omits the value constrains it in no
281    /// way.
282    ///
283    /// Comparing each value with the matching value is enough for a bound that is not
284    /// negative. Such a `Price` has `excl_vat` less than or equal to its own `incl_vat`, so a
285    /// `min_price` whose `excl_vat` is greater than the `max_price`'s `incl_vat` is greater than
286    /// its `excl_vat` too, and the `excl_vat` comparison catches the pair. Parsing a `Price` that
287    /// fails `vat_is_consistent` reports `Warning::ImpliedVatIsNegative`.
288    ///
289    /// A negative bound reverses that ordering, so that argument does not hold there. The
290    /// conclusion still does. Whatever sign the bounds have, one corner of the two ranges is
291    /// always a consistent pair, so a `min_price` and `max_price` passing both comparisons
292    /// always admit a total.
293    ///
294    /// `Price` has no `PartialOrd` on purpose. A derived one compares `excl_vat` first and
295    /// reaches `incl_vat` only to break a tie, which answers a question neither rule asks.
296    pub(crate) fn exceeds_on_either_value(self, other: Self) -> bool {
297        let excl = self.excl_vat > other.excl_vat;
298
299        let incl = match (self.incl_vat, other.incl_vat) {
300            (Some(mine), Some(theirs)) => mine > theirs,
301            _ => false,
302        };
303
304        excl || incl
305    }
306
307    #[must_use]
308    /// Round both amounts to `digits` decimal places.
309    pub fn round_dp(self, digits: u32) -> Self {
310        Self {
311            excl_vat: self.excl_vat.round_dp(digits),
312            incl_vat: self.incl_vat.map(|v| v.round_dp(digits)),
313        }
314    }
315
316    /// Display a Price with the given currency.
317    pub fn display_currency(&self, currency: currency::Code) -> DisplayPriceCurrency<'_> {
318        DisplayPriceCurrency {
319            currency,
320            price: self,
321        }
322    }
323}
324
325/// A Display object for displaying a `Price` with an associated currency.
326///
327/// Note: The placement of the currency symbol is always before the amount.
328/// The locale is not used to determine symbol position.
329pub struct DisplayPriceCurrency<'a> {
330    currency: currency::Code,
331    price: &'a Price,
332}
333
334impl fmt::Display for DisplayPriceCurrency<'_> {
335    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
336        if let Some(incl_vat) = self.price.incl_vat {
337            write!(
338                f,
339                "{{ -vat: {:#}, +vat: {:#} }}",
340                self.price.excl_vat, incl_vat
341            )
342        } else {
343            fmt::Display::fmt(&self.price.excl_vat.display_currency(self.currency), f)
344        }
345    }
346}
347
348impl Default for Price {
349    fn default() -> Self {
350        Self::zero()
351    }
352}
353
354/// A monetary amount, the currency is dependent on the specified tariff.
355#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]
356#[cfg_attr(test, derive(serde::Deserialize))]
357pub struct Money(Decimal);
358
359impl_dec_newtype!(Money, "ยค");
360
361impl IsZero for Money {
362    fn is_zero(&self) -> bool {
363        const TOLERANCE: Decimal = dec!(0.01);
364
365        approx_eq_dec(&self.0, &Decimal::ZERO, TOLERANCE)
366    }
367}
368
369impl Money {
370    #[must_use]
371    pub(crate) const fn zero() -> Self {
372        Self(Decimal::ZERO)
373    }
374
375    /// Apply a VAT percentage to this monetary amount.
376    #[must_use]
377    pub fn apply_vat(self, vat: Vat) -> Self {
378        const ONE: Decimal = dec!(1);
379
380        let x = vat.as_unit_interval().saturating_add(ONE);
381        Self(self.0.saturating_mul(x))
382    }
383
384    /// Display Money with the given currency.
385    pub fn display_currency(&self, currency: currency::Code) -> DisplayCurrency<'_> {
386        DisplayCurrency {
387            currency,
388            money: self,
389        }
390    }
391}
392
393/// A Display object for displaying `Money` with an associated currency.
394///
395/// Note: The placement of the currency symbol is always before the amount.
396/// The locale is not used to determine symbol position.
397pub struct DisplayCurrency<'a> {
398    currency: currency::Code,
399    money: &'a Money,
400}
401
402impl fmt::Display for DisplayCurrency<'_> {
403    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404        write!(f, "{}{:#}", self.currency.into_symbol(), self.money)
405    }
406}
407
408/// A VAT percentage.
409#[derive(Debug, PartialEq, Eq, Clone, Copy)]
410pub struct Vat(Decimal);
411
412impl_dec_newtype!(Vat, "%");
413
414impl Vat {
415    #[expect(clippy::missing_panics_doc, reason = "The divisor is non-zero")]
416    /// Return the rate as a fraction of one, so a `Vat` of `21` becomes `0.21`.
417    ///
418    /// This is the form to multiply an amount by. The stored value is a percentage.
419    pub fn as_unit_interval(self) -> Decimal {
420        const PERCENT: Decimal = dec!(100);
421
422        self.0.checked_div(PERCENT).expect("divisor is non-zero")
423    }
424}
425
426/// The origin of a potential VAT percentage.
427#[derive(Clone, Copy, Debug)]
428pub(crate) enum VatOrigin {
429    /// The VAT percentage is unknown as the tariff is v211 and has no `vat` field.
430    ///
431    /// NOTE: All `incl_vat` fields should be `None` in the final calculation.
432    Unknown,
433
434    /// The tariff could have a `vat` field but a value is not provided.
435    ///
436    /// NOTE: The total `incl_vat` should be equal to `excl_vat`.
437    NotProvided,
438
439    /// The tariff could have a `vat` field and a value is provided.
440    Provided(Vat),
441}
442
443impl<'buf> LowerSchema<'buf, schema::Number<'buf>> for VatOrigin {
444    type Warning = Warning;
445
446    fn lower_schema(
447        source: &schema::Number<'buf>,
448        warnings: &mut dyn warning::Gather<Warning>,
449    ) -> Result<Self, warning::Error<Warning>> {
450        let vat = Decimal::from_schema(source, warnings)?;
451
452        // The rate is kept as written rather than dropped, so the report still shows
453        // the stated rate and the warning names the field that is wrong. Dropping it would
454        // price the component as though no VAT applied, which is a different tariff.
455        if vat.is_sign_negative() {
456            warnings.insert(source.element(), Warning::NegativeVat);
457        }
458
459        Ok(Self::Provided(Vat::from_decimal(vat)))
460    }
461}