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
//! Account service
//!
//! Provides business logic for account management including CRUD operations,
//! balance calculation, and validation.

use crate::audit::EntityType;
use crate::error::{EnvelopeError, EnvelopeResult};
use crate::models::{Account, AccountId, AccountType, Money, TransactionStatus};
use crate::storage::Storage;

/// Service for account management
pub struct AccountService<'a> {
    storage: &'a Storage,
}

/// Summary of an account with computed fields
#[derive(Debug, Clone)]
pub struct AccountSummary {
    pub account: Account,
    /// Current balance (starting balance + all transactions)
    pub balance: Money,
    /// Cleared balance (starting balance + cleared/reconciled transactions only)
    pub cleared_balance: Money,
    /// Number of uncleared transactions
    pub uncleared_count: usize,
}

impl<'a> AccountService<'a> {
    /// Create a new account service
    pub fn new(storage: &'a Storage) -> Self {
        Self { storage }
    }

    /// Create a new account
    pub fn create(
        &self,
        name: &str,
        account_type: AccountType,
        starting_balance: Money,
        on_budget: bool,
    ) -> EnvelopeResult<Account> {
        // Validate name is not empty
        let name = name.trim();
        if name.is_empty() {
            return Err(EnvelopeError::Validation(
                "Account name cannot be empty".into(),
            ));
        }

        // Check for duplicate name
        if self.storage.accounts.name_exists(name, None)? {
            return Err(EnvelopeError::Duplicate {
                entity_type: "Account",
                identifier: name.to_string(),
            });
        }

        // Create the account
        let mut account = Account::with_starting_balance(name, account_type, starting_balance);
        account.on_budget = on_budget;

        // Validate
        account
            .validate()
            .map_err(|e| EnvelopeError::Validation(e.to_string()))?;

        // Save to storage
        self.storage.accounts.upsert(account.clone())?;
        self.storage.accounts.save()?;

        // Audit log
        self.storage.log_create(
            EntityType::Account,
            account.id.to_string(),
            Some(account.name.clone()),
            &account,
        )?;

        Ok(account)
    }

    /// Get an account by ID
    pub fn get(&self, id: AccountId) -> EnvelopeResult<Option<Account>> {
        self.storage.accounts.get(id)
    }

    /// Get an account by name (case-insensitive)
    pub fn get_by_name(&self, name: &str) -> EnvelopeResult<Option<Account>> {
        self.storage.accounts.get_by_name(name)
    }

    /// Find an account by name or ID string
    pub fn find(&self, identifier: &str) -> EnvelopeResult<Option<Account>> {
        // Try by name first
        if let Some(account) = self.storage.accounts.get_by_name(identifier)? {
            return Ok(Some(account));
        }

        // Try parsing as ID
        if let Ok(id) = identifier.parse::<AccountId>() {
            return self.storage.accounts.get(id);
        }

        Ok(None)
    }

    /// Get all accounts
    pub fn list(&self, include_archived: bool) -> EnvelopeResult<Vec<Account>> {
        if include_archived {
            self.storage.accounts.get_all()
        } else {
            self.storage.accounts.get_active()
        }
    }

    /// Get all accounts with their computed balances
    pub fn list_with_balances(
        &self,
        include_archived: bool,
    ) -> EnvelopeResult<Vec<AccountSummary>> {
        let accounts = self.list(include_archived)?;
        let mut summaries = Vec::with_capacity(accounts.len());

        for account in accounts {
            let summary = self.get_summary(&account)?;
            summaries.push(summary);
        }

        Ok(summaries)
    }

    /// Get account summary with computed balances
    pub fn get_summary(&self, account: &Account) -> EnvelopeResult<AccountSummary> {
        let transactions = self.storage.transactions.get_by_account(account.id)?;

        let mut balance = account.starting_balance;
        let mut cleared_balance = account.starting_balance;
        let mut uncleared_count = 0;

        for txn in &transactions {
            balance += txn.amount;

            match txn.status {
                TransactionStatus::Cleared | TransactionStatus::Reconciled => {
                    cleared_balance += txn.amount;
                }
                TransactionStatus::Pending => {
                    uncleared_count += 1;
                }
            }
        }

        Ok(AccountSummary {
            account: account.clone(),
            balance,
            cleared_balance,
            uncleared_count,
        })
    }

    /// Calculate the current balance for an account
    pub fn calculate_balance(&self, account_id: AccountId) -> EnvelopeResult<Money> {
        let account = self
            .storage
            .accounts
            .get(account_id)?
            .ok_or_else(|| EnvelopeError::account_not_found(account_id.to_string()))?;

        let transactions = self.storage.transactions.get_by_account(account_id)?;
        let transaction_total: Money = transactions.iter().map(|t| t.amount).sum();

        Ok(account.starting_balance + transaction_total)
    }

    /// Calculate the cleared balance for an account
    pub fn calculate_cleared_balance(&self, account_id: AccountId) -> EnvelopeResult<Money> {
        let account = self
            .storage
            .accounts
            .get(account_id)?
            .ok_or_else(|| EnvelopeError::account_not_found(account_id.to_string()))?;

        let transactions = self.storage.transactions.get_by_account(account_id)?;
        let cleared_total: Money = transactions
            .iter()
            .filter(|t| {
                matches!(
                    t.status,
                    TransactionStatus::Cleared | TransactionStatus::Reconciled
                )
            })
            .map(|t| t.amount)
            .sum();

        Ok(account.starting_balance + cleared_total)
    }

    /// Update an account
    pub fn update(&self, id: AccountId, name: Option<&str>) -> EnvelopeResult<Account> {
        let mut account = self
            .storage
            .accounts
            .get(id)?
            .ok_or_else(|| EnvelopeError::account_not_found(id.to_string()))?;

        let before = account.clone();

        // Update name if provided
        if let Some(new_name) = name {
            let new_name = new_name.trim();
            if new_name.is_empty() {
                return Err(EnvelopeError::Validation(
                    "Account name cannot be empty".into(),
                ));
            }

            // Check for duplicate name (excluding self)
            if self.storage.accounts.name_exists(new_name, Some(id))? {
                return Err(EnvelopeError::Duplicate {
                    entity_type: "Account",
                    identifier: new_name.to_string(),
                });
            }

            account.name = new_name.to_string();
        }

        account.updated_at = chrono::Utc::now();

        // Validate
        account
            .validate()
            .map_err(|e| EnvelopeError::Validation(e.to_string()))?;

        // Save
        self.storage.accounts.upsert(account.clone())?;
        self.storage.accounts.save()?;

        // Audit log
        let diff = if before.name != account.name {
            Some(format!("name: {} -> {}", before.name, account.name))
        } else {
            None
        };

        self.storage.log_update(
            EntityType::Account,
            account.id.to_string(),
            Some(account.name.clone()),
            &before,
            &account,
            diff,
        )?;

        Ok(account)
    }

    /// Archive an account (soft delete)
    pub fn archive(&self, id: AccountId) -> EnvelopeResult<Account> {
        let mut account = self
            .storage
            .accounts
            .get(id)?
            .ok_or_else(|| EnvelopeError::account_not_found(id.to_string()))?;

        if account.archived {
            return Err(EnvelopeError::Validation(
                "Account is already archived".into(),
            ));
        }

        let before = account.clone();
        account.archive();

        // Save
        self.storage.accounts.upsert(account.clone())?;
        self.storage.accounts.save()?;

        // Audit log
        self.storage.log_update(
            EntityType::Account,
            account.id.to_string(),
            Some(account.name.clone()),
            &before,
            &account,
            Some("archived: false -> true".to_string()),
        )?;

        Ok(account)
    }

    /// Unarchive an account
    pub fn unarchive(&self, id: AccountId) -> EnvelopeResult<Account> {
        let mut account = self
            .storage
            .accounts
            .get(id)?
            .ok_or_else(|| EnvelopeError::account_not_found(id.to_string()))?;

        if !account.archived {
            return Err(EnvelopeError::Validation("Account is not archived".into()));
        }

        let before = account.clone();
        account.unarchive();

        // Save
        self.storage.accounts.upsert(account.clone())?;
        self.storage.accounts.save()?;

        // Audit log
        self.storage.log_update(
            EntityType::Account,
            account.id.to_string(),
            Some(account.name.clone()),
            &before,
            &account,
            Some("archived: true -> false".to_string()),
        )?;

        Ok(account)
    }

    /// Get total balance across all on-budget accounts
    pub fn total_on_budget_balance(&self) -> EnvelopeResult<Money> {
        let accounts = self.storage.accounts.get_active()?;
        let mut total = Money::zero();

        for account in accounts {
            if account.on_budget {
                total += self.calculate_balance(account.id)?;
            }
        }

        Ok(total)
    }

    /// Get total balance for all accounts of a specific type
    pub fn total_balance_by_type(&self, account_type: AccountType) -> EnvelopeResult<Money> {
        let accounts = self.storage.accounts.get_active()?;
        let mut total = Money::zero();

        for account in accounts {
            if account.account_type == account_type {
                total += self.calculate_balance(account.id)?;
            }
        }

        Ok(total)
    }

    /// Get count of accounts of a specific type
    pub fn count_by_type(&self, account_type: AccountType) -> EnvelopeResult<usize> {
        let accounts = self.storage.accounts.get_active()?;
        Ok(accounts
            .iter()
            .filter(|a| a.account_type == account_type)
            .count())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::paths::EnvelopePaths;
    use tempfile::TempDir;

    fn create_test_storage() -> (TempDir, Storage) {
        let temp_dir = TempDir::new().unwrap();
        let paths = EnvelopePaths::with_base_dir(temp_dir.path().to_path_buf());
        let mut storage = Storage::new(paths).unwrap();
        storage.load_all().unwrap();
        (temp_dir, storage)
    }

    #[test]
    fn test_create_account() {
        let (_temp_dir, storage) = create_test_storage();
        let service = AccountService::new(&storage);

        let account = service
            .create(
                "Checking",
                AccountType::Checking,
                Money::from_cents(100000),
                true,
            )
            .unwrap();

        assert_eq!(account.name, "Checking");
        assert_eq!(account.account_type, AccountType::Checking);
        assert_eq!(account.starting_balance.cents(), 100000);
        assert!(account.on_budget);
    }

    #[test]
    fn test_create_duplicate_name() {
        let (_temp_dir, storage) = create_test_storage();
        let service = AccountService::new(&storage);

        service
            .create("Checking", AccountType::Checking, Money::zero(), true)
            .unwrap();

        // Try to create another with same name
        let result = service.create("Checking", AccountType::Savings, Money::zero(), true);
        assert!(matches!(result, Err(EnvelopeError::Duplicate { .. })));
    }

    #[test]
    fn test_find_account() {
        let (_temp_dir, storage) = create_test_storage();
        let service = AccountService::new(&storage);

        let created = service
            .create("My Checking", AccountType::Checking, Money::zero(), true)
            .unwrap();

        // Find by name
        let found = service.find("My Checking").unwrap().unwrap();
        assert_eq!(found.id, created.id);

        // Case insensitive
        let found = service.find("my checking").unwrap().unwrap();
        assert_eq!(found.id, created.id);
    }

    #[test]
    fn test_list_accounts() {
        let (_temp_dir, storage) = create_test_storage();
        let service = AccountService::new(&storage);

        service
            .create("Account 1", AccountType::Checking, Money::zero(), true)
            .unwrap();
        service
            .create("Account 2", AccountType::Savings, Money::zero(), true)
            .unwrap();

        let accounts = service.list(false).unwrap();
        assert_eq!(accounts.len(), 2);
    }

    #[test]
    fn test_archive_account() {
        let (_temp_dir, storage) = create_test_storage();
        let service = AccountService::new(&storage);

        let account = service
            .create("Test", AccountType::Checking, Money::zero(), true)
            .unwrap();

        let archived = service.archive(account.id).unwrap();
        assert!(archived.archived);

        // Should not appear in active list
        let active = service.list(false).unwrap();
        assert!(active.is_empty());

        // Should appear in all list
        let all = service.list(true).unwrap();
        assert_eq!(all.len(), 1);
    }

    #[test]
    fn test_update_account() {
        let (_temp_dir, storage) = create_test_storage();
        let service = AccountService::new(&storage);

        let account = service
            .create("Old Name", AccountType::Checking, Money::zero(), true)
            .unwrap();

        let updated = service.update(account.id, Some("New Name")).unwrap();
        assert_eq!(updated.name, "New Name");
    }

    #[test]
    fn test_balance_calculation() {
        let (_temp_dir, storage) = create_test_storage();
        let service = AccountService::new(&storage);

        let account = service
            .create(
                "Test",
                AccountType::Checking,
                Money::from_cents(100000),
                true,
            )
            .unwrap();

        // Add some transactions
        use crate::models::Transaction;
        use chrono::NaiveDate;

        let txn1 = Transaction::new(
            account.id,
            NaiveDate::from_ymd_opt(2025, 1, 15).unwrap(),
            Money::from_cents(-5000),
        );
        storage.transactions.upsert(txn1).unwrap();

        let mut txn2 = Transaction::new(
            account.id,
            NaiveDate::from_ymd_opt(2025, 1, 16).unwrap(),
            Money::from_cents(20000),
        );
        txn2.clear();
        storage.transactions.upsert(txn2).unwrap();

        // Total balance = 100000 - 5000 + 20000 = 115000
        let balance = service.calculate_balance(account.id).unwrap();
        assert_eq!(balance.cents(), 115000);

        // Cleared balance = 100000 + 20000 = 120000 (pending txn not counted)
        let cleared = service.calculate_cleared_balance(account.id).unwrap();
        assert_eq!(cleared.cents(), 120000);
    }
}