planter-core 0.0.7

Domain logic for PlanTer, a project management application
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
use std::collections::BTreeMap;
use std::iter::Sum;
use std::ops::{Add, AddAssign};

pub use iso_currency::Currency;

/// A resolved monetary value: an integer count of `currency`'s minor unit (ISO 4217 term; e.g.
/// cents for EUR/USD) together with the currency it is denominated in.
///
/// `Currency::exponent` gives how many decimal places a currency's minor unit represents;
/// formatting for humans with that exponent is a caller concern, not this type's.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Money {
    minor_units: u64,
    currency: Currency,
}

impl Money {
    /// Creates a monetary value of `minor_units` of `currency`'s minor unit. `1050` EUR minor
    /// units is 10.50 EUR.
    ///
    /// # Example
    ///
    /// ```
    /// use planter_core::money::{Money, Currency};
    ///
    /// let money = Money::from_minor_units(1050, Currency::EUR); // EUR 10.50
    /// assert_eq!(money.minor_units(), 1050);
    /// assert_eq!(money.currency(), Currency::EUR);
    /// ```
    #[must_use]
    pub const fn from_minor_units(minor_units: u64, currency: Currency) -> Self {
        Money {
            minor_units,
            currency,
        }
    }

    /// Returns the raw count of the currency's minor unit, not normalised to whole currency
    /// units. The caller scales it with [`Currency::exponent`] to render a human figure.
    ///
    /// # Example
    ///
    /// ```
    /// use planter_core::money::{Money, Currency};
    ///
    /// let money = Money::from_minor_units(1050, Currency::EUR);
    /// assert_eq!(money.minor_units(), 1050);
    /// ```
    #[must_use]
    pub const fn minor_units(&self) -> u64 {
        self.minor_units
    }

    /// Returns the currency this amount is denominated in.
    ///
    /// # Example
    ///
    /// ```
    /// use planter_core::money::{Money, Currency};
    ///
    /// let money = Money::from_minor_units(1000, Currency::EUR);
    /// assert_eq!(money.currency(), Currency::EUR);
    /// ```
    #[must_use]
    pub const fn currency(&self) -> Currency {
        self.currency
    }
}

/// A sum of money that may span multiple currencies. Amounts in the same currency are added
/// together; different currencies are kept as separate entries and are never silently combined
/// or converted, since `planter-core` has no exchange-rate logic. A caller that wants a single
/// blended figure must convert explicitly, with rates it sources itself.
///
/// Build one by adding [`Money`] values (`a + b`, `total += money`), or by summing or
/// collecting them (`iter.collect()`, `iter.sum()`); read it back with [`Self::iter`] or
/// [`Self::in_currency`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct MultiCurrencyAmount(BTreeMap<Currency, u64>);

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for MultiCurrencyAmount {
    /// Deserializes by routing through this type's `FromIterator<Money>` implementation, the
    /// same chokepoint every other constructor goes through, so a zero entry in the source data
    /// is dropped rather than preserved.
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let raw = BTreeMap::<Currency, u64>::deserialize(deserializer)?;
        Ok(raw
            .into_iter()
            .map(|(currency, amount)| Money::from_minor_units(amount, currency))
            .collect())
    }
}

impl MultiCurrencyAmount {
    /// Creates an empty amount: zero cost, no entries.
    ///
    /// # Example
    ///
    /// ```
    /// use planter_core::money::MultiCurrencyAmount;
    ///
    /// assert!(MultiCurrencyAmount::new().is_empty());
    /// ```
    #[must_use]
    pub const fn new() -> Self {
        MultiCurrencyAmount(BTreeMap::new())
    }

    /// Returns `true` if there are no entries, i.e. this represents zero cost.
    ///
    /// # Example
    ///
    /// ```
    /// use planter_core::money::{Money, Currency, MultiCurrencyAmount};
    ///
    /// let mut total = MultiCurrencyAmount::new();
    /// assert!(total.is_empty());
    /// total += Money::from_minor_units(500, Currency::EUR);
    /// assert!(!total.is_empty());
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the total in `currency`, or `None` if there is no entry for it.
    ///
    /// # Example
    ///
    /// ```
    /// use planter_core::money::{Money, Currency, MultiCurrencyAmount};
    ///
    /// let total = Money::from_minor_units(200, Currency::EUR) + Money::from_minor_units(50, Currency::EUR);
    /// assert_eq!(total.in_currency(Currency::EUR), Some(Money::from_minor_units(250, Currency::EUR)));
    /// assert_eq!(total.in_currency(Currency::USD), None);
    /// ```
    #[must_use]
    pub fn in_currency(&self, currency: Currency) -> Option<Money> {
        self.0
            .get(&currency)
            .map(|&amount| Money::from_minor_units(amount, currency))
    }

    /// Iterates over the per-currency subtotals, one [`Money`] per currency.
    ///
    /// # Example
    ///
    /// ```
    /// use planter_core::money::{Money, Currency, MultiCurrencyAmount};
    ///
    /// let total = Money::from_minor_units(500, Currency::USD) + Money::from_minor_units(200, Currency::EUR);
    /// let subtotals: Vec<_> = total.iter().collect();
    /// assert_eq!(subtotals.len(), 2);
    /// assert!(subtotals.contains(&Money::from_minor_units(200, Currency::EUR)));
    /// assert!(subtotals.contains(&Money::from_minor_units(500, Currency::USD)));
    /// ```
    pub fn iter(&self) -> impl Iterator<Item = Money> + '_ {
        self.into_iter()
    }

    /// Adds `money` into the entry for its currency (saturating), inserting one if absent. A
    /// zero amount is ignored: it never creates an entry, since a currency that contributes
    /// nothing isn't part of the total.
    fn add_money(&mut self, money: Money) {
        if money.minor_units() == 0 {
            return;
        }
        let slot = self.0.entry(money.currency()).or_insert(0);
        *slot = slot.saturating_add(money.minor_units());
    }
}

impl Extend<Money> for MultiCurrencyAmount {
    fn extend<I: IntoIterator<Item = Money>>(&mut self, iter: I) {
        for money in iter {
            self.add_money(money);
        }
    }
}

impl FromIterator<Money> for MultiCurrencyAmount {
    fn from_iter<I: IntoIterator<Item = Money>>(iter: I) -> Self {
        let mut total = Self::new();
        total.extend(iter);
        total
    }
}

impl From<Money> for MultiCurrencyAmount {
    fn from(money: Money) -> Self {
        let mut total = Self::new();
        total += money;
        total
    }
}

impl Add for Money {
    type Output = MultiCurrencyAmount;

    /// Sums two monetary values into a [`MultiCurrencyAmount`]: same-currency amounts merge into
    /// one entry, different currencies stay separate. The result is always a
    /// `MultiCurrencyAmount`, never a `Money`, because the two currencies may differ and this
    /// crate never blends them.
    fn add(self, rhs: Self) -> MultiCurrencyAmount {
        let mut total = MultiCurrencyAmount::new();
        total += self;
        total += rhs;
        total
    }
}

impl Add<Money> for MultiCurrencyAmount {
    type Output = Self;

    fn add(mut self, rhs: Money) -> Self {
        self += rhs;
        self
    }
}

impl Add<MultiCurrencyAmount> for Money {
    type Output = MultiCurrencyAmount;

    fn add(self, mut rhs: MultiCurrencyAmount) -> MultiCurrencyAmount {
        rhs += self;
        rhs
    }
}

impl AddAssign<Money> for MultiCurrencyAmount {
    fn add_assign(&mut self, money: Money) {
        self.add_money(money);
    }
}

impl AddAssign for MultiCurrencyAmount {
    fn add_assign(&mut self, rhs: Self) {
        for (currency, amount) in rhs.0 {
            self.add_money(Money::from_minor_units(amount, currency));
        }
    }
}

impl Add for MultiCurrencyAmount {
    type Output = Self;

    fn add(mut self, rhs: Self) -> Self {
        self += rhs;
        self
    }
}

impl Sum for MultiCurrencyAmount {
    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
        iter.fold(Self::new(), Add::add)
    }
}

impl Sum<Money> for MultiCurrencyAmount {
    fn sum<I: Iterator<Item = Money>>(iter: I) -> Self {
        Self::from_iter(iter)
    }
}

impl<'a> IntoIterator for &'a MultiCurrencyAmount {
    type Item = Money;
    type IntoIter = std::iter::Map<
        std::collections::btree_map::Iter<'a, Currency, u64>,
        fn((&Currency, &u64)) -> Money,
    >;

    fn into_iter(self) -> Self::IntoIter {
        self.0
            .iter()
            .map(|(&currency, &amount)| Money::from_minor_units(amount, currency))
    }
}

#[cfg(test)]
/// Utilities to test monetary values.
pub mod test_utils {
    use proptest::prelude::*;

    use super::{Currency, Money};

    /// The currencies the strategies here draw from.
    pub const CURRENCIES: [Currency; 4] =
        [Currency::EUR, Currency::USD, Currency::GBP, Currency::JPY];

    /// A random currency from [`CURRENCIES`].
    pub fn currency_strategy() -> impl Strategy<Value = Currency> {
        prop::sample::select(CURRENCIES.to_vec())
    }

    /// A random [`Money`] in a random currency, with its amount drawn from `amount`.
    pub fn money_strategy(amount: impl Strategy<Value = u64>) -> impl Strategy<Value = Money> {
        (currency_strategy(), amount).prop_map(|(c, a)| Money::from_minor_units(a, c))
    }
}

#[cfg(test)]
mod tests {
    use proptest::prelude::*;

    use super::test_utils::{CURRENCIES, currency_strategy, money_strategy};
    use super::{Currency, Money, MultiCurrencyAmount};

    proptest! {
        #[test]
        fn same_currency_amounts_merge(c in currency_strategy(), a in 0u64..1_000_000, b in 0u64..1_000_000) {
            let total = Money::from_minor_units(a, c) + Money::from_minor_units(b, c);
            let expected = (a + b != 0).then(|| Money::from_minor_units(a + b, c));
            prop_assert_eq!(total.in_currency(c), expected);
        }

        #[test]
        fn different_currencies_stay_separate(
            c1 in currency_strategy(), c2 in currency_strategy(),
            a in 1u64..1_000_000, b in 1u64..1_000_000,
        ) {
            prop_assume!(c1 != c2);
            let total = Money::from_minor_units(a, c1) + Money::from_minor_units(b, c2);
            prop_assert_eq!(total.iter().count(), 2);
            prop_assert_eq!(total.in_currency(c1), Some(Money::from_minor_units(a, c1)));
            prop_assert_eq!(total.in_currency(c2), Some(Money::from_minor_units(b, c2)));
        }

        #[test]
        fn addition_saturates_instead_of_overflowing(c in currency_strategy(), a in any::<u64>(), b in any::<u64>()) {
            let total = Money::from_minor_units(a, c) + Money::from_minor_units(b, c);
            let sum = a.saturating_add(b);
            let expected = (sum != 0).then(|| Money::from_minor_units(sum, c));
            prop_assert_eq!(total.in_currency(c), expected);
        }

        #[test]
        fn sum_merges_by_currency(amounts in prop::collection::vec(money_strategy(0u64..100_000), 0..12)) {
            let total: MultiCurrencyAmount = amounts.iter().copied().sum();
            for c in CURRENCIES {
                let manual: u64 = amounts
                    .iter()
                    .filter(|m| m.currency() == c)
                    .map(Money::minor_units)
                    .sum();
                prop_assert_eq!(total.in_currency(c).map_or(0, |m| m.minor_units()), manual);
            }
        }

        #[test]
        fn from_money_round_trips(c in currency_strategy(), a in 0u64..1_000_000) {
            let m = Money::from_minor_units(a, c);
            let expected = (a != 0).then_some(m);
            prop_assert_eq!(MultiCurrencyAmount::from(m).in_currency(c), expected);
        }

        #[test]
        fn zero_is_the_additive_identity(c in currency_strategy(), a in 1u64..1_000_000) {
            let base = MultiCurrencyAmount::from(Money::from_minor_units(a, c));
            let mut with_zero = base.clone();
            with_zero += Money::from_minor_units(0, c);
            prop_assert_eq!(base, with_zero);
        }
    }

    #[test]
    fn new_amount_is_empty() {
        assert!(MultiCurrencyAmount::new().is_empty());
    }

    #[test]
    fn adding_only_zeros_stays_empty() {
        let total =
            Money::from_minor_units(0, Currency::EUR) + Money::from_minor_units(0, Currency::USD);
        assert!(total.is_empty());
        assert_eq!(total.in_currency(Currency::EUR), None);
    }

    #[test]
    fn the_addition_operators_compose() {
        // Money + Money, Money + MultiCurrencyAmount, and MultiCurrencyAmount + Money chain.
        let total = Money::from_minor_units(1, Currency::GBP)
            + (Money::from_minor_units(880, Currency::EUR)
                + Money::from_minor_units(300, Currency::USD))
            + Money::from_minor_units(9, Currency::GBP);
        assert_eq!(
            total.in_currency(Currency::GBP),
            Some(Money::from_minor_units(10, Currency::GBP))
        );
        assert_eq!(
            total.in_currency(Currency::EUR),
            Some(Money::from_minor_units(880, Currency::EUR))
        );
    }
}

#[cfg(all(test, feature = "serde"))]
mod serde_tests {
    use proptest::prelude::*;

    use super::test_utils::money_strategy;
    use super::{Money, MultiCurrencyAmount};

    proptest! {
        #[test]
        fn money_serde_roundtrip(money in money_strategy(any::<u64>())) {
            let json = serde_json::to_string(&money).unwrap();
            prop_assert_eq!(serde_json::from_str::<Money>(&json).unwrap(), money);
        }

        #[test]
        fn multi_currency_amount_serde_roundtrip(
            amounts in prop::collection::vec(money_strategy(any::<u64>()), 0..8),
        ) {
            let bag: MultiCurrencyAmount = amounts.into_iter().sum();
            let json = serde_json::to_string(&bag).unwrap();
            prop_assert_eq!(serde_json::from_str::<MultiCurrencyAmount>(&json).unwrap(), bag);
        }
    }

    #[test]
    fn deserializing_a_zero_entry_drops_it() {
        let json = r#"{"EUR":0,"USD":500}"#;
        let amount: MultiCurrencyAmount = serde_json::from_str(json).unwrap();
        assert_eq!(amount.in_currency(super::Currency::EUR), None);
        assert_eq!(
            amount.in_currency(super::Currency::USD),
            Some(Money::from_minor_units(500, super::Currency::USD))
        );
    }
}