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
//! Various monetary types.
#[cfg(test)]
mod test;
#[cfg(test)]
mod test_from_schema;
use std::fmt;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use crate::{
FromSchema, SaturatingAdd as _, Verdict, currency, from_warning_all, impl_dec_newtype,
number::{self, FromDecimal as _, IsZero, RoundDecimal, approx_eq_dec},
schema::{self, HasElement as _},
warning::{self, GatherWarnings as _, IntoCaveat as _},
};
/// 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` and `incl_vat` fields imply a VAT rate less than `0`.
///
/// The two values imply a rate, and `Price::vat_is_consistent` says which pairs imply a
/// rate less than `0`. The same bound covers a rate stated by a tariff, reported as
/// `Warning::NegativeVat`.
ImpliedVatIsNegative,
/// The `vat` field states a rate less than `0`.
///
/// A rate less than `0` is not VAT. `Price::vat_is_consistent` reads a pair as though no such
/// rate exists, since that rule holds only while `1 + vat/100` is a multiplier greater than or
/// equal to `1`. This warning reports the rate rather than refusing it, so the component is
/// still priced at the stated rate. OCPI doesn't bound the `vat` field of the `PriceComponent`
/// class
/// (<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_pricecomponent_class>),
/// so the bound is this library's rather than the spec's.
NegativeVat,
/// A number this module lowered is not valid: `excl_vat`, `incl_vat` or `vat`.
Number(number::Warning),
/// A feature rejected the schema IR for a `Price` because a required field was missing or
/// invalid. The located cause is reported by the schema validation warnings; this is a
/// content-free marker (see [`warning::Rejected`]).
Rejected,
}
impl fmt::Display for Warning {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ImpliedVatIsNegative => write!(
f,
"The `excl_vat` and `incl_vat` fields imply a VAT rate less than `0`"
),
Self::NegativeVat => {
write!(
f,
"The `vat` field states a rate less than `0`, which is not VAT"
)
}
Self::Number(kind) => fmt::Display::fmt(kind, f),
Self::Rejected => f.write_str(
"The schema IR for a `Price` was rejected; see the schema validation warnings.",
),
}
}
}
impl crate::Warning for Warning {
fn id(&self) -> warning::Id {
match self {
Self::ImpliedVatIsNegative => warning::Id::from_static("implied_vat_is_negative"),
Self::NegativeVat => warning::Id::from_static("negative_vat"),
Self::Number(kind) => kind.id(),
Self::Rejected => warning::Id::from_static("rejected"),
}
}
fn is_rejected(&self) -> bool {
matches!(self, Self::Rejected)
}
}
impl From<warning::Rejected> for Warning {
fn from(_: warning::Rejected) -> Self {
Self::Rejected
}
}
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)]
#[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<'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 content-free `Rejected` signal.
let excl_vat = warnings.ok_or_bail(excl_vat)?;
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 = incl_vat
.map_some(Money::from_schema)
.transpose()?
.gather_warnings_into(&mut warnings);
let price = Self { excl_vat, incl_vat };
if !price.vat_is_consistent() {
warnings.insert(elem, Warning::ImpliedVatIsNegative);
}
Ok(price.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 {
/// A `Price` of zero, with a zero `incl_vat` rather than an absent one.
pub fn zero() -> Self {
Self {
excl_vat: Money::zero(),
incl_vat: Some(Money::zero()),
}
}
/// Negate both amounts, which is how a Credit CDR states the `total_cost` of the CDR it credits.
#[must_use]
pub(crate) fn negate(self) -> Self {
Self {
excl_vat: Money(self.excl_vat.0.saturating_mul(Decimal::NEGATIVE_ONE)),
incl_vat: self
.incl_vat
.map(|incl_vat| Money(incl_vat.0.saturating_mul(Decimal::NEGATIVE_ONE))),
}
}
/// 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,
}
}
/// True when the two values imply a VAT rate greater than or equal to `0`.
///
/// `incl_vat` divided by `excl_vat` is the multiplier that produced one from the other, and
/// that multiplier is `1 + vat/100`. A rate greater than or equal to `0` puts the
/// multiplier greater than or equal to `1`, which grows a magnitude and leaves a sign alone.
///
/// Read back from a pair, the implied rate is less than `0` in two shapes and no others. Values
/// with different signs give a negative multiplier. Values sharing a sign, with
/// `incl_vat` the smaller in magnitude, give a multiplier between `0` and `1`. Those are one
/// fault rather than two, and the same bound covers a rate stated by a tariff.
///
/// An `excl_vat` of `0` implies no rate at all, because no multiplier turns `0` into a
/// non-zero `incl_vat`. Such a pair is accepted rather than reported, which is a gap in the
/// rule rather than a case it decides.
///
/// Stating the rule as `excl_vat` less than or equal to `incl_vat` describes the implication
/// for a non-negative amount only. `specs/v221/mod_cdrs.asciidoc:39` says only a Credit CDR's
/// `total_cost` contains the negative amounts, and both of its values are negative, so the
/// larger in magnitude is the more negative and the ordering reverses.
///
/// A `Price` stating no `incl_vat` implies nothing.
pub(crate) fn vat_is_consistent(self) -> bool {
let Some(incl_vat) = self.incl_vat else {
return true;
};
let excl = Decimal::from(self.excl_vat);
let incl = Decimal::from(incl_vat);
excl.is_sign_negative() == incl.is_sign_negative() && incl.abs() >= excl.abs()
}
/// True when `excl_vat` is above `other`'s `excl_vat`, or `incl_vat` is above `other`'s
/// `incl_vat`.
///
/// OCPI states `min_price` and `max_price` as two independent rules, one per value, and both
/// apply (`specs/v221/mod_tariffs.asciidoc:295-303`). A `min_price` above a `max_price` on
/// either value is therefore a pair no total satisfies. An `incl_vat` absent on either side
/// drops the inclusive comparison, because a bound that omits the value constrains it in no
/// way.
///
/// Comparing each value with the matching value is enough for a bound that is not
/// negative. Such a `Price` has `excl_vat` less than or equal to its own `incl_vat`, so a
/// `min_price` whose `excl_vat` is greater than the `max_price`'s `incl_vat` is greater than
/// its `excl_vat` too, and the `excl_vat` comparison catches the pair. Parsing a `Price` that
/// fails `vat_is_consistent` reports `Warning::ImpliedVatIsNegative`.
///
/// A negative bound reverses that ordering, so that argument does not hold there. The
/// conclusion still does. Whatever sign the bounds have, one corner of the two ranges is
/// always a consistent pair, so a `min_price` and `max_price` passing both comparisons
/// always admit a total.
///
/// `Price` has no `PartialOrd` on purpose. A derived one compares `excl_vat` first and
/// reaches `incl_vat` only to break a tie, which answers a question neither rule asks.
pub(crate) fn exceeds_on_either_value(self, other: Self) -> bool {
let excl = self.excl_vat > other.excl_vat;
let incl = match (self.incl_vat, other.incl_vat) {
(Some(mine), Some(theirs)) => mine > theirs,
_ => false,
};
excl || incl
}
#[must_use]
/// Round both amounts to `digits` decimal places.
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,
}
}
}
/// 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")]
/// Return the rate as a fraction of one, so a `Vat` of `21` becomes `0.21`.
///
/// This is the form to multiply an amount by. The stored value is a percentage.
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<'buf> FromSchema<'buf, schema::Number<'buf>> for VatOrigin {
type Warning = Warning;
fn from_schema(source: &schema::Number<'buf>) -> Verdict<Self, Self::Warning> {
let mut warnings = warning::Set::new();
let vat = Decimal::from_schema(source)?.gather_warnings_into(&mut warnings);
// The rate is kept as written rather than dropped, so the report still shows
// the stated rate and the warning names the field that is wrong. Dropping it would
// price the component as though no VAT applied, which is a different tariff.
if vat.is_sign_negative() {
warnings.insert(source.element(), Warning::NegativeVat);
}
Ok(Self::Provided(Vat::from_decimal(vat)).into_caveat(warnings))
}
}