summaryrefslogtreecommitdiff
path: root/src/qif.rs
blob: 46b2bc39d1ee0c60c88b4a85575c7c8614671b36 (plain)
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
use std::fmt;

pub struct QifFile {
    header: String,
    entries: Vec<QifEntry>
}

impl QifFile {
    pub fn new(header: String) -> QifFile {
        QifFile {
            header: header,
            entries: Vec::new()
        }
    }

    pub fn append_non_empty(&mut self, entry: QifEntry) {
        if !entry.is_empty() {
            self.entries.push(entry);
        }
    }
    
    pub fn append(&mut self, entry: QifEntry) {
        self.entries.push(entry);
    }
}

impl fmt::Display for QifFile {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut hat_separated = String::new();

        for entry in &self.entries {
            hat_separated.push_str("\n");
            hat_separated.push_str(&entry.to_string());
            hat_separated.push_str("\n^");
        }

        write!(f, "{}{}", self.header, hat_separated)
    }
}

pub struct QifEntry {
    date: String,
    amount: String,
    description: String
}

const DATE_PREFIX: &str = "D";
const AMOUNT_PREFIX: &str = "T";
const DESCRIPTION_PREFIX: &str = "M";

impl QifEntry {
    pub fn new(lines: &Vec<String>) -> QifEntry {
        let date = lines.iter().find(|l| l.starts_with(DATE_PREFIX)).expect("No date");
        let amount = lines.iter().find(|l| l.starts_with(AMOUNT_PREFIX)).expect("No amount");
        let description = lines.iter().find(|l| l.starts_with(DESCRIPTION_PREFIX)).expect("No description");
        QifEntry {
            date: date.clone(),
            amount: amount.clone(),
            description: description.clone()
        }
    }

    pub fn is_empty(&self) -> bool {
        self.amount == String::from("T0")
    }

    pub fn clean_description(&self) -> String {
        self.description.clone()
    }
}

impl fmt::Display for QifEntry {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}\n{}\n{}", self.date, self.amount, self.clean_description())
    }
}