summaryrefslogtreecommitdiff
path: root/src/tui/app.rs
blob: 3d413aa2eb8c4bce7077b3430e45c88f160515a3 (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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use std::collections::HashMap;
use chrono::{Datelike, Local, NaiveDate};
use crate::model::Transaction;
use crate::db::{get_recent_transactions_filtered, get_spending_by_category_filtered, 
    get_income_vs_expenses_filtered, get_budget_status, load_portfolios};
use crate::investment::Portfolio;
use super::event::{Event, EventHandler};
use super::ui;
use crossterm::event::KeyCode;
use super::CrosstermTerminal;
use ratatui::widgets::ListState;

#[derive(Debug, Clone, PartialEq)]
pub enum View {
    Dashboard,
    Transactions,
    Budgets,
    Investments,
}

#[derive(Debug, Clone)]
pub struct TimeRange {
    pub start: Option<String>,
    pub end: Option<String>,
    pub label: String,
}

impl TimeRange {
    pub fn current_month() -> Self {
        let now = Local::now();
        let start = NaiveDate::from_ymd_opt(now.year(), now.month(), 1)
            .unwrap()
            .format("%Y-%m-%d")
            .to_string();
        Self {
            start: Some(start),
            end: None,
            label: "This Month".to_string(),
        }
    }

    pub fn last_30_days() -> Self {
        let end = Local::now().naive_local().date();
        let start = end - chrono::Duration::days(30);
        Self {
            start: Some(start.format("%Y-%m-%d").to_string()),
            end: Some(end.format("%Y-%m-%d").to_string()),
            label: "Last 30 Days".to_string(),
        }
    }
}

pub struct App {
    pub current_view: View,
    pub time_range: TimeRange,
    pub transactions: Vec<Transaction>,
    pub spending_by_category: HashMap<String, f64>,
    pub income: f64,
    pub expenses: f64,
    pub budgets: Vec<(String, f64, f64, f64)>, // category, budget, spent, remaining
    pub portfolios: Vec<Portfolio>,
    pub selected_transaction_index: usize,
    pub search_query: String,
    pub show_help: bool,
    pub net_worth: f64,
    pub cash_balance: f64,
    pub investment_balance: f64,
    pub transaction_list_state: ListState,
}

impl App {
    pub async fn new() -> anyhow::Result<Self> {
        let time_range = TimeRange::current_month();
        let mut list_state = ListState::default();
        list_state.select(Some(0));
        
        let mut app = Self {
            current_view: View::Dashboard,
            time_range: time_range.clone(),
            transactions: Vec::new(),
            spending_by_category: HashMap::new(),
            income: 0.0,
            expenses: 0.0,
            budgets: Vec::new(),
            portfolios: Vec::new(),
            selected_transaction_index: 0,
            search_query: String::new(),
            show_help: false,
            net_worth: 0.0,
            cash_balance: 0.0,
            investment_balance: 0.0,
            transaction_list_state: list_state,
        };
        
        app.refresh_data().await?;
        Ok(app)
    }
    
    pub async fn refresh_data(&mut self) -> anyhow::Result<()> {
        // Load ALL transactions (no date filter for transaction view)
        self.transactions = get_recent_transactions_filtered(
            100000,  // Load up to 100k transactions
            None,    // No start date filter
            None     // No end date filter
        )?;
        
        // Load spending by category
        self.spending_by_category = get_spending_by_category_filtered(
            self.time_range.start.as_deref(),
            self.time_range.end.as_deref()
        )?;
        
        // Load income vs expenses
        let (income, expenses) = get_income_vs_expenses_filtered(
            self.time_range.start.as_deref(),
            self.time_range.end.as_deref()
        )?;
        self.income = income;
        self.expenses = expenses;
        
        // Load budgets
        self.budgets = get_budget_status()?;
        
        // Load investment data
        self.portfolios = load_portfolios()?;
        
        // Calculate net worth
        // TODO: This is a simplified calculation - actual cash balance would need
        // to track running balance from all transactions, not just current period
        self.cash_balance = income - expenses; // Simplified estimate
        self.investment_balance = self.portfolios.iter()
            .map(|p| p.total_market_value)
            .sum();
        self.net_worth = self.cash_balance + self.investment_balance;
        
        Ok(())
    }
    
    pub async fn run(&mut self, terminal: &mut CrosstermTerminal) -> anyhow::Result<()> {
        let event_handler = EventHandler::new(250);
        
        loop {
            terminal.draw(|f| ui::draw(f, self))?;
            
            match event_handler.next()? {
                Event::Key(key_event) => {
                    match key_event.code {
                        KeyCode::Char('q') => break,
                        KeyCode::Tab => self.next_view(),
                        KeyCode::BackTab => self.previous_view(),
                        KeyCode::Char('t') => self.current_view = View::Transactions,
                        KeyCode::Char('d') => self.current_view = View::Dashboard,
                        KeyCode::Char('b') => self.current_view = View::Budgets,
                        KeyCode::Char('i') => self.current_view = View::Investments,
                        KeyCode::Char('r') => self.refresh_data().await?,
                        KeyCode::Char('?') => self.show_help = !self.show_help,
                        KeyCode::Up | KeyCode::Char('k') => self.move_selection_up(),
                        KeyCode::Down | KeyCode::Char('j') => self.move_selection_down(),
                        KeyCode::Char('/') => {
                            // Start search mode
                            self.search_query.clear();
                        }
                        _ => {}
                    }
                }
                Event::Tick => {}
            }
        }
        
        Ok(())
    }
    
    fn next_view(&mut self) {
        self.current_view = match self.current_view {
            View::Dashboard => View::Transactions,
            View::Transactions => View::Budgets,
            View::Budgets => View::Investments,
            View::Investments => View::Dashboard,
        };
    }
    
    fn previous_view(&mut self) {
        self.current_view = match self.current_view {
            View::Dashboard => View::Investments,
            View::Transactions => View::Dashboard,
            View::Budgets => View::Transactions,
            View::Investments => View::Budgets,
        };
    }
    
    fn move_selection_up(&mut self) {
        if self.current_view == View::Transactions && self.selected_transaction_index > 0 {
            self.selected_transaction_index -= 1;
            self.transaction_list_state.select(Some(self.selected_transaction_index));
        }
    }
    
    fn move_selection_down(&mut self) {
        if self.current_view == View::Transactions 
            && self.selected_transaction_index < self.transactions.len().saturating_sub(1) {
            self.selected_transaction_index += 1;
            self.transaction_list_state.select(Some(self.selected_transaction_index));
        }
    }
}