Skip to main content

klirr_core/models/
invoice_number.rs

1use crate::prelude::*;
2
3/// A unique number for the invoice, e.g. `90`
4#[derive(
5    Clone, Debug, Default, Display, Serialize, Deserialize, PartialEq, Eq, Hash, From, Deref,
6)]
7#[serde(transparent)]
8pub struct InvoiceNumber(u16);
9
10impl std::str::FromStr for InvoiceNumber {
11    type Err = crate::prelude::Error;
12
13    /// Parses a string into an `InvoiceNumber`.
14    /// Returns an error if the string is not a valid number or is out of range.
15    /// # Errors
16    /// Returns an `Error::InvalidInvoiceNumberString` if the string cannot be
17    /// parsed into a valid `u16`.
18    ///
19    /// # Examples
20    /// ```
21    /// use klirr_core::prelude::*;
22    /// let invoice_number = InvoiceNumber::from_str("1234").unwrap();
23    /// assert_eq!(*invoice_number, 1234);
24    /// ```
25    fn from_str(s: &str) -> Result<Self> {
26        s.parse::<u16>()
27            .map(InvoiceNumber)
28            .map_err(|_| Error::InvalidInvoiceNumberString {
29                invalid_string: s.to_owned(),
30            })
31    }
32}
33
34impl HasSample for InvoiceNumber {
35    fn sample() -> Self {
36        Self::from(9876)
37    }
38    fn sample_other() -> Self {
39        Self::from(1234)
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    type Sut = InvoiceNumber;
48
49    #[test]
50    fn equality() {
51        assert_eq!(Sut::sample(), Sut::sample());
52        assert_eq!(Sut::sample_other(), Sut::sample_other());
53    }
54
55    #[test]
56    fn inequality() {
57        assert_ne!(Sut::sample(), Sut::sample_other());
58    }
59
60    #[test]
61    fn test_invoice_number_sample() {
62        let sample = Sut::sample();
63        assert_eq!(*sample, 9876);
64    }
65
66    #[test]
67    fn test_invoice_number_default_is_zero() {
68        let default = Sut::default();
69        assert_eq!(*default, 0);
70    }
71
72    #[test]
73    fn test_from_str_valid() {
74        let invoice_number = Sut::from_str("1234").unwrap();
75        assert_eq!(*invoice_number, 1234);
76    }
77
78    #[test]
79    fn test_from_str_invalid() {
80        let result = Sut::from_str("invalid");
81        assert!(
82            result.is_err(),
83            "Expected error for invalid string, got: {:?}",
84            result
85        );
86    }
87}