grid_tariffs/
money.rs

1use std::{
2    fmt::{Display, Formatter},
3    iter::Sum,
4    ops::{Add, Div, Mul, Neg, Sub},
5    str::FromStr,
6};
7
8use serde::Serialize;
9
10use crate::{Country, currency::Currency};
11
12#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
13pub enum MoneyError {
14    #[error("Invalid money")]
15    InvalidMoney,
16    #[error("Money sub-unit is more than 99")]
17    SubunitOutOfRange,
18}
19
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize)]
21#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
22pub struct Money(i64);
23
24impl Money {
25    pub const ZERO: Self = Self(0);
26    const GAIN: i64 = 100000;
27    const GAIN_F64: f64 = 100000.;
28
29    pub const fn new(int: i64, fract: u8) -> Self {
30        let base = int * Self::GAIN;
31        let sub = fract as i64 * Self::GAIN / 100;
32        Self(if base.is_negative() {
33            base - sub
34        } else {
35            base + sub
36        })
37    }
38
39    /// From a subunit amount (öre, cents etc)
40    /// E.g. Money::new_subunit(8.86) -> Money(8860)
41    pub const fn new_subunit(value: f64) -> Self {
42        Self((value * Self::GAIN_F64 / 100.) as i64)
43    }
44
45    pub const fn display(&self, currency: Currency) -> MoneyDisplay {
46        MoneyDisplay(*self, currency)
47    }
48
49    pub const fn inner(&self) -> i64 {
50        self.0
51    }
52
53    pub const fn from_inner(inner: i64) -> Self {
54        Self(inner)
55    }
56
57    pub const fn from_f64(value: f64) -> Self {
58        Self((value * Self::GAIN_F64) as i64)
59    }
60
61    pub const fn to_f64(self) -> f64 {
62        self.0 as f64 / Self::GAIN_F64
63    }
64
65    pub const fn divide_by(&self, by: i64) -> Self {
66        Self(self.0 / by)
67    }
68
69    pub(crate) const fn add_vat(&self, country: Country) -> Money {
70        Self::from_f64(country.add_vat(self.to_f64()))
71    }
72
73    pub(crate) const fn remove_vat(&self, country: Country) -> Money {
74        Self::from_f64(country.remove_vat(self.to_f64()))
75    }
76
77    pub(crate) const fn reduce_by(self, reduce_amount: Money) -> Money {
78        Self(self.inner() - reduce_amount.inner())
79    }
80}
81
82impl Display for Money {
83    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
84        format!("{:.2}", self.to_f64()).fmt(f)
85    }
86}
87
88impl FromStr for Money {
89    type Err = MoneyError;
90
91    fn from_str(s: &str) -> Result<Self, Self::Err> {
92        if let Some((int, fract)) = s.split_once('.') {
93            let int: i64 = int.parse().map_err(|_| MoneyError::InvalidMoney)?;
94            let fract: u8 = fract.parse().map_err(|_| MoneyError::SubunitOutOfRange)?;
95            Ok(Self::new(int, fract))
96        } else {
97            let int: i64 = s.parse().map_err(|_| MoneyError::InvalidMoney)?;
98            Ok(Self::new(int, 0))
99        }
100    }
101}
102
103impl From<f64> for Money {
104    fn from(value: f64) -> Self {
105        Self::from_f64(value)
106    }
107}
108
109impl From<(i32, u8)> for Money {
110    fn from((int, fract): (i32, u8)) -> Self {
111        Self::new(int.into(), fract)
112    }
113}
114
115impl From<Money> for f64 {
116    fn from(value: Money) -> Self {
117        value.to_f64()
118    }
119}
120
121impl Mul<f64> for Money {
122    type Output = Self;
123
124    fn mul(self, rhs: f64) -> Self::Output {
125        Self::from(self.to_f64() * rhs)
126    }
127}
128
129impl Div<f64> for Money {
130    type Output = Self;
131
132    fn div(self, rhs: f64) -> Self::Output {
133        Self::from(self.to_f64() / rhs)
134    }
135}
136
137impl Div<i64> for Money {
138    type Output = Self;
139
140    fn div(self, rhs: i64) -> Self::Output {
141        Self(self.0 / rhs)
142    }
143}
144
145impl Add for Money {
146    type Output = Self;
147
148    fn add(self, rhs: Self) -> Self::Output {
149        Self(self.0 + rhs.0)
150    }
151}
152
153impl Sub for Money {
154    type Output = Self;
155
156    fn sub(self, rhs: Self) -> Self::Output {
157        Self(self.0 - rhs.0)
158    }
159}
160
161impl Neg for Money {
162    type Output = Self;
163
164    fn neg(self) -> Self::Output {
165        Self(-self.0)
166    }
167}
168
169impl Sum for Money {
170    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
171        iter.reduce(|a, b| a + b).unwrap_or_default()
172    }
173}
174
175impl<'a> Sum<&'a Money> for Money {
176    fn sum<I: Iterator<Item = &'a Money>>(iter: I) -> Self {
177        iter.map(|m| m.to_owned()).sum()
178    }
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
182pub struct MoneyDisplay(pub Money, pub Currency);
183
184impl std::fmt::Display for MoneyDisplay {
185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        f.write_fmt(format_args!("{} {}", self.amount(), self.currency().sign()))
187    }
188}
189
190impl MoneyDisplay {
191    pub const fn money(&self) -> Money {
192        self.0
193    }
194    pub const fn currency(&self) -> Currency {
195        self.1
196    }
197
198    pub fn subunit_display(&self) -> String {
199        format!(
200            "{} {}",
201            self.subunit_amount(),
202            self.currency().subunit_sign()
203        )
204    }
205
206    pub fn amount(&self) -> String {
207        format!("{:.2}", self.money().to_f64())
208    }
209
210    pub fn subunit_amount(&self) -> String {
211        format!("{:.0}", self.money().to_f64() * 100.)
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use super::{Currency, Money};
218
219    #[test]
220    fn new_money_positive() {
221        assert_eq!(Money::new(2, 14), Money(214000));
222    }
223
224    #[test]
225    fn new_money_small() {
226        assert_eq!(Money::new(0, 4), Money(4000));
227    }
228
229    #[test]
230    fn new_money_negative() {
231        assert_eq!(Money::new(-2, 14), Money(-214000));
232    }
233
234    #[test]
235    fn from_negative_f64() {
236        assert_eq!(Money::from(-2.14), Money(-214000));
237    }
238
239    #[test]
240    fn from_small_f64() {
241        assert_eq!(Money::from(0.04732), Money(4732));
242    }
243
244    #[test]
245    fn new_subunit() {
246        assert_eq!(Money::new_subunit(14.), Money(14_000));
247        assert_eq!(Money::new_subunit(8.86), Money(8_860));
248    }
249
250    #[test]
251    fn new_subunit_and_new_equal() {
252        assert_eq!(Money::new_subunit(14.), Money::new(0, 14));
253    }
254
255    #[test]
256    fn display_impl() {
257        assert_eq!(Money(9000).to_string(), "0.09");
258        assert_eq!(Money(199999).to_string(), "2.00");
259        assert_eq!(Money(20_999_999).to_string(), "210.00");
260    }
261
262    #[test]
263    fn display() {
264        let m = Money::from((1, 42)).display(Currency::SEK);
265        assert_eq!(m.to_string(), "1.42 kr");
266    }
267
268    #[test]
269    fn display_small() {
270        let m = Money::from((0, 9)).display(Currency::SEK);
271        assert_eq!(m.to_string(), "0.09 kr");
272    }
273
274    #[test]
275    fn subunit_display() {
276        let m = Money::from((1, 42)).display(Currency::SEK);
277        assert_eq!(m.subunit_display(), "142 öre");
278    }
279
280    #[test]
281    fn amount_display() {
282        let m = Money::from((1, 42)).display(Currency::SEK);
283        assert_eq!(m.amount(), "1.42");
284    }
285
286    #[test]
287    fn amount_display_small() {
288        let m = Money(7765).display(Currency::SEK);
289        assert_eq!(m.amount(), "0.08");
290    }
291
292    #[test]
293    fn amount_display_large() {
294        let m = Money::from((123456789, 99)).display(Currency::SEK);
295        assert_eq!(m.amount(), "123456789.99");
296    }
297
298    #[test]
299    fn subunit_amount_display() {
300        let m = Money::from((1, 42)).display(Currency::SEK);
301        assert_eq!(m.subunit_amount(), "142");
302    }
303
304    #[test]
305    fn add_money() {
306        assert_eq!(Money(1437), Money(100) + Money(1337));
307    }
308
309    #[test]
310    fn mul_money_f64() {
311        assert_eq!(Money(145) * 10f64, Money(1450));
312    }
313
314    #[test]
315    fn into_f64() {
316        let val: f64 = Money(145000).into();
317        assert_eq!(val, 1.45);
318    }
319
320    #[test]
321    fn sum_money_references() {
322        assert_eq!([Money(100), Money(1237)].iter().sum::<Money>(), Money(1337));
323    }
324
325    #[test]
326    fn sum_money_negative() {
327        assert_eq!(
328            [Money(-40000), Money(-3000), Money(-7500)]
329                .iter()
330                .sum::<Money>(),
331            Money(-50500)
332        );
333    }
334
335    #[test]
336    fn sum_money_mixed() {
337        assert_eq!(
338            [Money(-40000), Money(5000), Money(8000)]
339                .iter()
340                .sum::<Money>(),
341            Money(-27000)
342        );
343    }
344}