lucre 0.9.0

An ergonomic library for handling money.
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
//! What the `serde` feature puts on the wire. The crate docs state the shapes
//! under Features.
//!
//! JSON, TOML, YAML and their kin work. Formats that carry no type tags —
//! bincode, postcard — do not: an amount is read through `deserialize_any`,
//! and [`Money`] is read as a map with no sequence form to fall back on.
//!
//! ## Example
//!
//! ```
//! # use std::error::Error;
//! #
//! # fn main() -> Result<(), Box<dyn Error>> {
//! use lucre::{Currency, Money, MoneyBag};
//!
//! let total = Money::from_minor(10475, &Currency::USD);
//! let document = serde_json::to_string(&total)?;
//!
//! assert_eq!(document, r#"{"amount":"104.75","currency":"USD"}"#);
//! assert_eq!(serde_json::from_str::<Money>(&document)?, total);
//!
//! let wallet: MoneyBag = serde_json::from_str(r#"{"EUR": "10.00", "USD": "30.00"}"#)?;
//!
//! assert_eq!(wallet.to_string(), "10.00 EUR, 30.00 USD");
//! #
//! #     Ok(())
//! # }
//! ```

use std::{fmt, str::FromStr};

use serde::{
    Deserialize, Deserializer, Serialize, Serializer,
    de::{self, MapAccess, Unexpected, Visitor},
    ser::{SerializeMap, SerializeStruct},
};

use crate::{Currency, Decimal, IsoAlphabeticCode, IsoNumericCode, Money, MoneyBag, RoundingMode};

const AMOUNT_FIELD: &str = "amount";
const CURRENCY_FIELD: &str = "currency";
const MONEY_FIELDS: &[&str] = &[AMOUNT_FIELD, CURRENCY_FIELD];

/// An amount on its way to or from a document: text going out, text or a
/// number coming in.
///
/// [`Decimal`] has serde impls of its own, but they answer to rust_decimal's
/// `serde-float` and `serde-str` features, which any crate sharing the build
/// can turn on. Encoding the amount here keeps lucre's shapes lucre's to
/// change.
struct Amount(Decimal);

impl Serialize for Amount {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for Amount {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_any(AmountVisitor)
    }
}

struct AmountVisitor;

impl Visitor<'_> for AmountVisitor {
    type Value = Amount;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("an amount, written as text or as a number")
    }

    fn visit_str<E: de::Error>(self, amount: &str) -> Result<Self::Value, E> {
        Decimal::from_str(amount)
            .or_else(|_| Decimal::from_scientific(amount))
            .map(Amount)
            .map_err(|_| E::invalid_value(Unexpected::Str(amount), &self))
    }

    fn visit_u64<E: de::Error>(self, amount: u64) -> Result<Self::Value, E> {
        Ok(Amount(Decimal::from(amount)))
    }

    fn visit_i64<E: de::Error>(self, amount: i64) -> Result<Self::Value, E> {
        Ok(Amount(Decimal::from(amount)))
    }

    /// Reads the digits a float prints rather than the binary fraction behind
    /// them, so `104.75` arrives as two decimal places and not as the nearest
    /// `f64` spelled out to the last bit.
    fn visit_f64<E: de::Error>(self, amount: f64) -> Result<Self::Value, E> {
        Decimal::from_str(&amount.to_string())
            .map(Amount)
            .map_err(|_| E::invalid_value(Unexpected::Float(amount), &self))
    }
}

/// Writes the amount and the currency it is denominated in as a pair of named
/// fields.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Money};
///
/// let total = Money::from_minor(10475, &Currency::USD);
///
/// assert_eq!(
///     serde_json::to_string(&total)?,
///     r#"{"amount":"104.75","currency":"USD"}"#
/// );
/// #
/// #     Ok(())
/// # }
/// ```
impl Serialize for Money {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut money = serializer.serialize_struct("Money", MONEY_FIELDS.len())?;

        money.serialize_field(AMOUNT_FIELD, &Amount(self.amount()))?;
        money.serialize_field(CURRENCY_FIELD, &self.currency())?;
        money.end()
    }
}

/// Reads both fields, in either order. Neither may be left out, and fields
/// beyond the two are skipped, so a document may carry more than an amount
/// without being rewritten first.
///
/// The amount is taken verbatim, as by [`Money::from_decimal`]: nothing is
/// rounded or scaled to the currency's minor digits.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Money};
///
/// let line = r#"{"description": "coffee", "amount": 4.75, "currency": "USD"}"#;
///
/// assert_eq!(
///     serde_json::from_str::<Money>(line)?,
///     Money::from_minor(475, &Currency::USD)
/// );
/// assert!(serde_json::from_str::<Money>(r#"{"amount": "4.75"}"#).is_err());
/// #
/// #     Ok(())
/// # }
/// ```
impl<'de> Deserialize<'de> for Money {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_struct("Money", MONEY_FIELDS, MoneyVisitor)
    }
}

struct MoneyVisitor;

impl<'de> Visitor<'de> for MoneyVisitor {
    type Value = Money;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("an amount and the currency it is denominated in")
    }

    fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Self::Value, M::Error> {
        let mut amount: Option<Amount> = None;
        let mut currency: Option<Currency> = None;

        while let Some(field) = map.next_key()? {
            match field {
                MoneyField::Amount if amount.is_some() => {
                    return Err(de::Error::duplicate_field(AMOUNT_FIELD));
                }
                MoneyField::Currency if currency.is_some() => {
                    return Err(de::Error::duplicate_field(CURRENCY_FIELD));
                }
                MoneyField::Amount => amount = Some(map.next_value()?),
                MoneyField::Currency => currency = Some(map.next_value()?),
                MoneyField::Other => {
                    map.next_value::<de::IgnoredAny>()?;
                }
            }
        }

        let Amount(amount) = amount.ok_or_else(|| de::Error::missing_field(AMOUNT_FIELD))?;
        let currency = currency.ok_or_else(|| de::Error::missing_field(CURRENCY_FIELD))?;

        Ok(Money::from_decimal(amount, &currency))
    }
}

/// A field of the serialized form, with everything unrecognized gathered into
/// one arm rather than refused.
enum MoneyField {
    Amount,
    Currency,
    Other,
}

impl<'de> Deserialize<'de> for MoneyField {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_identifier(MoneyFieldVisitor)
    }
}

struct MoneyFieldVisitor;

impl Visitor<'_> for MoneyFieldVisitor {
    type Value = MoneyField;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a field name")
    }

    fn visit_str<E: de::Error>(self, name: &str) -> Result<Self::Value, E> {
        Ok(match name {
            AMOUNT_FIELD => MoneyField::Amount,
            CURRENCY_FIELD => MoneyField::Currency,
            _ => MoneyField::Other,
        })
    }
}

/// Writes one entry per currency held, keyed by ISO alphabetic code and
/// ordered by it. A bag holding nothing writes an empty map.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Money, MoneyBag};
///
/// let mut wallet = MoneyBag::new();
/// wallet += Money::from_major(30, &Currency::USD);
/// wallet += Money::from_major(10, &Currency::EUR);
///
/// assert_eq!(
///     serde_json::to_string(&wallet)?,
///     r#"{"EUR":"10.00","USD":"30.00"}"#
/// );
/// assert_eq!(serde_json::to_string(&MoneyBag::new())?, "{}");
/// #
/// #     Ok(())
/// # }
/// ```
impl Serialize for MoneyBag {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut balances = serializer.serialize_map(Some(self.len()))?;

        for money in self {
            balances.serialize_entry(&money.currency(), &Amount(money.amount()))?;
        }

        balances.end()
    }
}

/// Reads entries the way a bag accumulates them rather than insisting the
/// document already be in the shape a bag would have written: a balance of
/// zero leaves no currency behind, and a currency named twice is totaled.
/// Whichever way such a document is read, the position it describes is the
/// same.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Money, MoneyBag};
///
/// let ledger = r#"{"USD": "10.00", "EUR": "0.00"}"#;
/// let wallet: MoneyBag = serde_json::from_str(ledger)?;
///
/// assert_eq!(wallet, MoneyBag::from(Money::from_major(10, &Currency::USD)));
/// #
/// #     Ok(())
/// # }
/// ```
impl<'de> Deserialize<'de> for MoneyBag {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_map(MoneyBagVisitor)
    }
}

struct MoneyBagVisitor;

impl<'de> Visitor<'de> for MoneyBagVisitor {
    type Value = MoneyBag;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a balance per currency, keyed by ISO 4217 alphabetic code")
    }

    fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Self::Value, M::Error> {
        let mut bag = MoneyBag::new();

        while let Some((currency, Amount(amount))) = map.next_entry::<Currency, Amount>()? {
            bag = bag
                .checked_add(Money::from_decimal(amount, &currency))
                .map_err(|_| {
                    de::Error::custom(format!(
                        "the {currency} balance totals past what a decimal can hold"
                    ))
                })?;
        }

        Ok(bag)
    }
}

/// Writes the three-letter code, the same text [`Display`](std::fmt::Display)
/// writes.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::Currency;
///
/// assert_eq!(serde_json::to_string(&Currency::JPY)?, r#""JPY""#);
/// #
/// #     Ok(())
/// # }
/// ```
impl Serialize for Currency {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.alphabetic_code().as_str())
    }
}

/// Looks the code up in the ISO 4217 catalog, as
/// [`Currency::from_alphabetic_code`] does, so a code the standard leaves
/// unassigned is refused. Capitals only.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::Currency;
///
/// assert_eq!(serde_json::from_str::<Currency>(r#""JPY""#)?, Currency::JPY);
/// assert!(serde_json::from_str::<Currency>(r#""ZZZ""#).is_err());
/// #
/// #     Ok(())
/// # }
/// ```
impl<'de> Deserialize<'de> for Currency {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_str(CurrencyVisitor)
    }
}

struct CurrencyVisitor;

impl Visitor<'_> for CurrencyVisitor {
    type Value = Currency;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("the alphabetic code of a currency ISO 4217 assigns")
    }

    fn visit_str<E: de::Error>(self, code: &str) -> Result<Self::Value, E> {
        Currency::from_alphabetic_code(code)
            .ok_or_else(|| E::invalid_value(Unexpected::Str(code), &self))
    }
}

/// Writes the three letters, the same text [`Display`](std::fmt::Display)
/// writes.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::Currency;
///
/// assert_eq!(
///     serde_json::to_string(&Currency::JPY.alphabetic_code())?,
///     r#""JPY""#
/// );
/// #
/// #     Ok(())
/// # }
/// ```
impl Serialize for IsoAlphabeticCode {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

/// Takes any three capitals, as
/// [`TryFrom<&str>`](IsoAlphabeticCode::try_from) does, so a code ISO 4217
/// has yet to spend on a currency still reads.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::IsoAlphabeticCode;
///
/// let unassigned: IsoAlphabeticCode = serde_json::from_str(r#""ZZZ""#)?;
///
/// assert_eq!(unassigned.as_str(), "ZZZ");
/// assert!(serde_json::from_str::<IsoAlphabeticCode>(r#""usd""#).is_err());
/// #
/// #     Ok(())
/// # }
/// ```
impl<'de> Deserialize<'de> for IsoAlphabeticCode {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_str(IsoAlphabeticCodeVisitor)
    }
}

struct IsoAlphabeticCodeVisitor;

impl Visitor<'_> for IsoAlphabeticCodeVisitor {
    type Value = IsoAlphabeticCode;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("three capital letters, as ISO 4217 spells its codes")
    }

    fn visit_str<E: de::Error>(self, code: &str) -> Result<Self::Value, E> {
        IsoAlphabeticCode::try_from(code)
            .map_err(|_| E::invalid_value(Unexpected::Str(code), &self))
    }
}

/// Writes a plain integer, leaving the leading zeroes
/// [`Display`](std::fmt::Display) pads with to text.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::Currency;
///
/// assert_eq!(serde_json::to_string(&Currency::ALL.numeric_code())?, "8");
/// #
/// #     Ok(())
/// # }
/// ```
impl Serialize for IsoNumericCode {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_u32(self.value())
    }
}

/// Takes any integer of at most three digits, as
/// [`TryFrom<u32>`](IsoNumericCode::try_from) does, assigned or not.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, IsoNumericCode};
///
/// assert_eq!(
///     serde_json::from_str::<IsoNumericCode>("840")?,
///     Currency::USD.numeric_code()
/// );
/// assert!(serde_json::from_str::<IsoNumericCode>("1000").is_err());
/// #
/// #     Ok(())
/// # }
/// ```
impl<'de> Deserialize<'de> for IsoNumericCode {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_u32(IsoNumericCodeVisitor)
    }
}

struct IsoNumericCodeVisitor;

impl Visitor<'_> for IsoNumericCodeVisitor {
    type Value = IsoNumericCode;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("an integer of at most three digits, as ISO 4217 numbers currencies")
    }

    fn visit_u64<E: de::Error>(self, code: u64) -> Result<Self::Value, E> {
        u32::try_from(code)
            .ok()
            .and_then(|code| IsoNumericCode::try_from(code).ok())
            .ok_or_else(|| E::invalid_value(Unexpected::Unsigned(code), &self))
    }

    fn visit_i64<E: de::Error>(self, code: i64) -> Result<Self::Value, E> {
        match u64::try_from(code) {
            Ok(code) => self.visit_u64(code),
            Err(_) => Err(E::invalid_value(Unexpected::Signed(code), &self)),
        }
    }
}

/// Names each strategy in lower case, hyphenated: `"half-up"`,
/// `"half-down"`, `"half-even"`.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::RoundingMode;
///
/// assert_eq!(
///     serde_json::to_string(&RoundingMode::HalfEven)?,
///     r#""half-even""#
/// );
/// #
/// #     Ok(())
/// # }
/// ```
impl Serialize for RoundingMode {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(match self {
            RoundingMode::HalfUp => "half-up",
            RoundingMode::HalfDown => "half-down",
            RoundingMode::HalfEven => "half-even",
        })
    }
}

/// Reads those three names, and nothing else — the Rust spelling of a variant
/// is not a name this recognizes.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::RoundingMode;
///
/// assert_eq!(
///     serde_json::from_str::<RoundingMode>(r#""half-up""#)?,
///     RoundingMode::HalfUp
/// );
/// assert!(serde_json::from_str::<RoundingMode>(r#""HalfUp""#).is_err());
/// #
/// #     Ok(())
/// # }
/// ```
impl<'de> Deserialize<'de> for RoundingMode {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_str(RoundingModeVisitor)
    }
}

struct RoundingModeVisitor;

impl Visitor<'_> for RoundingModeVisitor {
    type Value = RoundingMode;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(r#""half-up", "half-down", or "half-even""#)
    }

    fn visit_str<E: de::Error>(self, name: &str) -> Result<Self::Value, E> {
        match name {
            "half-up" => Ok(RoundingMode::HalfUp),
            "half-down" => Ok(RoundingMode::HalfDown),
            "half-even" => Ok(RoundingMode::HalfEven),
            _ => Err(E::invalid_value(Unexpected::Str(name), &self)),
        }
    }
}

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

    #[test]
    fn money_round_trips_test() {
        let total = Money::from_minor(10475, &Currency::USD);
        let document = serde_json::to_string(&total).unwrap();

        assert_eq!(document, r#"{"amount":"104.75","currency":"USD"}"#);
        assert_eq!(serde_json::from_str::<Money>(&document).unwrap(), total);
    }

    #[test]
    fn money_keeps_a_scale_finer_than_the_currency_test() {
        let share = Money::from_decimal(dec!(1.005), &Currency::USD);
        let document = serde_json::to_string(&share).unwrap();

        assert_eq!(document, r#"{"amount":"1.005","currency":"USD"}"#);
        assert_eq!(
            serde_json::from_str::<Money>(&document)
                .unwrap()
                .amount()
                .scale(),
            3
        );
    }

    #[test]
    fn money_reads_numeric_amounts_test() {
        let whole: Money = serde_json::from_str(r#"{"amount": 104, "currency": "USD"}"#).unwrap();
        let fraction: Money =
            serde_json::from_str(r#"{"amount": 104.75, "currency": "USD"}"#).unwrap();

        assert_eq!(whole, Money::from_major(104, &Currency::USD));
        assert_eq!(fraction, Money::from_minor(10475, &Currency::USD));
    }

    #[test]
    fn money_reads_an_amount_in_scientific_notation_test() {
        let thousand: Money =
            serde_json::from_str(r#"{"amount": "1e3", "currency": "USD"}"#).unwrap();

        assert_eq!(thousand.amount(), dec!(1000));
    }

    #[test]
    fn money_reads_its_fields_in_either_order_test() {
        let reversed: Money =
            serde_json::from_str(r#"{"currency": "EUR", "amount": "12.00"}"#).unwrap();

        assert_eq!(reversed, Money::from_major(12, &Currency::EUR));
    }

    #[test]
    fn money_skips_unknown_fields_test() {
        let annotated: Money = serde_json::from_str(
            r#"{"amount": "1.00", "note": {"paid": true}, "currency": "USD"}"#,
        )
        .unwrap();

        assert_eq!(annotated, Money::from_major(1, &Currency::USD));
    }

    #[test]
    fn money_needs_both_fields_test() {
        let no_currency = serde_json::from_str::<Money>(r#"{"amount": "1.00"}"#).unwrap_err();
        let no_amount = serde_json::from_str::<Money>(r#"{"currency": "USD"}"#).unwrap_err();

        assert!(no_currency.to_string().contains("missing field `currency`"));
        assert!(no_amount.to_string().contains("missing field `amount`"));
    }

    #[test]
    fn money_refuses_a_repeated_field_test() {
        let repeated = serde_json::from_str::<Money>(
            r#"{"amount": "1.00", "amount": "2.00", "currency": "USD"}"#,
        )
        .unwrap_err();

        assert!(repeated.to_string().contains("duplicate field `amount`"));
    }

    #[test]
    fn every_currency_round_trips_test() {
        for currency in Currency::all() {
            let document = serde_json::to_string(currency).unwrap();

            assert_eq!(document, format!("\"{currency}\""));
            assert_eq!(
                &serde_json::from_str::<Currency>(&document).unwrap(),
                currency
            );
        }
    }

    #[test]
    fn unassigned_currency_code_is_refused_test() {
        let error = serde_json::from_str::<Currency>(r#""ZZZ""#).unwrap_err();

        assert!(
            error
                .to_string()
                .contains(r#"invalid value: string "ZZZ", expected the alphabetic code"#)
        );
    }

    #[test]
    fn alphabetic_code_admits_unassigned_codes_test() {
        let unassigned: IsoAlphabeticCode = serde_json::from_str(r#""ZZZ""#).unwrap();

        assert_eq!(unassigned.as_str(), "ZZZ");
        assert_eq!(serde_json::to_string(&unassigned).unwrap(), r#""ZZZ""#);
        assert!(serde_json::from_str::<IsoAlphabeticCode>(r#""usd""#).is_err());
        assert!(serde_json::from_str::<IsoAlphabeticCode>(r#""USDD""#).is_err());
    }

    #[test]
    fn numeric_code_round_trips_test() {
        for currency in Currency::all() {
            let code = currency.numeric_code();
            let document = serde_json::to_string(&code).unwrap();

            assert_eq!(document, code.value().to_string());
            assert_eq!(
                serde_json::from_str::<IsoNumericCode>(&document).unwrap(),
                code
            );
        }
    }

    #[test]
    fn numeric_code_outside_three_digits_is_refused_test() {
        let too_many = serde_json::from_str::<IsoNumericCode>("1000").unwrap_err();
        let negative = serde_json::from_str::<IsoNumericCode>("-1").unwrap_err();

        assert!(
            too_many
                .to_string()
                .contains("invalid value: integer `1000`")
        );
        assert!(negative.to_string().contains("invalid value: integer `-1`"));
    }

    #[test]
    fn rounding_mode_round_trips_test() {
        let modes = [
            (RoundingMode::HalfUp, r#""half-up""#),
            (RoundingMode::HalfDown, r#""half-down""#),
            (RoundingMode::HalfEven, r#""half-even""#),
        ];

        for (mode, document) in modes {
            assert_eq!(serde_json::to_string(&mode).unwrap(), document);
            assert_eq!(
                serde_json::from_str::<RoundingMode>(document).unwrap(),
                mode
            );
        }

        assert!(serde_json::from_str::<RoundingMode>(r#""HalfUp""#).is_err());
    }

    #[test]
    fn bag_round_trips_test() {
        let wallet: MoneyBag = [
            Money::from_major(30, &Currency::USD),
            Money::from_major(10, &Currency::EUR),
        ]
        .into_iter()
        .collect();
        let document = serde_json::to_string(&wallet).unwrap();

        assert_eq!(document, r#"{"EUR":"10.00","USD":"30.00"}"#);
        assert_eq!(serde_json::from_str::<MoneyBag>(&document).unwrap(), wallet);
    }

    #[test]
    fn empty_bag_round_trips_test() {
        let document = serde_json::to_string(&MoneyBag::new()).unwrap();

        assert_eq!(document, "{}");
        assert!(
            serde_json::from_str::<MoneyBag>(&document)
                .unwrap()
                .is_empty()
        );
    }

    #[test]
    fn bag_drops_a_zero_balance_test() {
        let wallet: MoneyBag = serde_json::from_str(r#"{"EUR": "0.00", "USD": "10.00"}"#).unwrap();

        assert_eq!(wallet.len(), 1);
        assert_eq!(
            wallet,
            MoneyBag::from(Money::from_major(10, &Currency::USD))
        );
    }

    #[test]
    fn bag_sums_a_repeated_currency_test() {
        let wallet: MoneyBag = serde_json::from_str(r#"{"USD": "10.00", "USD": "5.00"}"#).unwrap();

        assert_eq!(
            wallet.balance(&Currency::USD),
            Money::from_major(15, &Currency::USD)
        );
    }

    #[test]
    fn bag_reports_a_balance_it_cannot_hold_test() {
        let document = format!(r#"{{"USD": "{}", "USD": "1"}}"#, Decimal::MAX);
        let error = serde_json::from_str::<MoneyBag>(&document).unwrap_err();

        assert!(
            error
                .to_string()
                .contains("the USD balance totals past what a decimal can hold")
        );
    }

    #[test]
    fn bag_refuses_an_unassigned_currency_test() {
        assert!(serde_json::from_str::<MoneyBag>(r#"{"ZZZ": "1.00"}"#).is_err());
    }
}