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
use std::fmt;

/// Represent a Split, which is basically a portion of a transaction
#[derive(Default, Debug, Clone)]
pub struct Split {
    category: String,
    memo: String,
    pub(in crate) amount: f64,
}

impl Split {
    pub fn new() -> Self {
        Split::default()
    }

    pub fn category(mut self, val: &str) -> Self {
        self.category = String::from(val);
        self
    }

    pub fn memo(mut self, val: &str) -> Self {
        self.memo = String::from(val);
        self
    }

    pub fn amount(mut self, val: f64) -> Self {
        self.amount = val;
        self
    }

    pub fn build(self) -> Split {
        Split {
            category: self.category,
            memo: self.memo,
            amount: self.amount,
        }
    }
}

impl fmt::Display for Split {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(
            f,
            "S{0}\nE{1}\n${2:.2}",
            self.category, self.memo, self.amount
        )
    }
}

#[cfg(test)]
mod split_test {
    use super::*;

    #[test]
    fn split_format() {
        let s = Split::new()
            .amount(-10.00)
            .category("testcat")
            .memo("testmemo")
            .build();
        let s2 = Split::new()
            .amount(-10.00)
            .category("testcat")
            .memo("")
            .build();

        assert_eq!(s.to_string(), "Stestcat\nEtestmemo\n$-10.00\n");
        assert_eq!(s2.to_string(), "Stestcat\nE\n$-10.00\n");
    }
}