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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
//! Budget service
//!
//! Provides business logic for budget management including allocation,
//! Available to Budget calculation, and budget overview.

use crate::audit::EntityType;
use crate::error::{EnvelopeError, EnvelopeResult};
use crate::models::{
    BudgetAllocation, BudgetPeriod, BudgetTarget, BudgetTargetId, CategoryBudgetSummary,
    CategoryId, Money, TargetCadence,
};
use crate::services::CategoryService;
use crate::storage::Storage;
use chrono::Datelike;

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

/// Budget overview for a period
#[derive(Debug, Clone)]
pub struct BudgetOverview {
    pub period: BudgetPeriod,
    pub total_budgeted: Money,
    pub total_activity: Money,
    pub total_available: Money,
    pub available_to_budget: Money,
    pub categories: Vec<CategoryBudgetSummary>,
    /// Expected income for this period (if set)
    pub expected_income: Option<Money>,
    /// Amount over expected income (Some if budgeted > expected, None otherwise)
    pub over_budget_amount: Option<Money>,
}

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

    /// Assign funds to a category for a period
    pub fn assign_to_category(
        &self,
        category_id: CategoryId,
        period: &BudgetPeriod,
        amount: Money,
    ) -> EnvelopeResult<BudgetAllocation> {
        // Verify category exists
        let category = self
            .storage
            .categories
            .get_category(category_id)?
            .ok_or_else(|| EnvelopeError::category_not_found(category_id.to_string()))?;

        // Get or create allocation
        let mut allocation = self.storage.budget.get_or_default(category_id, period)?;
        let before = allocation.clone();

        allocation.set_budgeted(amount);

        // Validate
        allocation
            .validate()
            .map_err(|e| EnvelopeError::Budget(e.to_string()))?;

        // Save
        self.storage.budget.upsert(allocation.clone())?;
        self.storage.budget.save()?;

        // Audit
        self.storage.log_update(
            EntityType::BudgetAllocation,
            format!("{}:{}", category_id, period),
            Some(category.name),
            &before,
            &allocation,
            Some(format!(
                "budgeted: {} -> {}",
                before.budgeted, allocation.budgeted
            )),
        )?;

        Ok(allocation)
    }

    /// Add to a category's budget for a period
    pub fn add_to_category(
        &self,
        category_id: CategoryId,
        period: &BudgetPeriod,
        amount: Money,
    ) -> EnvelopeResult<BudgetAllocation> {
        // Verify category exists
        let category = self
            .storage
            .categories
            .get_category(category_id)?
            .ok_or_else(|| EnvelopeError::category_not_found(category_id.to_string()))?;

        // Get or create allocation
        let mut allocation = self.storage.budget.get_or_default(category_id, period)?;
        let before = allocation.clone();

        allocation.add_budgeted(amount);

        // Validate (check not negative)
        allocation
            .validate()
            .map_err(|e| EnvelopeError::Budget(e.to_string()))?;

        // Save
        self.storage.budget.upsert(allocation.clone())?;
        self.storage.budget.save()?;

        // Audit
        self.storage.log_update(
            EntityType::BudgetAllocation,
            format!("{}:{}", category_id, period),
            Some(category.name),
            &before,
            &allocation,
            Some(format!(
                "budgeted: {} -> {} (+{})",
                before.budgeted, allocation.budgeted, amount
            )),
        )?;

        Ok(allocation)
    }

    /// Move funds between categories for a period
    pub fn move_between_categories(
        &self,
        from_category_id: CategoryId,
        to_category_id: CategoryId,
        period: &BudgetPeriod,
        amount: Money,
    ) -> EnvelopeResult<()> {
        if amount.is_zero() {
            return Ok(());
        }

        if amount.is_negative() {
            return Err(EnvelopeError::Budget(
                "Amount to move must be positive".into(),
            ));
        }

        // Verify both categories exist
        let from_category = self
            .storage
            .categories
            .get_category(from_category_id)?
            .ok_or_else(|| EnvelopeError::category_not_found(from_category_id.to_string()))?;

        let to_category = self
            .storage
            .categories
            .get_category(to_category_id)?
            .ok_or_else(|| EnvelopeError::category_not_found(to_category_id.to_string()))?;

        // Get current allocations
        let mut from_alloc = self
            .storage
            .budget
            .get_or_default(from_category_id, period)?;
        let mut to_alloc = self.storage.budget.get_or_default(to_category_id, period)?;

        let from_before = from_alloc.clone();
        let to_before = to_alloc.clone();

        // Check if from has enough budgeted
        if from_alloc.budgeted < amount {
            return Err(EnvelopeError::InsufficientFunds {
                category: from_category.name.clone(),
                needed: amount.cents(),
                available: from_alloc.budgeted.cents(),
            });
        }

        // Move funds
        from_alloc.add_budgeted(-amount);
        to_alloc.add_budgeted(amount);

        // Validate both
        from_alloc
            .validate()
            .map_err(|e| EnvelopeError::Budget(e.to_string()))?;
        to_alloc
            .validate()
            .map_err(|e| EnvelopeError::Budget(e.to_string()))?;

        // Save both
        self.storage.budget.upsert(from_alloc.clone())?;
        self.storage.budget.upsert(to_alloc.clone())?;
        self.storage.budget.save()?;

        // Audit
        self.storage.log_update(
            EntityType::BudgetAllocation,
            format!("{}:{}", from_category_id, period),
            Some(from_category.name.clone()),
            &from_before,
            &from_alloc,
            Some(format!("moved {} to '{}'", amount, to_category.name)),
        )?;

        self.storage.log_update(
            EntityType::BudgetAllocation,
            format!("{}:{}", to_category_id, period),
            Some(to_category.name.clone()),
            &to_before,
            &to_alloc,
            Some(format!("received {} from '{}'", amount, from_category.name)),
        )?;

        Ok(())
    }

    /// Get the allocation for a category in a period
    pub fn get_allocation(
        &self,
        category_id: CategoryId,
        period: &BudgetPeriod,
    ) -> EnvelopeResult<BudgetAllocation> {
        self.storage.budget.get_or_default(category_id, period)
    }

    /// Get budget summary for a category in a period
    pub fn get_category_summary(
        &self,
        category_id: CategoryId,
        period: &BudgetPeriod,
    ) -> EnvelopeResult<CategoryBudgetSummary> {
        let allocation = self.storage.budget.get_or_default(category_id, period)?;

        // Calculate activity (sum of transactions in this category for this period)
        let activity = self.calculate_category_activity(category_id, period)?;

        Ok(CategoryBudgetSummary::from_allocation(
            &allocation,
            activity,
        ))
    }

    /// Calculate activity (spending) for a category in a period
    pub fn calculate_category_activity(
        &self,
        category_id: CategoryId,
        period: &BudgetPeriod,
    ) -> EnvelopeResult<Money> {
        let transactions = self.storage.transactions.get_by_category(category_id)?;

        // Filter to transactions within the period
        let period_start = period.start_date();
        let period_end = period.end_date();

        let activity: Money = transactions
            .iter()
            .filter(|t| t.date >= period_start && t.date <= period_end)
            .map(|t| {
                // Check if this is a split transaction
                if t.is_split() {
                    // Sum only the splits for this category
                    t.splits
                        .iter()
                        .filter(|s| s.category_id == category_id)
                        .map(|s| s.amount)
                        .sum()
                } else {
                    t.amount
                }
            })
            .sum();

        Ok(activity)
    }

    /// Calculate total income for a period (sum of all positive transactions)
    pub fn calculate_income_for_period(&self, period: &BudgetPeriod) -> EnvelopeResult<Money> {
        let period_start = period.start_date();
        let period_end = period.end_date();

        let transactions = self
            .storage
            .transactions
            .get_by_date_range(period_start, period_end)?;

        let income: Money = transactions
            .iter()
            .filter(|t| t.amount.is_positive())
            .map(|t| t.amount)
            .sum();

        Ok(income)
    }

    /// Calculate Available to Budget for a period
    ///
    /// Available to Budget = Total On-Budget Balances - Total Budgeted for current + prior periods
    pub fn get_available_to_budget(&self, period: &BudgetPeriod) -> EnvelopeResult<Money> {
        // Get total balance across all on-budget accounts
        let account_service = crate::services::AccountService::new(self.storage);
        let total_balance = account_service.total_on_budget_balance()?;

        // Get total budgeted for this period
        let allocations = self.storage.budget.get_for_period(period)?;
        let total_budgeted: Money = allocations.iter().map(|a| a.budgeted).sum();

        Ok(total_balance - total_budgeted)
    }

    /// Get expected income for a period (if set)
    pub fn get_expected_income(&self, period: &BudgetPeriod) -> Option<Money> {
        self.storage
            .income
            .get_for_period(period)
            .map(|e| e.expected_amount)
    }

    /// Check if total budgeted exceeds expected income
    ///
    /// Returns Some(overage_amount) if over budget, None otherwise
    pub fn is_over_expected_income(&self, period: &BudgetPeriod) -> EnvelopeResult<Option<Money>> {
        let expected = match self.get_expected_income(period) {
            Some(e) => e,
            None => return Ok(None), // No expectation set
        };

        let allocations = self.storage.budget.get_for_period(period)?;
        let total_budgeted: Money = allocations.iter().map(|a| a.budgeted).sum();

        if total_budgeted > expected {
            Ok(Some(total_budgeted - expected)) // Return overage amount
        } else {
            Ok(None)
        }
    }

    /// Get remaining amount that can be budgeted based on expected income
    ///
    /// Returns the difference between expected income and total budgeted.
    /// Positive = room to budget more, Negative = over-budgeted
    pub fn get_remaining_to_budget_from_income(
        &self,
        period: &BudgetPeriod,
    ) -> EnvelopeResult<Option<Money>> {
        let expected = match self.get_expected_income(period) {
            Some(e) => e,
            None => return Ok(None),
        };

        let allocations = self.storage.budget.get_for_period(period)?;
        let total_budgeted: Money = allocations.iter().map(|a| a.budgeted).sum();

        Ok(Some(expected - total_budgeted))
    }

    /// Get a complete budget overview for a period
    pub fn get_budget_overview(&self, period: &BudgetPeriod) -> EnvelopeResult<BudgetOverview> {
        let category_service = CategoryService::new(self.storage);
        let categories = category_service.list_categories()?;

        let mut summaries = Vec::with_capacity(categories.len());
        let mut total_budgeted = Money::zero();
        let mut total_activity = Money::zero();
        let mut total_available = Money::zero();

        for category in &categories {
            let summary = self.get_category_summary(category.id, period)?;
            total_budgeted += summary.budgeted;
            total_activity += summary.activity;
            total_available += summary.available;
            summaries.push(summary);
        }

        let available_to_budget = self.get_available_to_budget(period)?;

        // Get expected income and calculate over-budget amount
        let expected_income = self.get_expected_income(period);
        let over_budget_amount = expected_income.and_then(|expected| {
            if total_budgeted > expected {
                Some(total_budgeted - expected)
            } else {
                None
            }
        });

        Ok(BudgetOverview {
            period: period.clone(),
            total_budgeted,
            total_activity,
            total_available,
            available_to_budget,
            categories: summaries,
            expected_income,
            over_budget_amount,
        })
    }

    /// Get all allocations for a category (history)
    pub fn get_allocation_history(
        &self,
        category_id: CategoryId,
    ) -> EnvelopeResult<Vec<BudgetAllocation>> {
        self.storage.budget.get_for_category(category_id)
    }

    /// Calculate the cumulative amount budgeted to a category across all periods
    /// up to and including the specified period.
    ///
    /// This is useful for ByDate targets where progress should reflect total
    /// budgeted over time, not just current available balance.
    pub fn calculate_cumulative_budgeted(
        &self,
        category_id: CategoryId,
        up_to_period: &BudgetPeriod,
    ) -> EnvelopeResult<Money> {
        let allocations = self.storage.budget.get_for_category(category_id)?;

        let total: Money = allocations
            .iter()
            .filter(|a| &a.period <= up_to_period)
            .map(|a| a.budgeted)
            .sum();

        Ok(total)
    }

    /// Calculate the cumulative amount paid/spent from a category across all time
    /// up to and including the specified period.
    ///
    /// This returns the absolute value of negative activity (outflows/payments).
    /// Useful for ByDate targets where payments should count as progress even
    /// if no explicit budgeting occurred.
    pub fn calculate_cumulative_paid(
        &self,
        category_id: CategoryId,
        up_to_period: &BudgetPeriod,
    ) -> EnvelopeResult<Money> {
        let transactions = self.storage.transactions.get_by_category(category_id)?;
        let end_date = up_to_period.end_date();

        let total_paid: i64 = transactions
            .iter()
            .filter(|t| t.date <= end_date)
            .map(|t| {
                if t.is_split() {
                    // Sum only the splits for this category
                    t.splits
                        .iter()
                        .filter(|s| s.category_id == category_id)
                        .map(|s| s.amount.cents())
                        .sum::<i64>()
                } else {
                    t.amount.cents()
                }
            })
            .filter(|&cents| cents < 0) // Only count outflows (payments)
            .map(|cents| cents.abs()) // Convert to positive
            .sum();

        Ok(Money::from_cents(total_paid))
    }

    /// Calculate the carryover amount for a category going into a specific period
    ///
    /// This is the "Available" balance from the previous period, which includes:
    /// - Budgeted amount
    /// - Previous carryover
    /// - Activity (spending)
    pub fn get_carryover(
        &self,
        category_id: CategoryId,
        period: &BudgetPeriod,
    ) -> EnvelopeResult<Money> {
        let prev_period = period.prev();
        let summary = self.get_category_summary(category_id, &prev_period)?;
        Ok(summary.rollover_amount())
    }

    /// Apply rollover from the previous period to a category's allocation
    ///
    /// This should be called when entering a new period to carry forward
    /// any surplus or deficit from the previous period.
    pub fn apply_rollover(
        &self,
        category_id: CategoryId,
        period: &BudgetPeriod,
    ) -> EnvelopeResult<BudgetAllocation> {
        // Calculate carryover from previous period
        let carryover = self.get_carryover(category_id, period)?;

        // Get or create allocation for this period
        let mut allocation = self.storage.budget.get_or_default(category_id, period)?;

        // Only apply if carryover changed
        if allocation.carryover != carryover {
            let before = allocation.clone();
            allocation.set_carryover(carryover);

            // Save
            self.storage.budget.upsert(allocation.clone())?;
            self.storage.budget.save()?;

            // Get category name for audit
            let category = self.storage.categories.get_category(category_id)?;
            let category_name = category.map(|c| c.name);

            // Audit
            self.storage.log_update(
                EntityType::BudgetAllocation,
                format!("{}:{}", category_id, period),
                category_name,
                &before,
                &allocation,
                Some(format!(
                    "carryover: {} -> {}",
                    before.carryover, allocation.carryover
                )),
            )?;
        }

        Ok(allocation)
    }

    /// Apply rollover for all categories for a period
    ///
    /// This calculates and sets the carryover amount for every category
    /// based on their Available balance from the previous period.
    pub fn apply_rollover_all(
        &self,
        period: &BudgetPeriod,
    ) -> EnvelopeResult<Vec<BudgetAllocation>> {
        let category_service = CategoryService::new(self.storage);
        let categories = category_service.list_categories()?;

        let mut allocations = Vec::with_capacity(categories.len());
        for category in &categories {
            let allocation = self.apply_rollover(category.id, period)?;
            allocations.push(allocation);
        }

        Ok(allocations)
    }

    /// Get a list of overspent categories for a period
    pub fn get_overspent_categories(
        &self,
        period: &BudgetPeriod,
    ) -> EnvelopeResult<Vec<CategoryBudgetSummary>> {
        let category_service = CategoryService::new(self.storage);
        let categories = category_service.list_categories()?;

        let mut overspent = Vec::new();
        for category in &categories {
            let summary = self.get_category_summary(category.id, period)?;
            if summary.is_overspent() {
                overspent.push(summary);
            }
        }

        Ok(overspent)
    }

    // ==================== Budget Target Methods ====================

    /// Create or update a budget target for a category
    pub fn set_target(
        &self,
        category_id: CategoryId,
        amount: Money,
        cadence: TargetCadence,
    ) -> EnvelopeResult<BudgetTarget> {
        let category = self
            .storage
            .categories
            .get_category(category_id)?
            .ok_or_else(|| EnvelopeError::category_not_found(category_id.to_string()))?;

        // Deactivate any existing active target for this category
        if let Some(mut existing) = self.storage.targets.get_for_category(category_id)? {
            existing.deactivate();
            self.storage.targets.upsert(existing)?;
        }

        let target = BudgetTarget::new(category_id, amount, cadence);
        target
            .validate()
            .map_err(|e| EnvelopeError::Budget(e.to_string()))?;

        self.storage.targets.upsert(target.clone())?;
        self.storage.targets.save()?;

        self.storage.log_create(
            EntityType::BudgetTarget,
            target.id.to_string(),
            Some(category.name),
            &target,
        )?;

        Ok(target)
    }

    /// Update an existing budget target
    pub fn update_target(
        &self,
        target_id: BudgetTargetId,
        amount: Option<Money>,
        cadence: Option<TargetCadence>,
    ) -> EnvelopeResult<BudgetTarget> {
        let mut target = self
            .storage
            .targets
            .get(target_id)?
            .ok_or_else(|| EnvelopeError::Budget(format!("Target {} not found", target_id)))?;

        let before = target.clone();

        if let Some(amt) = amount {
            target.set_amount(amt);
        }
        if let Some(cad) = cadence {
            target.set_cadence(cad);
        }

        target
            .validate()
            .map_err(|e| EnvelopeError::Budget(e.to_string()))?;

        self.storage.targets.upsert(target.clone())?;
        self.storage.targets.save()?;

        let category = self.storage.categories.get_category(target.category_id)?;
        let category_name = category.map(|c| c.name);

        self.storage.log_update(
            EntityType::BudgetTarget,
            target.id.to_string(),
            category_name,
            &before,
            &target,
            Some(format!("{} -> {}", before, target)),
        )?;

        Ok(target)
    }

    /// Get the active target for a category
    pub fn get_target(&self, category_id: CategoryId) -> EnvelopeResult<Option<BudgetTarget>> {
        self.storage.targets.get_for_category(category_id)
    }

    /// Get the suggested budget amount for a category based on its target
    pub fn get_suggested_budget(
        &self,
        category_id: CategoryId,
        period: &BudgetPeriod,
    ) -> EnvelopeResult<Option<Money>> {
        if let Some(target) = self.storage.targets.get_for_category(category_id)? {
            Ok(Some(target.calculate_for_period(period)))
        } else {
            Ok(None)
        }
    }

    /// Get the suggested budget amount for a category, accounting for progress made.
    ///
    /// For ByDate targets, this subtracts what's already been paid from the target
    /// amount before calculating the monthly suggestion. This prevents over-budgeting
    /// when payments have already been made toward a debt payoff goal.
    ///
    /// For other target types (Weekly, Monthly, Yearly, Custom), this delegates
    /// to the standard calculation since those are recurring targets.
    pub fn get_suggested_budget_with_progress(
        &self,
        category_id: CategoryId,
        period: &BudgetPeriod,
    ) -> EnvelopeResult<Option<Money>> {
        let target = match self.storage.targets.get_for_category(category_id)? {
            Some(t) => t,
            None => return Ok(None),
        };

        match &target.cadence {
            TargetCadence::ByDate { target_date } => {
                let period_start = period.start_date();

                // Target already passed
                if *target_date < period_start {
                    return Ok(Some(Money::zero()));
                }

                // Calculate cumulative paid toward this target
                let target_period = BudgetPeriod::monthly(target_date.year(), target_date.month());
                let cumulative_paid =
                    self.calculate_cumulative_paid(category_id, &target_period)?;

                // Calculate remaining amount needed
                let remaining = (target.amount.cents() - cumulative_paid.cents()).max(0);

                // If already fully paid, suggest $0
                if remaining == 0 {
                    return Ok(Some(Money::zero()));
                }

                // Calculate months remaining (including current month)
                let months = self.months_between(period_start, *target_date);

                if months <= 0 {
                    // Target is due this period - suggest remaining amount
                    Ok(Some(Money::from_cents(remaining)))
                } else {
                    // Spread remaining over remaining months
                    Ok(Some(Money::from_cents(
                        (remaining as f64 / months as f64).ceil() as i64,
                    )))
                }
            }
            // For recurring targets, use the standard calculation
            _ => Ok(Some(target.calculate_for_period(period))),
        }
    }

    /// Calculate months between two dates
    fn months_between(&self, start: chrono::NaiveDate, end: chrono::NaiveDate) -> i32 {
        let years = end.year() - start.year();
        let months = end.month() as i32 - start.month() as i32;
        years * 12 + months
    }

    /// Delete a target
    pub fn delete_target(&self, target_id: BudgetTargetId) -> EnvelopeResult<bool> {
        if let Some(target) = self.storage.targets.get(target_id)? {
            let category = self.storage.categories.get_category(target.category_id)?;
            let category_name = category.map(|c| c.name);

            self.storage.targets.delete(target_id)?;
            self.storage.targets.save()?;

            self.storage.log_delete(
                EntityType::BudgetTarget,
                target.id.to_string(),
                category_name,
                &target,
            )?;

            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Remove target for a category
    pub fn remove_target(&self, category_id: CategoryId) -> EnvelopeResult<bool> {
        if let Some(target) = self.storage.targets.get_for_category(category_id)? {
            self.delete_target(target.id)
        } else {
            Ok(false)
        }
    }

    /// Get all active targets
    pub fn get_all_targets(&self) -> EnvelopeResult<Vec<BudgetTarget>> {
        self.storage.targets.get_all_active()
    }

    /// Auto-fill budget for a category based on its target
    ///
    /// Uses progress-aware calculation for ByDate targets, accounting for
    /// payments already made toward the goal.
    pub fn auto_fill_from_target(
        &self,
        category_id: CategoryId,
        period: &BudgetPeriod,
    ) -> EnvelopeResult<Option<BudgetAllocation>> {
        if let Some(suggested) = self.get_suggested_budget_with_progress(category_id, period)? {
            let allocation = self.assign_to_category(category_id, period, suggested)?;
            Ok(Some(allocation))
        } else {
            Ok(None)
        }
    }

    /// Auto-fill budgets for all categories with targets
    ///
    /// Uses progress-aware calculation for ByDate targets, accounting for
    /// payments already made toward each goal.
    pub fn auto_fill_all_targets(
        &self,
        period: &BudgetPeriod,
    ) -> EnvelopeResult<Vec<BudgetAllocation>> {
        let targets = self.storage.targets.get_all_active()?;
        let mut allocations = Vec::with_capacity(targets.len());

        for target in &targets {
            if let Some(suggested) =
                self.get_suggested_budget_with_progress(target.category_id, period)?
            {
                let allocation = self.assign_to_category(target.category_id, period, suggested)?;
                allocations.push(allocation);
            }
        }

        Ok(allocations)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::paths::EnvelopePaths;
    use crate::models::{Account, AccountType, Category, CategoryGroup, Transaction};
    use chrono::NaiveDate;
    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)
    }

    fn setup_test_data(storage: &Storage) -> (CategoryId, CategoryId, BudgetPeriod) {
        // Create a group
        let group = CategoryGroup::new("Test Group");
        storage.categories.upsert_group(group.clone()).unwrap();

        // Create two categories
        let cat1 = Category::new("Groceries", group.id);
        let cat2 = Category::new("Dining Out", group.id);
        let cat1_id = cat1.id;
        let cat2_id = cat2.id;
        storage.categories.upsert_category(cat1).unwrap();
        storage.categories.upsert_category(cat2).unwrap();
        storage.categories.save().unwrap();

        let period = BudgetPeriod::monthly(2025, 1);

        (cat1_id, cat2_id, period)
    }

    #[test]
    fn test_assign_to_category() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat_id, _, period) = setup_test_data(&storage);
        let service = BudgetService::new(&storage);

        let allocation = service
            .assign_to_category(cat_id, &period, Money::from_cents(50000))
            .unwrap();

        assert_eq!(allocation.budgeted.cents(), 50000);
    }

    #[test]
    fn test_add_to_category() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat_id, _, period) = setup_test_data(&storage);
        let service = BudgetService::new(&storage);

        // First assignment
        service
            .assign_to_category(cat_id, &period, Money::from_cents(30000))
            .unwrap();

        // Add more
        let allocation = service
            .add_to_category(cat_id, &period, Money::from_cents(20000))
            .unwrap();

        assert_eq!(allocation.budgeted.cents(), 50000);
    }

    #[test]
    fn test_move_between_categories() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat1_id, cat2_id, period) = setup_test_data(&storage);
        let service = BudgetService::new(&storage);

        // Assign to first category
        service
            .assign_to_category(cat1_id, &period, Money::from_cents(50000))
            .unwrap();

        // Move some to second
        service
            .move_between_categories(cat1_id, cat2_id, &period, Money::from_cents(20000))
            .unwrap();

        let alloc1 = service.get_allocation(cat1_id, &period).unwrap();
        let alloc2 = service.get_allocation(cat2_id, &period).unwrap();

        assert_eq!(alloc1.budgeted.cents(), 30000);
        assert_eq!(alloc2.budgeted.cents(), 20000);
    }

    #[test]
    fn test_move_insufficient_funds() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat1_id, cat2_id, period) = setup_test_data(&storage);
        let service = BudgetService::new(&storage);

        // Assign to first category
        service
            .assign_to_category(cat1_id, &period, Money::from_cents(10000))
            .unwrap();

        // Try to move more than available
        let result =
            service.move_between_categories(cat1_id, cat2_id, &period, Money::from_cents(20000));

        assert!(matches!(
            result,
            Err(EnvelopeError::InsufficientFunds { .. })
        ));
    }

    #[test]
    fn test_category_activity() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat_id, _, period) = setup_test_data(&storage);

        // Create an account and add a transaction
        let account = Account::new("Checking", AccountType::Checking);
        storage.accounts.upsert(account.clone()).unwrap();

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

        let service = BudgetService::new(&storage);
        let activity = service
            .calculate_category_activity(cat_id, &period)
            .unwrap();

        assert_eq!(activity.cents(), -5000);
    }

    #[test]
    fn test_available_to_budget() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat_id, _, period) = setup_test_data(&storage);

        // Create account with balance
        let account = Account::with_starting_balance(
            "Checking",
            AccountType::Checking,
            Money::from_cents(100000),
        );
        storage.accounts.upsert(account.clone()).unwrap();
        storage.accounts.save().unwrap();

        let service = BudgetService::new(&storage);

        // Before budgeting
        let atb = service.get_available_to_budget(&period).unwrap();
        assert_eq!(atb.cents(), 100000);

        // After budgeting $500
        service
            .assign_to_category(cat_id, &period, Money::from_cents(50000))
            .unwrap();

        let atb = service.get_available_to_budget(&period).unwrap();
        assert_eq!(atb.cents(), 50000); // 100000 - 50000
    }

    #[test]
    fn test_positive_carryover() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat_id, _, jan) = setup_test_data(&storage);
        let feb = jan.next();

        let service = BudgetService::new(&storage);

        // Budget $500 in January, spend nothing
        service
            .assign_to_category(cat_id, &jan, Money::from_cents(50000))
            .unwrap();

        // Get carryover for February (should be $500 - $0 = $500)
        let carryover = service.get_carryover(cat_id, &feb).unwrap();
        assert_eq!(carryover.cents(), 50000);
    }

    #[test]
    fn test_negative_carryover() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat_id, _, jan) = setup_test_data(&storage);
        let feb = jan.next();

        // Create account and add an overspending transaction
        let account = Account::new("Checking", AccountType::Checking);
        storage.accounts.upsert(account.clone()).unwrap();

        let mut txn = Transaction::new(
            account.id,
            NaiveDate::from_ymd_opt(2025, 1, 15).unwrap(),
            Money::from_cents(-60000), // Spent $600
        );
        txn.category_id = Some(cat_id);
        storage.transactions.upsert(txn).unwrap();

        let service = BudgetService::new(&storage);

        // Budget $500 in January, spent $600 (overspent by $100)
        service
            .assign_to_category(cat_id, &jan, Money::from_cents(50000))
            .unwrap();

        // Get carryover for February (should be $500 - $600 = -$100)
        let carryover = service.get_carryover(cat_id, &feb).unwrap();
        assert_eq!(carryover.cents(), -10000);
    }

    #[test]
    fn test_apply_rollover() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat_id, _, jan) = setup_test_data(&storage);
        let feb = jan.next();

        let service = BudgetService::new(&storage);

        // Budget $500 in January
        service
            .assign_to_category(cat_id, &jan, Money::from_cents(50000))
            .unwrap();

        // Apply rollover to February
        let feb_alloc = service.apply_rollover(cat_id, &feb).unwrap();

        // Carryover should be $500
        assert_eq!(feb_alloc.carryover.cents(), 50000);
        assert_eq!(feb_alloc.budgeted.cents(), 0);
        assert_eq!(feb_alloc.total_budgeted().cents(), 50000);
    }

    #[test]
    fn test_apply_rollover_all() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat1_id, cat2_id, jan) = setup_test_data(&storage);
        let feb = jan.next();

        let service = BudgetService::new(&storage);

        // Budget in January
        service
            .assign_to_category(cat1_id, &jan, Money::from_cents(50000))
            .unwrap();
        service
            .assign_to_category(cat2_id, &jan, Money::from_cents(20000))
            .unwrap();

        // Apply rollover for all categories
        let allocations = service.apply_rollover_all(&feb).unwrap();
        assert_eq!(allocations.len(), 2);

        // Check carryovers
        let cat1_alloc = service.get_allocation(cat1_id, &feb).unwrap();
        let cat2_alloc = service.get_allocation(cat2_id, &feb).unwrap();

        assert_eq!(cat1_alloc.carryover.cents(), 50000);
        assert_eq!(cat2_alloc.carryover.cents(), 20000);
    }

    #[test]
    fn test_overspent_categories() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat1_id, cat2_id, period) = setup_test_data(&storage);

        // Create account and add overspending transaction to cat1
        let account = Account::new("Checking", AccountType::Checking);
        storage.accounts.upsert(account.clone()).unwrap();

        let mut txn = Transaction::new(
            account.id,
            NaiveDate::from_ymd_opt(2025, 1, 15).unwrap(),
            Money::from_cents(-60000), // Overspent in cat1
        );
        txn.category_id = Some(cat1_id);
        storage.transactions.upsert(txn).unwrap();

        let service = BudgetService::new(&storage);

        // Budget $500 in cat1 (will be overspent by $100)
        service
            .assign_to_category(cat1_id, &period, Money::from_cents(50000))
            .unwrap();

        // Budget $200 in cat2 (not overspent)
        service
            .assign_to_category(cat2_id, &period, Money::from_cents(20000))
            .unwrap();

        let overspent = service.get_overspent_categories(&period).unwrap();
        assert_eq!(overspent.len(), 1);
        assert_eq!(overspent[0].category_id, cat1_id);
        assert_eq!(overspent[0].available.cents(), -10000);
    }

    #[test]
    fn test_cumulative_budgeted_for_bydate_progress() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat_id, _, _) = setup_test_data(&storage);
        let service = BudgetService::new(&storage);

        // Budget $200 in November 2025
        let nov = BudgetPeriod::monthly(2025, 11);
        service
            .assign_to_category(cat_id, &nov, Money::from_cents(20000))
            .unwrap();

        // Budget $200 in December 2025
        let dec = BudgetPeriod::monthly(2025, 12);
        service
            .assign_to_category(cat_id, &dec, Money::from_cents(20000))
            .unwrap();

        // Cumulative through November should be $200
        let cumulative_nov = service.calculate_cumulative_budgeted(cat_id, &nov).unwrap();
        assert_eq!(cumulative_nov.cents(), 20000);

        // Cumulative through December should be $400
        let cumulative_dec = service.calculate_cumulative_budgeted(cat_id, &dec).unwrap();
        assert_eq!(cumulative_dec.cents(), 40000);

        // Cumulative through a future month (Dec 2026) should still be $400
        let dec_2026 = BudgetPeriod::monthly(2026, 12);
        let cumulative_future = service
            .calculate_cumulative_budgeted(cat_id, &dec_2026)
            .unwrap();
        assert_eq!(cumulative_future.cents(), 40000);
    }

    #[test]
    fn test_cumulative_paid_for_bydate_progress() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat_id, _, _) = setup_test_data(&storage);

        // Create an account for transactions
        let account = Account::new("Checking", AccountType::Checking);
        storage.accounts.upsert(account.clone()).unwrap();

        // Make a $100 payment in November (no budgeting)
        let mut txn1 = Transaction::new(
            account.id,
            NaiveDate::from_ymd_opt(2025, 11, 15).unwrap(),
            Money::from_cents(-10000), // $100 payment (negative = outflow)
        );
        txn1.category_id = Some(cat_id);
        storage.transactions.upsert(txn1).unwrap();

        // Make another $50 payment in December
        let mut txn2 = Transaction::new(
            account.id,
            NaiveDate::from_ymd_opt(2025, 12, 15).unwrap(),
            Money::from_cents(-5000), // $50 payment
        );
        txn2.category_id = Some(cat_id);
        storage.transactions.upsert(txn2).unwrap();

        let service = BudgetService::new(&storage);

        // Cumulative paid through November should be $100
        let nov = BudgetPeriod::monthly(2025, 11);
        let cumulative_nov = service.calculate_cumulative_paid(cat_id, &nov).unwrap();
        assert_eq!(cumulative_nov.cents(), 10000);

        // Cumulative paid through December should be $150
        let dec = BudgetPeriod::monthly(2025, 12);
        let cumulative_dec = service.calculate_cumulative_paid(cat_id, &dec).unwrap();
        assert_eq!(cumulative_dec.cents(), 15000);

        // With $0 budgeted, payments should still count as progress
        let cumulative_budgeted = service.calculate_cumulative_budgeted(cat_id, &dec).unwrap();
        assert_eq!(cumulative_budgeted.cents(), 0);

        // Paid always wins when there are payments (it's the source of truth)
        let progress_amount = if cumulative_dec.cents() > 0 {
            cumulative_dec.cents()
        } else {
            cumulative_budgeted.cents().max(0)
        };
        assert_eq!(progress_amount, 15000); // $150 from payments
    }

    #[test]
    fn test_paid_wins_over_budgeted() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat_id, _, _) = setup_test_data(&storage);

        // Create an account for transactions
        let account = Account::new("Checking", AccountType::Checking);
        storage.accounts.upsert(account.clone()).unwrap();

        let service = BudgetService::new(&storage);
        let dec = BudgetPeriod::monthly(2025, 12);

        // Budget $200 in December
        service
            .assign_to_category(cat_id, &dec, Money::from_cents(20000))
            .unwrap();

        // But only pay $100
        let mut txn = Transaction::new(
            account.id,
            NaiveDate::from_ymd_opt(2025, 12, 15).unwrap(),
            Money::from_cents(-10000), // $100 payment
        );
        txn.category_id = Some(cat_id);
        storage.transactions.upsert(txn).unwrap();

        let cumulative_budgeted = service.calculate_cumulative_budgeted(cat_id, &dec).unwrap();
        let cumulative_paid = service.calculate_cumulative_paid(cat_id, &dec).unwrap();

        assert_eq!(cumulative_budgeted.cents(), 20000); // $200 budgeted
        assert_eq!(cumulative_paid.cents(), 10000); // $100 paid

        // Paid wins - even though budgeted is higher, paid is the source of truth
        let progress_amount = if cumulative_paid.cents() > 0 {
            cumulative_paid.cents()
        } else {
            cumulative_budgeted.cents().max(0)
        };
        assert_eq!(progress_amount, 10000); // $100 from payments, not $200 budgeted
    }

    #[test]
    fn test_suggested_budget_accounts_for_cumulative_paid() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat_id, _, _) = setup_test_data(&storage);

        // Create an account for transactions
        let account = Account::new("Checking", AccountType::Checking);
        storage.accounts.upsert(account.clone()).unwrap();

        let service = BudgetService::new(&storage);

        // Create a ByDate target: $2000 by December 2026
        let target_date = NaiveDate::from_ymd_opt(2026, 12, 31).unwrap();
        service
            .set_target(
                cat_id,
                Money::from_cents(200000),
                TargetCadence::by_date(target_date),
            )
            .unwrap();

        // Current period: January 2026
        // months_between(Jan, Dec) = 12 - 1 = 11 months
        let jan_2026 = BudgetPeriod::monthly(2026, 1);

        // Without any payments, should suggest $2000/11 = $181.82 (ceil)
        let suggested = service
            .get_suggested_budget_with_progress(cat_id, &jan_2026)
            .unwrap()
            .unwrap();
        assert_eq!(suggested.cents(), 18182); // ceil($2000/11) = $181.82

        // Now make a $500 payment in January
        let mut txn = Transaction::new(
            account.id,
            NaiveDate::from_ymd_opt(2026, 1, 15).unwrap(),
            Money::from_cents(-50000), // $500 payment
        );
        txn.category_id = Some(cat_id);
        storage.transactions.upsert(txn).unwrap();

        // For February, should suggest ($2000-$500)/10 = $150
        // months_between(Feb, Dec) = 12 - 2 = 10 months
        let feb_2026 = BudgetPeriod::monthly(2026, 2);
        let suggested = service
            .get_suggested_budget_with_progress(cat_id, &feb_2026)
            .unwrap()
            .unwrap();
        // Remaining: $1500, Months: 10 (Feb through Dec)
        assert_eq!(suggested.cents(), 15000); // $1500/10 = $150

        // Make another $500 payment in February
        let mut txn2 = Transaction::new(
            account.id,
            NaiveDate::from_ymd_opt(2026, 2, 15).unwrap(),
            Money::from_cents(-50000), // $500 payment
        );
        txn2.category_id = Some(cat_id);
        storage.transactions.upsert(txn2).unwrap();

        // For March, should suggest ($2000-$1000)/9 = $111.12 (ceil)
        // months_between(Mar, Dec) = 12 - 3 = 9 months
        let mar_2026 = BudgetPeriod::monthly(2026, 3);
        let suggested = service
            .get_suggested_budget_with_progress(cat_id, &mar_2026)
            .unwrap()
            .unwrap();
        assert_eq!(suggested.cents(), 11112); // ceil($1000/9) = $111.12
    }

    #[test]
    fn test_suggested_budget_fully_paid_suggests_zero() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat_id, _, _) = setup_test_data(&storage);

        // Create an account for transactions
        let account = Account::new("Checking", AccountType::Checking);
        storage.accounts.upsert(account.clone()).unwrap();

        let service = BudgetService::new(&storage);

        // Create a ByDate target: $500 by June 2026
        let target_date = NaiveDate::from_ymd_opt(2026, 6, 30).unwrap();
        service
            .set_target(
                cat_id,
                Money::from_cents(50000),
                TargetCadence::by_date(target_date),
            )
            .unwrap();

        // Pay full amount in January
        let mut txn = Transaction::new(
            account.id,
            NaiveDate::from_ymd_opt(2026, 1, 15).unwrap(),
            Money::from_cents(-50000), // $500 payment - full target
        );
        txn.category_id = Some(cat_id);
        storage.transactions.upsert(txn).unwrap();

        // For February, should suggest $0 since fully paid
        let feb_2026 = BudgetPeriod::monthly(2026, 2);
        let suggested = service
            .get_suggested_budget_with_progress(cat_id, &feb_2026)
            .unwrap()
            .unwrap();
        assert_eq!(suggested.cents(), 0);
    }

    #[test]
    fn test_suggested_budget_recurring_targets_unchanged() {
        let (_temp_dir, storage) = create_test_storage();
        let (cat_id, _, _) = setup_test_data(&storage);

        let service = BudgetService::new(&storage);

        // Create a Monthly target: $300/month
        service
            .set_target(cat_id, Money::from_cents(30000), TargetCadence::Monthly)
            .unwrap();

        let jan_2026 = BudgetPeriod::monthly(2026, 1);

        // Should always suggest $300 regardless of payments (recurring target)
        let suggested = service
            .get_suggested_budget_with_progress(cat_id, &jan_2026)
            .unwrap()
            .unwrap();
        assert_eq!(suggested.cents(), 30000);
    }
}