summaryrefslogtreecommitdiff
path: root/src/qif.rs
blob: f93dc66161032d5b3aa645ab23f1e8119a10b5c4 (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
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
use lazy_static::lazy_static;
use regex::Regex;
use std::error::Error;
use std::fmt;
use std::result::Result;

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

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

    pub fn push(&mut self, entry: QifEntry) {
        if !entry.is_empty() {
            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>) -> Result<QifEntry, QifParsingError> {
        let date = lines.iter().find(|l| l.starts_with(DATE_PREFIX));
        let amount = lines.iter().find(|l| l.starts_with(AMOUNT_PREFIX));
        let description = lines.iter().find(|l| l.starts_with(DESCRIPTION_PREFIX));
        match (date, amount, description) {
            (Some(date), Some(amount), Some(description)) => Ok(QifEntry {
                date: date.chars().skip(1).collect(),
                amount: amount.chars().skip(1).collect(),
                description: description.chars().skip(1).collect(),
            }),
            (None, _, _) => Err(QifParsingError::MissingDate),
            (_, None, _) => Err(QifParsingError::MissingAmount),
            (_, _, None) => Err(QifParsingError::MissingDescription),
        }
    }

    pub fn is_empty(&self) -> bool {
        &self.amount == "0" || &self.amount == "0.00"
    }

    pub fn clean_description(&self) -> String {
        let mut new_description = self.description.clone();
        for algorithm in [
            remove_date,
            remove_card_number,
            replace_common,
            remove_payment_provider,
        ] {
            new_description = algorithm(&new_description);
        }
        new_description
    }
}

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

fn remove_date(text: &str) -> String {
    lazy_static! {
        static ref DATE_REGEX: Regex =
            Regex::new(r"(?i)\d{2} (JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)( \d{4})?")
                .unwrap();
    }
    DATE_REGEX.replace_all(text, "").trim().to_string()
}

fn remove_card_number(text: &str) -> String {
    lazy_static! {
        static ref CARD_NUM_REGEX: Regex = Regex::new(r"(\d{6}\*+\d{4}|\d{16})").unwrap();
    }
    CARD_NUM_REGEX.replace_all(text, "").trim().to_string()
}

fn remove_payment_provider(text: &str) -> String {
    lazy_static! {
        static ref PURCH_REGEX: Regex =
            Regex::new(r"(?i)^(purch( payfast\*)?|pp +\*|c\*|yoco +\*|ikh\*)").unwrap();
    }
    PURCH_REGEX.replace_all(text, "").trim().to_string()
}

fn replace_common(text: &str) -> String {
    lazy_static! {
        static ref COMMON_NAMES: Vec<(Regex, &'static str)> = vec!(
            (r"(?i)(pick n pay|pnp)", "Pick n Pay"),
            (r"(?i)checkers", "Checkers"),
            (r"(?i)WOOLWORTHS", "Woolworths"),
            (r"(?i)clicks", "Clicks"),
            (r"(?i)dischem", "Dischem"),
            (r"(?i)spar", "Spar"),
            (r"(?i)(disc memb|disc prem)", "Discovery medical aid"),
            (r"(?i)10XRA", "10X Retirement Annuity"),
            (r"(?i)NEDABF/MFC", "Nedbank MFC"),
            (r"(?i)SARSEFLNG", "SARS Efiling"),
            (r"(?i)Crazy store", "Crazy Store"),
            (r"^PNA", "PNA"),
            (r"^BWH", "Builders Warehouse"),
            (r"^MCD ", "McDonalds"),
            (r"^MRP ", "Mr Price"),
            (r"NakedIn", "Naked Insurance"),
            (r"(?i)sahl", "SA Home Loans"),
            (r"(?i)gautrain", "Gautrain"),
            (r"(?i)BYC DEBIT", "TO SAVINGS POCKET"),
            (r"(?i)AFRIHOST", "Afrihost"),
            (r"(?i)DIALDIRECT", "Dialdirect"),
            (r"(?i)STEERS", "Steers"),
            (r"(?i)CELL C", "Cell C"),
            (r"(?i)ELECTRICITY", "Electricity"),
            (r"(?i)(COUNTRY VIEW|STAR STOP|Shell|Sasol|Engen)", "Petrol"),
            (r"(?i)kung ?-?fu", "Kungfu Kitchen"),
            (r"(?i)^atm cash", "Cash"),
            (r"(?i)DRS CL & ME LA", "Medipark 24")
        )
        .into_iter()
        .map(|(from, to)| (Regex::new(from).unwrap(), to))
        .collect();
    }
    COMMON_NAMES
        .iter()
        .filter_map(|(rule, replacement)| {
            if rule.is_match(text) {
                Some(replacement.to_string())
            } else {
                None
            }
        })
        .next()
        .unwrap_or_else(|| text.to_owned())
        .to_string()
}

#[derive(Debug)]
pub enum QifParsingError {
    MissingDate,
    MissingAmount,
    MissingDescription,
}

impl fmt::Display for QifParsingError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl Error for QifParsingError {}