1use 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
16pub trait Cost: Copy {
18 fn cost(&self, money: Money) -> Money;
20}
21
22impl Cost for () {
23 fn cost(&self, money: Money) -> Money {
24 money
25 }
26}
27
28#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
30pub enum WarningKind {
31 ExclusiveVatGreaterThanInclusive,
33
34 InvalidType,
36
37 MissingExclVatField,
39
40 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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd)]
81#[cfg_attr(test, derive(serde::Deserialize))]
82pub struct Price {
83 pub excl_vat: Money,
85
86 #[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 #[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 #[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#[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 #[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#[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#[derive(Clone, Copy, Debug)]
239pub enum VatApplicable {
240 Unknown,
244
245 Inapplicable,
249
250 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}