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
//! Various monetary types.

#[cfg(test)]
mod test;

#[cfg(test)]
mod test_from_schema;

#[cfg(test)]
mod test_price;

use std::fmt;

use rust_decimal::Decimal;
use rust_decimal_macros::dec;

use crate::{
    currency, from_warning_all, impl_dec_newtype,
    json::{self, FieldsAsExt as _},
    number::{self, approx_eq_dec, FromDecimal as _, IsZero, RoundDecimal},
    schema::{self, Integrity},
    warning::{self, GatherWarnings as _, IntoCaveat as _},
    FromSchema, SaturatingAdd as _, Verdict,
};

/// An item that has a cost.
pub trait Cost: Copy {
    /// The cost of this dimension at a certain price.
    fn cost(&self, money: Money) -> Money;
}

impl Cost for () {
    fn cost(&self, money: Money) -> Money {
        money
    }
}

/// The warnings that can happen when parsing or linting a `Price`.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum Warning {
    /// The `excl_vat` field is greater than the `incl_vat` field.
    ExclusiveVatGreaterThanInclusive,

    /// The JSON value given is not an object.
    InvalidType { type_found: json::ValueKind },

    /// The `excl_vat` field is required.
    MissingExclVatField,

    /// Both the `excl_vat` and `incl_vat` fields should be valid numbers.
    Number(number::Warning),
}

impl Warning {
    fn invalid_type(elem: &json::Element<'_>) -> Self {
        Self::InvalidType {
            type_found: elem.value().kind(),
        }
    }
}

impl fmt::Display for Warning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ExclusiveVatGreaterThanInclusive => write!(
                f,
                "The `excl_vat` field is greater than the `incl_vat` field"
            ),
            Self::InvalidType { type_found } => {
                write!(
                    f,
                    "The value should be a `Price {{ excl_vat, incl_vat }}` object but is `{type_found}`"
                )
            }
            Self::MissingExclVatField => write!(f, "The `excl_vat` field is required."),
            Self::Number(kind) => fmt::Display::fmt(kind, f),
        }
    }
}

impl crate::Warning for Warning {
    fn id(&self) -> warning::Id {
        match self {
            Self::ExclusiveVatGreaterThanInclusive => {
                warning::Id::from_static("exclusive_vat_greater_than_inclusive")
            }
            Self::InvalidType { type_found } => {
                warning::Id::from_string(format!("invalid_type({type_found})"))
            }
            Self::MissingExclVatField => warning::Id::from_static("missing_excl_vat_field"),
            Self::Number(kind) => kind.id(),
        }
    }
}

from_warning_all!(number::Warning => Warning::Number);

/// A price consisting of a value including VAT, and a value excluding VAT.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd)]
#[cfg_attr(test, derive(serde::Deserialize))]
pub struct Price {
    /// The price excluding VAT.
    pub excl_vat: Money,

    /// The price including VAT.
    ///
    /// If no vat is applicable this value will be equal to the `excl_vat`.
    ///
    /// If no vat could be determined this value will be `None`.
    /// The v211 tariffs can't determine VAT.
    #[cfg_attr(test, serde(default))]
    pub incl_vat: Option<Money>,
}

impl RoundDecimal for Price {
    fn round_to_ocpi_scale(self) -> Self {
        let Self { excl_vat, incl_vat } = self;
        Self {
            excl_vat: excl_vat.round_to_ocpi_scale(),
            incl_vat: incl_vat.round_to_ocpi_scale(),
        }
    }
}

impl fmt::Display for Price {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(incl_vat) = self.incl_vat {
            if f.alternate() {
                write!(f, "{{ -vat: {:#}, +vat: {:#} }}", self.excl_vat, incl_vat)
            } else {
                write!(f, "{{ -vat: {}, +vat: {} }}", self.excl_vat, incl_vat)
            }
        } else {
            fmt::Display::fmt(&self.excl_vat, f)
        }
    }
}

impl json::FromJson<'_> for Price {
    type Warning = Warning;

    fn from_json(elem: &json::Element<'_>) -> Verdict<Self, Self::Warning> {
        let mut warnings = warning::Set::new();
        let value = elem.as_value();

        let Some(fields) = value.as_object_fields() else {
            return warnings.bail(elem, Warning::invalid_type(elem));
        };

        let Some(excl_vat) = fields.find_field("excl_vat") else {
            return warnings.bail(elem, Warning::MissingExclVatField);
        };

        let excl_vat = Money::from_json(excl_vat.element())?.gather_warnings_into(&mut warnings);

        let incl_vat = fields
            .find_field("incl_vat")
            .map(|f| Money::from_json(f.element()))
            .transpose()?
            .gather_warnings_into(&mut warnings);

        if let Some(incl_vat) = incl_vat {
            if excl_vat > incl_vat {
                warnings.insert(elem, Warning::ExclusiveVatGreaterThanInclusive);
            }
        }

        Ok(Self { excl_vat, incl_vat }.into_caveat(warnings))
    }
}

impl<'buf> FromSchema<'buf, schema::v221::Price<'buf>> for Price {
    type Warning = Warning;

    fn from_schema(source: &schema::v221::Price<'buf>) -> Verdict<Self, Self::Warning> {
        let mut warnings = warning::Set::new();

        // A bare-number price (the 2.1.1 shape) is just `excl_vat`: there is no `incl_vat`
        // and thus no excl-vs-incl comparison to make.
        let (elem, excl_vat, incl_vat) = match source {
            schema::v221::Price::Number(number) => {
                let excl_vat = Money::from_schema(number)?.gather_warnings_into(&mut warnings);
                let price = Self {
                    excl_vat,
                    incl_vat: None,
                };
                return Ok(price.into_caveat(warnings));
            }
            schema::v221::Price::Object {
                elem,
                excl_vat,
                incl_vat,
            } => (elem, excl_vat, incl_vat),
        };

        // `excl_vat` is required; without a usable value a `Price` cannot be built. A
        // missing or wrong-kind field is already reported structurally by the schema
        // walk, so the bail here is the domain-level signal that the price is unusable.
        let Integrity::Ok(excl_vat) = excl_vat else {
            return warnings.bail(elem, Warning::MissingExclVatField);
        };
        let excl_vat = Money::from_schema(excl_vat)?.gather_warnings_into(&mut warnings);

        // `incl_vat` is optional. Absent or `null` leaves the price without VAT info; a
        // wrong-kind value (flagged structurally by the schema) is likewise treated as no
        // VAT rather than failing the whole price.
        let incl_vat = match incl_vat {
            Integrity::Ok(Some(number)) => {
                Some(Money::from_schema(number)?.gather_warnings_into(&mut warnings))
            }
            Integrity::Ok(None) | Integrity::Missing | Integrity::Err => None,
        };

        if let Some(incl_vat) = incl_vat {
            if excl_vat > incl_vat {
                warnings.insert(elem, Warning::ExclusiveVatGreaterThanInclusive);
            }
        }

        Ok(Self { excl_vat, incl_vat }.into_caveat(warnings))
    }
}

impl IsZero for Price {
    fn is_zero(&self) -> bool {
        self.excl_vat.is_zero() && self.incl_vat.is_none_or(|v| v.is_zero())
    }
}

impl Price {
    pub fn zero() -> Self {
        Self {
            excl_vat: Money::zero(),
            incl_vat: Some(Money::zero()),
        }
    }

    /// Round this number to the OCPI specified amount of decimals.
    #[must_use]
    pub fn rescale(self) -> Self {
        Self {
            excl_vat: self.excl_vat.rescale(),
            incl_vat: self.incl_vat.map(Money::rescale),
        }
    }

    /// Saturating addition.
    #[must_use]
    pub(crate) fn saturating_add(self, rhs: Self) -> Self {
        let incl_vat = self
            .incl_vat
            .zip(rhs.incl_vat)
            .map(|(lhs, rhs)| lhs.saturating_add(rhs));

        Self {
            excl_vat: self.excl_vat.saturating_add(rhs.excl_vat),
            incl_vat,
        }
    }

    #[must_use]
    pub fn round_dp(self, digits: u32) -> Self {
        Self {
            excl_vat: self.excl_vat.round_dp(digits),
            incl_vat: self.incl_vat.map(|v| v.round_dp(digits)),
        }
    }

    /// Display a Price with the given currency.
    pub fn display_currency(&self, currency: currency::Code) -> DisplayPriceCurrency<'_> {
        DisplayPriceCurrency {
            currency,
            price: self,
        }
    }
}

/// Parses a JSON `Element` into a `Price`.
///
/// If the `Element` is a JSON `Number` then the value is set to the `Price::excl_vat` field
/// leaving the `incl_vat` field as `None`.
pub(crate) struct PriceOrNumber(Price);

impl PriceOrNumber {
    pub(crate) fn into_inner(self) -> Price {
        self.0
    }
}

impl json::FromJson<'_> for PriceOrNumber {
    type Warning = Warning;

    fn from_json(elem: &json::Element<'_>) -> Verdict<Self, Self::Warning> {
        let mut warnings = warning::Set::new();
        let value = elem.as_value();

        if value.kind() == json::ValueKind::Number {
            warnings.insert(elem, Warning::invalid_type(elem));

            let excl_vat = Money::from_json(elem)?.gather_warnings_into(&mut warnings);
            let price = Price {
                excl_vat,
                incl_vat: None,
            };
            return Ok(Self(price).into_caveat(warnings));
        }

        let price = Price::from_json(elem).gather_warnings_into(&mut warnings)?;
        Ok(Self(price).into_caveat(warnings))
    }
}

/// A Display object for displaying a `Price` with an associated currency.
///
/// Note: The placement of the currency symbol is always before the amount.
/// The locale is not used to determine symbol position.
pub struct DisplayPriceCurrency<'a> {
    currency: currency::Code,
    price: &'a Price,
}

impl fmt::Display for DisplayPriceCurrency<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(incl_vat) = self.price.incl_vat {
            write!(
                f,
                "{{ -vat: {:#}, +vat: {:#} }}",
                self.price.excl_vat, incl_vat
            )
        } else {
            fmt::Display::fmt(&self.price.excl_vat.display_currency(self.currency), f)
        }
    }
}

impl Default for Price {
    fn default() -> Self {
        Self::zero()
    }
}

/// A monetary amount, the currency is dependent on the specified tariff.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]
#[cfg_attr(test, derive(serde::Deserialize))]
pub struct Money(Decimal);

impl_dec_newtype!(Money, "ยค");

impl IsZero for Money {
    fn is_zero(&self) -> bool {
        const TOLERANCE: Decimal = dec!(0.01);

        approx_eq_dec(&self.0, &Decimal::ZERO, TOLERANCE)
    }
}

impl Money {
    #[must_use]
    pub(crate) const fn zero() -> Self {
        Self(Decimal::ZERO)
    }

    /// Apply a VAT percentage to this monetary amount.
    #[must_use]
    pub fn apply_vat(self, vat: Vat) -> Self {
        const ONE: Decimal = dec!(1);

        let x = vat.as_unit_interval().saturating_add(ONE);
        Self(self.0.saturating_mul(x))
    }

    /// Display Money with the given currency.
    pub fn display_currency(&self, currency: currency::Code) -> DisplayCurrency<'_> {
        DisplayCurrency {
            currency,
            money: self,
        }
    }
}

/// A Display object for displaying `Money` with an associated currency.
///
/// Note: The placement of the currency symbol is always before the amount.
/// The locale is not used to determine symbol position.
pub struct DisplayCurrency<'a> {
    currency: currency::Code,
    money: &'a Money,
}

impl fmt::Display for DisplayCurrency<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{:#}", self.currency.into_symbol(), self.money)
    }
}

/// A VAT percentage.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct Vat(Decimal);

impl_dec_newtype!(Vat, "%");

impl Vat {
    #[expect(clippy::missing_panics_doc, reason = "The divisor is non-zero")]
    pub fn as_unit_interval(self) -> Decimal {
        const PERCENT: Decimal = dec!(100);

        self.0.checked_div(PERCENT).expect("divisor is non-zero")
    }
}

/// The origin of a potential VAT percentage.
#[derive(Clone, Copy, Debug)]
pub(crate) enum VatOrigin {
    /// The VAT percentage is unknown as the tariff is v211 and has no `vat` field.
    ///
    /// NOTE: All `incl_vat` fields should be `None` in the final calculation.
    Unknown,

    /// The tariff could have a `vat` field but a value is not provided.
    ///
    /// NOTE: The total `incl_vat` should be equal to `excl_vat`.
    NotProvided,

    /// The tariff could have a `vat` field and a value is provided.
    Provided(Vat),
}

impl json::FromJson<'_> for VatOrigin {
    type Warning = number::Warning;

    fn from_json(elem: &'_ json::Element<'_>) -> Verdict<Self, Self::Warning> {
        let vat = Decimal::from_json(elem)?;
        Ok(vat.map(|d| Self::Provided(Vat::from_decimal(d))))
    }
}

impl<'buf> FromSchema<'buf, schema::Number<'buf>> for VatOrigin {
    type Warning = number::Warning;

    fn from_schema(source: &schema::Number<'buf>) -> Verdict<Self, Self::Warning> {
        let vat = Decimal::from_schema(source)?;
        Ok(vat.map(|d| Self::Provided(Vat::from_decimal(d))))
    }
}