envelope-cli 0.2.6

Terminal-based zero-based budgeting application
Documentation
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
//! Application state for the TUI
//!
//! The App struct holds all state needed for rendering and handling events.

use crate::config::paths::EnvelopePaths;
use crate::config::settings::Settings;
use crate::models::{AccountId, BudgetPeriod, CategoryGroupId, CategoryId, TransactionId};
use crate::storage::Storage;

use super::dialogs::account::AccountFormState;
use super::dialogs::adjustment::AdjustmentDialogState;
use super::dialogs::budget::BudgetDialogState;
use super::dialogs::bulk_categorize::BulkCategorizeState;
use super::dialogs::category::CategoryFormState;
use super::dialogs::group::GroupFormState;
use super::dialogs::income::IncomeFormState;
use super::dialogs::move_funds::MoveFundsState;
use super::dialogs::reconcile_start::ReconcileStartState;
use super::dialogs::transaction::TransactionFormState;
use super::dialogs::unlock_confirm::UnlockConfirmState;
use super::views::reconcile::ReconciliationState;

/// Which view is currently active
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ActiveView {
    #[default]
    Accounts,
    Register,
    Budget,
    Reports,
    Reconcile,
}

/// What to display in the budget header
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BudgetHeaderDisplay {
    /// Show Available to Assign / Overspent (default)
    #[default]
    AvailableToBudget,
    /// Show total checking account balance
    Checking,
    /// Show total savings account balance
    Savings,
    /// Show total credit card balance
    Credit,
    /// Show total cash balance
    Cash,
    /// Show total investment balance
    Investment,
    /// Show total line of credit balance
    LineOfCredit,
    /// Show total for other account types
    Other,
}

impl BudgetHeaderDisplay {
    /// Cycle to the next display mode
    pub fn next(self) -> Self {
        match self {
            Self::AvailableToBudget => Self::Checking,
            Self::Checking => Self::Savings,
            Self::Savings => Self::Credit,
            Self::Credit => Self::Cash,
            Self::Cash => Self::Investment,
            Self::Investment => Self::LineOfCredit,
            Self::LineOfCredit => Self::Other,
            Self::Other => Self::AvailableToBudget,
        }
    }

    /// Cycle to the previous display mode
    pub fn prev(self) -> Self {
        match self {
            Self::AvailableToBudget => Self::Other,
            Self::Checking => Self::AvailableToBudget,
            Self::Savings => Self::Checking,
            Self::Credit => Self::Savings,
            Self::Cash => Self::Credit,
            Self::Investment => Self::Cash,
            Self::LineOfCredit => Self::Investment,
            Self::Other => Self::LineOfCredit,
        }
    }

    /// Get the display label for this mode
    pub fn label(&self) -> &'static str {
        match self {
            Self::AvailableToBudget => "Available to Assign",
            Self::Checking => "Checking",
            Self::Savings => "Savings",
            Self::Credit => "Credit Cards",
            Self::Cash => "Cash",
            Self::Investment => "Investment",
            Self::LineOfCredit => "Line of Credit",
            Self::Other => "Other",
        }
    }
}

/// Which panel currently has focus
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FocusedPanel {
    #[default]
    Sidebar,
    Main,
}

/// Mode of input
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum InputMode {
    #[default]
    Normal,
    Editing,
    Command,
}

/// Currently active dialog (if any)
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ActiveDialog {
    #[default]
    None,
    AddTransaction,
    EditTransaction(TransactionId),
    AddAccount,
    EditAccount(AccountId),
    AddCategory,
    EditCategory(CategoryId),
    AddGroup,
    EditGroup(CategoryGroupId),
    MoveFunds,
    CommandPalette,
    Help,
    Confirm(String),
    BulkCategorize,
    ReconcileStart,
    UnlockConfirm(UnlockConfirmState),
    Adjustment,
    Budget,
    Income,
}

/// Main application state
pub struct App<'a> {
    /// The storage layer
    pub storage: &'a Storage,

    /// Application settings
    pub settings: &'a Settings,

    /// Paths configuration
    pub paths: &'a EnvelopePaths,

    /// Whether the app should quit
    pub should_quit: bool,

    /// Currently active view
    pub active_view: ActiveView,

    /// Which panel is focused
    pub focused_panel: FocusedPanel,

    /// Current input mode
    pub input_mode: InputMode,

    /// Currently active dialog
    pub active_dialog: ActiveDialog,

    /// Selected account (if any)
    pub selected_account: Option<AccountId>,

    /// Selected account index in the list
    pub selected_account_index: usize,

    /// Selected transaction (if any)
    pub selected_transaction: Option<TransactionId>,

    /// Selected transaction index in the register
    pub selected_transaction_index: usize,

    /// Selected category (for budget view)
    pub selected_category: Option<CategoryId>,

    /// Selected category index
    pub selected_category_index: usize,

    /// Current budget period being viewed
    pub current_period: BudgetPeriod,

    /// What to display in the budget header (toggle between ATB and account balances)
    pub budget_header_display: BudgetHeaderDisplay,

    /// Show archived accounts
    pub show_archived: bool,

    /// Multi-selection mode (for bulk operations)
    pub multi_select_mode: bool,

    /// Selected transaction IDs for bulk operations
    pub selected_transactions: Vec<TransactionId>,

    /// Scroll offset for the main view
    pub scroll_offset: usize,

    /// Status message to display
    pub status_message: Option<String>,

    /// Command palette input
    pub command_input: String,

    /// Filtered commands for palette
    pub command_results: Vec<usize>,

    /// Selected command index in palette
    pub selected_command_index: usize,

    /// Transaction form state
    pub transaction_form: TransactionFormState,

    /// Move funds dialog state
    pub move_funds_state: MoveFundsState,

    /// Bulk categorize dialog state
    pub bulk_categorize_state: BulkCategorizeState,

    /// Reconciliation view state
    pub reconciliation_state: ReconciliationState,

    /// Reconcile start dialog state
    pub reconcile_start_state: ReconcileStartState,

    /// Adjustment dialog state
    pub adjustment_dialog_state: AdjustmentDialogState,

    /// Account form dialog state
    pub account_form: AccountFormState,

    /// Category form dialog state
    pub category_form: CategoryFormState,

    /// Group form dialog state
    pub group_form: GroupFormState,

    /// Unified budget dialog state (period budget + target)
    pub budget_dialog_state: BudgetDialogState,

    /// Income form dialog state
    pub income_form: IncomeFormState,

    /// Pending 'g' keypress for Vim-style gg (go to top)
    pub pending_g: bool,
}

impl<'a> App<'a> {
    /// Create a new App instance
    pub fn new(storage: &'a Storage, settings: &'a Settings, paths: &'a EnvelopePaths) -> Self {
        // Initialize selected_account to first account (default view is Accounts)
        let selected_account = storage
            .accounts
            .get_active()
            .ok()
            .and_then(|accounts| accounts.first().map(|a| a.id));

        Self {
            storage,
            settings,
            paths,
            should_quit: false,
            active_view: ActiveView::default(),
            focused_panel: FocusedPanel::default(),
            input_mode: InputMode::default(),
            active_dialog: ActiveDialog::default(),
            selected_account,
            selected_account_index: 0,
            selected_transaction: None,
            selected_transaction_index: 0,
            selected_category: None,
            selected_category_index: 0,
            current_period: BudgetPeriod::current_month(),
            budget_header_display: BudgetHeaderDisplay::default(),
            show_archived: false,
            multi_select_mode: false,
            selected_transactions: Vec::new(),
            scroll_offset: 0,
            status_message: None,
            command_input: String::new(),
            command_results: Vec::new(),
            selected_command_index: 0,
            transaction_form: TransactionFormState::new(),
            move_funds_state: MoveFundsState::new(),
            bulk_categorize_state: BulkCategorizeState::new(),
            reconciliation_state: ReconciliationState::new(),
            reconcile_start_state: ReconcileStartState::new(),
            adjustment_dialog_state: AdjustmentDialogState::default(),
            account_form: AccountFormState::new(),
            category_form: CategoryFormState::new(),
            group_form: GroupFormState::new(),
            budget_dialog_state: BudgetDialogState::new(),
            income_form: IncomeFormState::new(),
            pending_g: false,
        }
    }

    /// Request to quit the application
    pub fn quit(&mut self) {
        self.should_quit = true;
    }

    /// Set a status message
    pub fn set_status(&mut self, message: impl Into<String>) {
        self.status_message = Some(message.into());
    }

    /// Clear the status message
    pub fn clear_status(&mut self) {
        self.status_message = None;
    }

    /// Switch to a different view
    pub fn switch_view(&mut self, view: ActiveView) {
        self.active_view = view;
        self.scroll_offset = 0;

        // Reset selection based on view
        match view {
            ActiveView::Accounts => {
                self.selected_account_index = 0;
                // Initialize selected_account to first account
                if let Ok(accounts) = self.storage.accounts.get_active() {
                    self.selected_account = accounts.first().map(|a| a.id);
                }
            }
            ActiveView::Register => {
                self.selected_transaction_index = 0;
                // Initialize selected_transaction to first transaction (sorted by date desc)
                if let Some(account_id) = self.selected_account {
                    let mut txns = self
                        .storage
                        .transactions
                        .get_by_account(account_id)
                        .unwrap_or_default();
                    txns.sort_by(|a, b| b.date.cmp(&a.date));
                    self.selected_transaction = txns.first().map(|t| t.id);
                }
            }
            ActiveView::Budget => {
                self.selected_category_index = 0;
                // Initialize selected_category to first category (in visual order)
                let groups = self.storage.categories.get_all_groups().unwrap_or_default();
                let all_categories = self
                    .storage
                    .categories
                    .get_all_categories()
                    .unwrap_or_default();
                // Find first category in visual order (first category in first group)
                for group in &groups {
                    if let Some(cat) = all_categories.iter().find(|c| c.group_id == group.id) {
                        self.selected_category = Some(cat.id);
                        break;
                    }
                }
            }
            ActiveView::Reports => {}
            ActiveView::Reconcile => {
                // Initialize reconciliation state if account is selected
                if let Some(account_id) = self.selected_account {
                    self.reconciliation_state.init_for_account(account_id);
                }
            }
        }
    }

    /// Toggle focus between sidebar and main panel
    pub fn toggle_panel_focus(&mut self) {
        self.focused_panel = match self.focused_panel {
            FocusedPanel::Sidebar => FocusedPanel::Main,
            FocusedPanel::Main => FocusedPanel::Sidebar,
        };
        // Initialize selection when switching to main panel
        if self.focused_panel == FocusedPanel::Main {
            self.ensure_selection_initialized();
        }
    }

    /// Ensure selection is initialized for the current view
    pub fn ensure_selection_initialized(&mut self) {
        match self.active_view {
            ActiveView::Accounts => {
                if self.selected_account.is_none() {
                    if let Ok(accounts) = self.storage.accounts.get_active() {
                        self.selected_account = accounts.first().map(|a| a.id);
                    }
                }
            }
            ActiveView::Register => {
                if self.selected_transaction.is_none() {
                    if let Some(account_id) = self.selected_account {
                        let mut txns = self
                            .storage
                            .transactions
                            .get_by_account(account_id)
                            .unwrap_or_default();
                        txns.sort_by(|a, b| b.date.cmp(&a.date));
                        self.selected_transaction = txns.first().map(|t| t.id);
                    }
                }
            }
            ActiveView::Budget => {
                if self.selected_category.is_none() {
                    let groups = self.storage.categories.get_all_groups().unwrap_or_default();
                    let all_categories = self
                        .storage
                        .categories
                        .get_all_categories()
                        .unwrap_or_default();
                    for group in &groups {
                        if let Some(cat) = all_categories.iter().find(|c| c.group_id == group.id) {
                            self.selected_category = Some(cat.id);
                            break;
                        }
                    }
                }
            }
            _ => {}
        }
    }

    /// Open a dialog
    pub fn open_dialog(&mut self, dialog: ActiveDialog) {
        self.active_dialog = dialog.clone();
        match &dialog {
            ActiveDialog::CommandPalette => {
                self.command_input.clear();
                self.input_mode = InputMode::Command;
            }
            ActiveDialog::AddTransaction => {
                // Reset form for new transaction
                self.transaction_form = TransactionFormState::new();
                self.transaction_form
                    .set_focus(super::dialogs::transaction::TransactionField::Date);
                self.input_mode = InputMode::Editing;
            }
            ActiveDialog::EditTransaction(txn_id) => {
                // Load transaction data into form
                if let Ok(Some(txn)) = self.storage.transactions.get(*txn_id) {
                    let categories: Vec<_> = self
                        .storage
                        .categories
                        .get_all_categories()
                        .unwrap_or_default()
                        .iter()
                        .map(|c| (c.id, c.name.clone()))
                        .collect();
                    self.transaction_form =
                        TransactionFormState::from_transaction(&txn, &categories);
                    self.transaction_form
                        .set_focus(super::dialogs::transaction::TransactionField::Date);
                }
                self.input_mode = InputMode::Editing;
            }
            ActiveDialog::AddAccount => {
                // Reset form for new account
                self.account_form = AccountFormState::new();
                self.account_form
                    .set_focus(super::dialogs::account::AccountField::Name);
                self.input_mode = InputMode::Editing;
            }
            ActiveDialog::EditAccount(account_id) => {
                // Load account data into form
                if let Ok(Some(account)) = self.storage.accounts.get(*account_id) {
                    self.account_form = AccountFormState::from_account(&account);
                    self.account_form
                        .set_focus(super::dialogs::account::AccountField::Name);
                }
                self.input_mode = InputMode::Editing;
            }
            ActiveDialog::AddCategory => {
                // Reset form for new category and load available groups
                self.category_form = CategoryFormState::new();
                let groups: Vec<_> = self
                    .storage
                    .categories
                    .get_all_groups()
                    .unwrap_or_default()
                    .into_iter()
                    .map(|g| (g.id, g.name))
                    .collect();
                self.category_form.init_with_groups(groups);
                self.input_mode = InputMode::Editing;
            }
            ActiveDialog::EditCategory(category_id) => {
                // Load category data into form
                if let Ok(Some(category)) = self.storage.categories.get_category(*category_id) {
                    let groups: Vec<_> = self
                        .storage
                        .categories
                        .get_all_groups()
                        .unwrap_or_default()
                        .into_iter()
                        .map(|g| (g.id, g.name.clone()))
                        .collect();
                    self.category_form.init_for_edit(&category, groups);
                }
                self.input_mode = InputMode::Editing;
            }
            ActiveDialog::AddGroup => {
                // Reset form for new group
                self.group_form = GroupFormState::new();
                self.input_mode = InputMode::Editing;
            }
            ActiveDialog::EditGroup(group_id) => {
                // Load group data into form for editing
                if let Ok(Some(group)) = self.storage.categories.get_group(*group_id) {
                    self.group_form = GroupFormState::new();
                    self.group_form.init_for_edit(&group);
                }
                self.input_mode = InputMode::Editing;
            }
            ActiveDialog::Budget => {
                // Initialize unified budget dialog for selected category
                if let Some(category_id) = self.selected_category {
                    if let Ok(Some(category)) = self.storage.categories.get_category(category_id) {
                        let budget_service = crate::services::BudgetService::new(self.storage);
                        let summary = budget_service
                            .get_category_summary(category_id, &self.current_period)
                            .unwrap_or_else(|_| {
                                crate::models::CategoryBudgetSummary::empty(category_id)
                            });
                        let suggested = budget_service
                            .get_suggested_budget_with_progress(category_id, &self.current_period)
                            .ok()
                            .flatten();
                        let existing_target = self
                            .storage
                            .targets
                            .get_for_category(category_id)
                            .ok()
                            .flatten();
                        self.budget_dialog_state.init_for_category(
                            category_id,
                            category.name,
                            summary.budgeted,
                            suggested,
                            existing_target.as_ref(),
                        );
                        self.input_mode = InputMode::Editing;
                    }
                }
            }
            ActiveDialog::Income => {
                // Initialize income dialog for current period
                self.income_form
                    .init_for_period(&self.current_period, self.storage);
                self.input_mode = InputMode::Editing;
            }
            _ => {}
        }
    }

    /// Close the current dialog
    pub fn close_dialog(&mut self) {
        self.active_dialog = ActiveDialog::None;
        self.input_mode = InputMode::Normal;
    }

    /// Check if a dialog is active
    pub fn has_dialog(&self) -> bool {
        !matches!(self.active_dialog, ActiveDialog::None)
    }

    /// Move selection up in the current view
    pub fn move_up(&mut self) {
        match self.focused_panel {
            FocusedPanel::Sidebar => {
                if self.selected_account_index > 0 {
                    self.selected_account_index -= 1;
                }
            }
            FocusedPanel::Main => match self.active_view {
                ActiveView::Register => {
                    if self.selected_transaction_index > 0 {
                        self.selected_transaction_index -= 1;
                    }
                }
                ActiveView::Budget => {
                    if self.selected_category_index > 0 {
                        self.selected_category_index -= 1;
                    }
                }
                _ => {}
            },
        }
    }

    /// Move selection down in the current view
    pub fn move_down(&mut self, max: usize) {
        match self.focused_panel {
            FocusedPanel::Sidebar => {
                if self.selected_account_index < max.saturating_sub(1) {
                    self.selected_account_index += 1;
                }
            }
            FocusedPanel::Main => match self.active_view {
                ActiveView::Register => {
                    if self.selected_transaction_index < max.saturating_sub(1) {
                        self.selected_transaction_index += 1;
                    }
                }
                ActiveView::Budget => {
                    if self.selected_category_index < max.saturating_sub(1) {
                        self.selected_category_index += 1;
                    }
                }
                _ => {}
            },
        }
    }

    /// Go to previous budget period
    pub fn prev_period(&mut self) {
        self.current_period = self.current_period.prev();
    }

    /// Go to next budget period
    pub fn next_period(&mut self) {
        self.current_period = self.current_period.next();
    }

    /// Toggle multi-select mode
    pub fn toggle_multi_select(&mut self) {
        self.multi_select_mode = !self.multi_select_mode;
        if !self.multi_select_mode {
            self.selected_transactions.clear();
        }
    }

    /// Toggle selection of current transaction in multi-select mode
    pub fn toggle_transaction_selection(&mut self) {
        if let Some(txn_id) = self.selected_transaction {
            if self.selected_transactions.contains(&txn_id) {
                self.selected_transactions.retain(|&id| id != txn_id);
            } else {
                self.selected_transactions.push(txn_id);
            }
        }
    }
}