aboutsummaryrefslogtreecommitdiffstats
path: root/src/ynab/budget.rs
blob: e3275bb0c3e9bf9b481c0b75d525880838cbf1b0 (plain) (blame)
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
use snafu::{OptionExt, ResultExt};

#[derive(Debug, snafu::Snafu)]
pub enum Error {
    #[snafu(display("couldn't get default budget: {}", source))]
    GetBudget { source: super::client::Error },

    #[snafu(display("couldn't update transactions: {}", source))]
    UpdateTransactions { source: super::client::Error },

    #[snafu(display("couldn't find the reimbursables category"))]
    FindReimbursablesCategory,
}

pub type Result<T> = std::result::Result<T, Error>;

pub struct Budget {
    client: super::client::Client,
    id: String,
    name: String,
    reimbursables: Vec<super::transaction::Transaction>,
}

impl Budget {
    pub fn new(key: &str) -> Result<Self> {
        let client = super::client::Client::new(key);
        let budget = client.default_budget().context(GetBudget)?;
        let reimbursables = Self::get_reimbursables(&budget)?;
        let budget = Self {
            client,
            id: budget.id.clone(),
            name: budget.name.clone(),
            reimbursables,
        };
        budget.check();
        Ok(budget)
    }

    #[must_use]
    pub fn refresh(&mut self) -> Result<()> {
        let budget = self.client.default_budget().context(GetBudget)?;
        self.id = budget.id.clone();
        self.name = budget.name.clone();
        self.reimbursables = Self::get_reimbursables(&budget)?;
        self.check();
        Ok(())
    }

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

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

    pub fn reimbursables(&self) -> &[super::transaction::Transaction] {
        &self.reimbursables
    }

    #[must_use]
    pub fn reconcile_transactions(
        &self,
        txns: &[&super::transaction::Transaction],
    ) -> Result<()> {
        let mut to_update =
            ynab_api::models::UpdateTransactionsWrapper::new();
        to_update.transactions = Some(
            txns.iter()
                .map(|t| {
                    let mut ut = t.to_update_transaction();
                    ut.flag_color = Some("green".to_string());
                    ut
                })
                .collect(),
        );
        self.client
            .update_transactions(&self.id, to_update)
            .context(UpdateTransactions)?;
        Ok(())
    }

    fn get_reimbursables(
        budget: &ynab_api::models::BudgetDetail,
    ) -> Result<Vec<super::transaction::Transaction>> {
        let reimbursables_id = budget
            .categories
            .as_ref()
            .and_then(|categories| {
                categories
                    .iter()
                    .find(|c| c.name == "Reimbursables")
                    .map(|c| c.id.clone())
            })
            .context(FindReimbursablesCategory)?;

        let mut payee_map = std::collections::HashMap::new();
        if let Some(payees) = &budget.payees {
            for p in payees {
                payee_map.insert(p.id.clone(), p.name.clone());
            }
        }
        let payee_map = payee_map;

        let mut account_map = std::collections::HashMap::new();
        if let Some(accounts) = &budget.accounts {
            for a in accounts {
                account_map.insert(a.id.clone(), a.name.clone());
            }
        }
        let account_map = account_map;

        let mut reimbursables = vec![];

        let mut transaction_map = std::collections::HashMap::new();
        if let Some(transactions) = &budget.transactions {
            for t in transactions {
                transaction_map.insert(t.id.clone(), t);

                if let Some(category_id) = &t.category_id {
                    if category_id != &reimbursables_id {
                        continue;
                    }
                } else {
                    continue;
                }

                let payee = t
                    .payee_id
                    .iter()
                    .map(|payee_id| payee_map.get(payee_id).cloned())
                    .next()
                    .unwrap_or(None);
                let account = account_map.get(&t.account_id).cloned();

                let mut txn =
                    super::transaction::Transaction::from_transaction(t);
                txn.payee = payee;
                txn.account = account;
                reimbursables.push(txn);
            }
        }
        let transaction_map = transaction_map;

        if let Some(subtransactions) = &budget.subtransactions {
            for st in subtransactions {
                if let Some(category_id) = &st.category_id {
                    if category_id != &reimbursables_id {
                        continue;
                    }
                } else {
                    continue;
                }

                let t = transaction_map[&st.transaction_id];
                let payee = st
                    .payee_id
                    .iter()
                    .map(|payee_id| payee_map.get(payee_id).cloned())
                    .next()
                    .unwrap_or_else(|| {
                        t.payee_id
                            .iter()
                            .map(|payee_id| payee_map.get(payee_id).cloned())
                            .next()
                            .unwrap_or(None)
                    });
                let account = account_map.get(&t.account_id).cloned();

                let mut txn =
                    super::transaction::Transaction::from_sub_transaction(
                        t, st,
                    );
                txn.payee = payee;
                txn.account = account;
                reimbursables.push(txn);
            }
        }

        reimbursables.sort_by_cached_key(|t| t.date.clone());
        Ok(reimbursables)
    }

    fn check(&self) {
        self.check_reconciled();
        self.check_has_inflows();
    }

    fn check_reconciled(&self) {
        let reconciled_amount: i64 = self
            .reimbursables()
            .iter()
            .filter(|t| t.reimbursed)
            .map(|t| t.amount)
            .sum();
        if reconciled_amount != 0 {
            eprintln!(
                "reconciled reimbursables don't sum to $0.00: ${}",
                crate::ynab::format_amount(reconciled_amount)
            );
            std::process::exit(1);
        }
    }

    fn check_has_inflows(&self) {
        let txns = self
            .reimbursables()
            .iter()
            .filter(|t| !t.reimbursed && t.amount > 0)
            .count();
        if txns == 0 {
            eprintln!("no transactions to reconcile");
            std::process::exit(1);
        }
    }
}