ocpi_tariffs/
money.rs

1//! Various monetary types.
2use std::{borrow::Cow, fmt};
3
4use rust_decimal::Decimal;
5use rust_decimal_macros::dec;
6use serde::Deserialize;
7
8use crate::{
9    from_warning_set_to, impl_dec_newtype, into_caveat,
10    json::{self, FieldsAsExt as _},
11    number,
12    warning::{self, GatherWarnings as _, IntoCaveat},
13    SaturatingAdd as _, Verdict,
14};
15
16/// A item that has a cost.
17pub trait Cost: Copy {
18    /// The cost of this dimension at a certain price.
19    fn cost(&self, money: Money) -> Money;
20}
21
22impl Cost for () {
23    fn cost(&self, money: Money) -> Money {
24        money
25    }
26}
27
28/// The warnings that can happen when parsing or linting a monetary value.
29#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
30pub enum WarningKind {
31    /// The `excl_vat` field is greater than the `incl_vat` field.
32    ExclusiveVatGreaterThanInclusive,
33
34    /// The JSON value given is not an object.
35    InvalidType,
36
37    /// The `excl_vat` field is required.
38    MissingExclVatField,
39
40    /// Both the `excl_vat` and `incl_vat` fields should be valid numbers.
41    Number(number::WarningKind),
42}
43
44impl fmt::Display for WarningKind {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        match self {
47            WarningKind::ExclusiveVatGreaterThanInclusive => write!(
48                f,
49                "The `excl_vat` field is greater than the `incl_vat` field"
50            ),
51            WarningKind::InvalidType => write!(f, "The value should be a number."),
52            WarningKind::MissingExclVatField => write!(f, "The `excl_vat` field is required."),
53            WarningKind::Number(kind) => fmt::Display::fmt(kind, f),
54        }
55    }
56}
57
58impl warning::Kind for WarningKind {
59    fn id(&self) -> Cow<'static, str> {
60        match self {
61            WarningKind::ExclusiveVatGreaterThanInclusive => {
62                "exclusive_vat_greater_than_inclusive".into()
63            }
64            WarningKind::InvalidType => "invalid_type".into(),
65            WarningKind::MissingExclVatField => "missing_excl_vat_field".into(),
66            WarningKind::Number(kind) => format!("number.{}", kind.id()).into(),
67        }
68    }
69}
70
71impl From<number::WarningKind> for WarningKind {
72    fn from(warn_kind: number::WarningKind) -> Self {
73        Self::Number(warn_kind)
74    }
75}
76
77from_warning_set_to!(number::WarningKind => WarningKind);
78
79/// A price consisting of a value including VAT, and a value excluding VAT.
80#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd)]
81#[cfg_attr(test, derive(serde::Deserialize))]
82pub struct Price {
83    /// The price excluding VAT.
84    pub excl_vat: Money,
85
86    /// The price including VAT.
87    ///
88    /// If no vat is applicable this value will be equal to the `excl_vat`.
89    ///
90    /// If no vat could be determined this value will be `None`.
91    /// The v211 tariffs can't determine VAT.
92    #[cfg_attr(test, serde(default))]
93    pub incl_vat: Option<Money>,
94}
95
96impl fmt::Display for Price {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        if let Some(incl_vat) = self.incl_vat {
99            write!(f, "{{ -vat: {}, +vat: {} }}", self.excl_vat, incl_vat)
100        } else {
101            fmt::Display::fmt(&self.excl_vat, f)
102        }
103    }
104}
105
106impl json::FromJson<'_, '_> for Price {
107    type WarningKind = WarningKind;
108
109    fn from_json(elem: &json::Element<'_>) -> Verdict<Self, Self::WarningKind> {
110        let mut warnings = warning::Set::new();
111        let value = elem.as_value();
112
113        let Some(fields) = value.as_object_fields() else {
114            warnings.with_elem(WarningKind::InvalidType, elem);
115            return Err(warnings);
116        };
117
118        let Some(excl_vat) = fields.find_field("excl_vat") else {
119            warnings.with_elem(WarningKind::MissingExclVatField, elem);
120            return Err(warnings);
121        };
122
123        let excl_vat = Money::from_json(excl_vat.element())?.gather_warnings_into(&mut warnings);
124
125        let incl_vat = fields
126            .find_field("incl_vat")
127            .map(|f| Money::from_json(f.element()))
128            .transpose()?
129            .gather_warnings_into(&mut warnings);
130
131        if let Some(incl_vat) = incl_vat {
132            if excl_vat > incl_vat {
133                warnings.with_elem(WarningKind::ExclusiveVatGreaterThanInclusive, elem);
134            }
135        }
136
137        Ok(Self { excl_vat, incl_vat }.into_caveat(warnings))
138    }
139}
140
141into_caveat!(Price);
142
143impl Price {
144    pub fn zero() -> Self {
145        Self {
146            excl_vat: Money::zero(),
147            incl_vat: Some(Money::zero()),
148        }
149    }
150
151    pub fn is_zero(&self) -> bool {
152        self.excl_vat.is_zero() && self.incl_vat.is_none_or(|v| v.is_zero())
153    }
154
155    /// Round this number to the OCPI specified amount of decimals.
156    #[must_use]
157    pub fn rescale(self) -> Self {
158        Self {
159            excl_vat: self.excl_vat.rescale(),
160            incl_vat: self.incl_vat.map(Money::rescale),
161        }
162    }
163
164    /// Saturating addition.
165    #[must_use]
166    pub(crate) fn saturating_add(self, rhs: Self) -> Self {
167        let incl_vat = self
168            .incl_vat
169            .zip(rhs.incl_vat)
170            .map(|(lhs, rhs)| lhs.saturating_add(rhs));
171
172        Self {
173            excl_vat: self.excl_vat.saturating_add(rhs.excl_vat),
174            incl_vat,
175        }
176    }
177
178    #[must_use]
179    pub fn round_dp(self, digits: u32) -> Self {
180        Self {
181            excl_vat: self.excl_vat.round_dp(digits),
182            incl_vat: self.incl_vat.map(|v| v.round_dp(digits)),
183        }
184    }
185}
186
187impl Default for Price {
188    fn default() -> Self {
189        Self::zero()
190    }
191}
192
193/// A monetary amount, the currency is dependant on the specified tariff.
194#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]
195#[cfg_attr(test, derive(Deserialize))]
196pub struct Money(Decimal);
197
198impl_dec_newtype!(Money, "ยค");
199
200impl Money {
201    /// Apply a VAT percentage to this monetary amount.
202    #[must_use]
203    pub fn apply_vat(self, vat: Vat) -> Self {
204        const ONE: Decimal = dec!(1);
205
206        let x = vat.as_unit_interval().saturating_add(ONE);
207        Self(self.0.saturating_mul(x))
208    }
209}
210
211/// A VAT percentage.
212#[derive(Debug, PartialEq, Eq, Clone, Copy, Deserialize)]
213#[serde(transparent)]
214pub struct Vat(Decimal);
215
216impl From<Vat> for Decimal {
217    fn from(value: Vat) -> Self {
218        value.0
219    }
220}
221
222impl Vat {
223    #[expect(clippy::missing_panics_doc, reason = "The divisor is non-zero")]
224    pub fn as_unit_interval(self) -> Decimal {
225        const PERCENT: Decimal = dec!(100);
226
227        self.0.checked_div(PERCENT).expect("divisor is non-zero")
228    }
229}
230
231impl fmt::Display for Vat {
232    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233        self.0.fmt(f)
234    }
235}
236
237/// A VAT percentage with embedded information about whether it's applicable, inapplicable or unknown.
238#[derive(Clone, Copy, Debug)]
239pub enum VatApplicable {
240    /// The VAT percentage is not known.
241    ///
242    /// All `incl_vat` fields should be `None` in the final calculation.
243    Unknown,
244
245    /// The VAT is known but not applicable.
246    ///
247    /// The total `incl_vat` should be equal to `excl_vat`.
248    Inapplicable,
249
250    /// The VAT us know nadn applicable.
251    Applicable(Vat),
252}
253
254impl<'de> Deserialize<'de> for VatApplicable {
255    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
256    where
257        D: serde::Deserializer<'de>,
258    {
259        let vat = <Option<Vat>>::deserialize(deserializer)?;
260
261        let vat = if let Some(vat) = vat {
262            Self::Applicable(vat)
263        } else {
264            Self::Inapplicable
265        };
266
267        Ok(vat)
268    }
269}
270
271#[cfg(test)]
272mod test {
273    use crate::test::ApproxEq;
274
275    use super::Price;
276
277    impl ApproxEq for Price {
278        fn approx_eq(&self, other: &Self) -> bool {
279            let incl_eq = match (self.incl_vat, other.incl_vat) {
280                (Some(a), Some(b)) => a.approx_eq(&b),
281                (None, None) => true,
282                _ => return false,
283            };
284
285            incl_eq && self.excl_vat.approx_eq(&other.excl_vat)
286        }
287    }
288}
289
290#[cfg(test)]
291mod test_price {
292    use assert_matches::assert_matches;
293    use rust_decimal::Decimal;
294    use rust_decimal_macros::dec;
295
296    use crate::json::{self, FromJson as _};
297
298    use super::{Price, WarningKind};
299
300    #[test]
301    fn should_create_from_json_with_only_excl_vat_field() {
302        const JSON: &str = r#"{
303            "excl_vat": 10.2
304        }"#;
305
306        let elem = json::parse(JSON).unwrap();
307        let price = Price::from_json(&elem).unwrap().unwrap();
308
309        assert!(price.incl_vat.is_none());
310        assert_eq!(Decimal::from(price.excl_vat), dec!(10.2));
311    }
312
313    #[test]
314    fn should_create_from_json_with_excl_and_incl_vat_fields() {
315        const JSON: &str = r#"{
316            "excl_vat": 10.2,
317            "incl_vat": 12.3
318        }"#;
319
320        let elem = json::parse(JSON).unwrap();
321        let price = Price::from_json(&elem).unwrap().unwrap();
322
323        assert_eq!(Decimal::from(price.incl_vat.unwrap()), dec!(12.3));
324        assert_eq!(Decimal::from(price.excl_vat), dec!(10.2));
325    }
326
327    #[test]
328    fn should_fail_to_create_from_non_object_json() {
329        const JSON: &str = "12.3";
330
331        let elem = json::parse(JSON).unwrap();
332        let warnings = Price::from_json(&elem).unwrap_err().into_kind_vec();
333
334        assert_matches!(*warnings, [WarningKind::InvalidType]);
335    }
336
337    #[test]
338    fn should_fail_to_create_from_json_as_excl_vat_is_required() {
339        const JSON: &str = r#"{
340            "incl_vat": 12.3
341        }"#;
342
343        let elem = json::parse(JSON).unwrap();
344        let warnings = Price::from_json(&elem).unwrap_err().into_kind_vec();
345
346        assert_matches!(*warnings, [WarningKind::MissingExclVatField]);
347    }
348
349    #[test]
350    fn should_create_from_json_and_warn_about_excl_vat_greater_than_incl_vat() {
351        const JSON: &str = r#"{
352            "excl_vat": 12.3,
353            "incl_vat": 10.2
354        }"#;
355
356        let elem = json::parse(JSON).unwrap();
357        let (_price, warnings) = Price::from_json(&elem).unwrap().into_parts();
358        let warnings = warnings.into_kind_vec();
359
360        assert_matches!(*warnings, [WarningKind::ExclusiveVatGreaterThanInclusive]);
361    }
362}