monarch-mcp 0.4.2

Monarch Money MCP server — an agentic budgeting companion (read + categorize only)
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
//! Pure aggregation logic for the `spending_report` tool.
//!
//! All arithmetic lives here, separated from I/O, so it can be unit-tested
//! without standing up a mock server. The tool handler in `tools.rs` fetches
//! data then delegates to [`compute_spending_report`].

use crate::client::{Budget, Cashflow, Transaction};
use serde::Serialize;
use std::collections::HashMap;

// ---------------------------------------------------------------------------
// Input types — subsets of client types we actually need
// ---------------------------------------------------------------------------

/// Spending and budget data for one category.
#[derive(Debug, Serialize, PartialEq)]
pub struct CategoryReport {
    pub spent: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub budget: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub percent_of_budget: Option<i64>,
}

/// A possible duplicate charge pair.
#[derive(Debug, Serialize, PartialEq)]
pub struct DuplicateCharge {
    pub merchant: String,
    pub amount: f64,
    pub date: String,
}

/// Month-over-month spending comparison.
#[derive(Debug, Serialize, PartialEq)]
pub struct PriorPeriodComparison {
    /// Positive = spending went up, negative = spending went down.
    pub delta: f64,
}

/// A charge-and-refund pair from the same merchant, reported for advisor review.
///
/// Surfaced when a charge and a later refund of near-equal magnitude appear
/// from the same merchant within N days. The pair is reported — not netted —
/// so the advisor can explain the anomaly without hiding either transaction.
#[derive(Debug, Serialize, PartialEq)]
pub struct ReversalPair {
    pub merchant: String,
    pub amount: f64,
    pub charge_date: String,
    pub refund_date: String,
}

/// The full spending report payload returned as JSON inside an MCP `CallToolResult`.
#[derive(Debug, Serialize, PartialEq)]
pub struct SpendingReport {
    pub total_spent: f64,
    pub over_budget_categories: Vec<String>,
    pub by_category: HashMap<String, CategoryReport>,
    pub possible_duplicates: Vec<DuplicateCharge>,
    pub possible_reversals: Vec<ReversalPair>,
    pub vs_prior_month: PriorPeriodComparison,
}

// ---------------------------------------------------------------------------
// Pure computation — no I/O
// ---------------------------------------------------------------------------

/// Compute the spending report from already-fetched Monarch data.
pub fn compute_spending_report(
    transactions: &[Transaction],
    budgets: &[Budget],
    cashflow: &Cashflow,
) -> SpendingReport {
    let by_category = aggregate_spending_by_category(transactions);
    let budget_map = build_budget_map(budgets);
    let category_reports = build_category_reports(&by_category, &budget_map);
    let over_budget_categories = find_over_budget_categories(&category_reports);
    // Delegate to the shared helper so spending_report and financial_overview
    // always agree on the definition of "true spending".
    let total_spent = compute_true_spending(transactions);
    let possible_duplicates = find_possible_duplicates(transactions);
    let possible_reversals = find_possible_reversals(transactions);
    let prior_period = PriorPeriodComparison {
        delta: total_spent - cashflow.prior_month_spending,
    };

    SpendingReport {
        total_spent,
        over_budget_categories,
        by_category: category_reports,
        possible_duplicates,
        possible_reversals,
        vs_prior_month: prior_period,
    }
}

/// Compute spend magnitude for a single transaction.
///
/// Monarch sign convention: expense outflows are **negative**. We convert to a
/// positive magnitude so `total_spent` and `percent_of_budget` are always ≥ 0.
///
/// Classification by `group_type`:
/// - `"expense"`: include magnitude `(-amount).max(0.0)`. A positive amount in
///   an expense category is a refund and contributes zero spend.
/// - `"income"` or `"transfer"`: always 0 — excluded from spending entirely.
/// - `None` (unknown group): defensive fallback — negative amounts count as
///   expense magnitude so real spending is never silently hidden. Positive
///   amounts contribute zero (treated as income/refund). See ADR 0004.
pub(crate) fn transaction_spend_magnitude(txn: &Transaction) -> f64 {
    match txn.category.group_type.as_deref() {
        Some("expense") => (-txn.amount).max(0.0),
        Some("income") | Some("transfer") => 0.0,
        _ => (-txn.amount).max(0.0), // defensive: sign-based fallback for unknown types
    }
}

/// Sum expense magnitudes per category name, excluding income and transfer categories.
///
/// Only categories whose `group_type` is `"expense"` (or unknown, via the
/// defensive fallback in `transaction_spend_magnitude`) contribute to the totals.
fn aggregate_spending_by_category(transactions: &[Transaction]) -> HashMap<String, f64> {
    let mut totals: HashMap<String, f64> = HashMap::new();
    for txn in transactions {
        let magnitude = transaction_spend_magnitude(txn);
        // Only include expense categories (and unknown-group fallback) in the map.
        // Income and transfer categories are excluded entirely so they never appear
        // in by_category, percent_of_budget, or over_budget_categories.
        if matches!(txn.category.group_type.as_deref(), Some("expense") | None) {
            *totals.entry(txn.category.name.clone()).or_insert(0.0) += magnitude;
        }
    }
    totals
}

/// Build a lookup map from category name to budget amount.
fn build_budget_map(budgets: &[Budget]) -> HashMap<String, f64> {
    budgets
        .iter()
        .map(|b| (b.category.name.clone(), b.amount))
        .collect()
}

/// Build per-category reports, attaching budget and percent-of-budget when available.
fn build_category_reports(
    spending: &HashMap<String, f64>,
    budget_map: &HashMap<String, f64>,
) -> HashMap<String, CategoryReport> {
    spending
        .iter()
        .map(|(category, &spent)| {
            let report = match budget_map.get(category) {
                Some(&budget) => CategoryReport {
                    spent,
                    budget: Some(budget),
                    percent_of_budget: percent_of_budget(spent, budget),
                },
                None => CategoryReport {
                    spent,
                    budget: None,
                    percent_of_budget: None,
                },
            };
            (category.clone(), report)
        })
        .collect()
}

/// Round (spent / budget_magnitude * 100) to the nearest whole percent.
///
/// Monarch stores expense budgets as negative `plannedCashFlowAmount` values
/// (e.g., "Loan Repayment" → `-1280`). We compare magnitudes so that a budget
/// of either `1280` or `-1280` yields the same percent for a given spend.
///
/// Returns `None` when `budget` is zero to avoid a divide-by-zero producing
/// `inf` (which casts to `i64::MAX`) or `NaN` (which casts to `0`).
fn percent_of_budget(spent: f64, budget: f64) -> Option<i64> {
    let magnitude = budget.abs();
    if magnitude == 0.0 {
        return None;
    }
    Some(((spent / magnitude) * 100.0).round() as i64)
}

/// A category is over budget only when spending strictly exceeds the budget magnitude.
///
/// Monarch stores expense budgets as negative `plannedCashFlowAmount` values
/// (e.g., "Loan Repayment" → `-1280`). We compare `spent` against `budget.abs()`
/// so that both positive-budget and negative-budget categories use the same
/// magnitude comparison. "Over budget" means "spent more than the planned amount".
fn find_over_budget_categories(category_reports: &HashMap<String, CategoryReport>) -> Vec<String> {
    let mut over_budget: Vec<String> = category_reports
        .iter()
        .filter_map(|(name, report)| {
            report.budget.and_then(|budget| {
                if report.spent > budget.abs() {
                    Some(name.clone())
                } else {
                    None
                }
            })
        })
        .collect();
    // Sort for deterministic output
    over_budget.sort();
    over_budget
}

/// Number of days within which a charge+refund pair is considered a possible reversal.
const REVERSAL_WINDOW_DAYS: i64 = 14;

/// Parse an ISO-8601 date string ("YYYY-MM-DD") into a day count since an epoch.
///
/// Uses the same Gregorian algorithm as `tools.rs` — no external crate needed.
/// Returns `None` when the string is not a valid ISO-8601 date.
fn parse_date_to_days(date: &str) -> Option<i64> {
    let parts: Vec<&str> = date.splitn(3, '-').collect();
    if parts.len() != 3 {
        return None;
    }
    let y: i64 = parts[0].parse().ok()?;
    let m: i64 = parts[1].parse().ok()?;
    let d: i64 = parts[2].parse().ok()?;
    // Civil-to-days formula (Howard Hinnant / Wikipedia proleptic Gregorian)
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    Some(era * 146_097 + doe - 719_468)
}

/// Find charge-and-refund pairs from the same merchant within [`REVERSAL_WINDOW_DAYS`].
///
/// A reversal is: one negative-amount transaction (the charge) followed by a
/// positive-amount transaction (the refund) from the same merchant, with
/// near-equal magnitudes, within the window. The pair is surfaced for advisor
/// review — it is **not** netted from totals.
///
/// Each refund participates in at most one pair. Once a refund is matched to a
/// charge it is marked consumed and skipped for all subsequent charges. This
/// prevents a single refund from being reported as reversing multiple charges
/// when a merchant issues duplicate charges with a single refund.
fn find_possible_reversals(transactions: &[Transaction]) -> Vec<ReversalPair> {
    let mut reversals = Vec::new();

    // Separate charges (negative, expense group) from refunds (positive, expense group).
    let charges: Vec<&Transaction> = transactions
        .iter()
        .filter(|t| {
            t.amount < 0.0 && matches!(t.category.group_type.as_deref(), Some("expense") | None)
        })
        .collect();
    let refunds: Vec<&Transaction> = transactions
        .iter()
        .filter(|t| {
            t.amount > 0.0 && matches!(t.category.group_type.as_deref(), Some("expense") | None)
        })
        .collect();

    // Track which refund indices have already been consumed by an earlier charge.
    let mut consumed_refund_indices = std::collections::HashSet::new();

    for charge in &charges {
        let charge_days = match parse_date_to_days(&charge.date) {
            Some(d) => d,
            None => continue,
        };
        let charge_cents = (-charge.amount * 100.0).round() as i64;

        for (refund_idx, refund) in refunds.iter().enumerate() {
            // Skip refunds already paired with an earlier charge.
            if consumed_refund_indices.contains(&refund_idx) {
                continue;
            }
            // Same merchant (exact match)
            if refund.merchant_name != charge.merchant_name {
                continue;
            }
            // Near-equal magnitude (within 1 cent to handle float rounding)
            let refund_cents = (refund.amount * 100.0).round() as i64;
            if (refund_cents - charge_cents).abs() > 1 {
                continue;
            }
            // Refund must come after (or same day as) the charge, within the window
            let refund_days = match parse_date_to_days(&refund.date) {
                Some(d) => d,
                None => continue,
            };
            let gap = refund_days - charge_days;
            if !(0..=REVERSAL_WINDOW_DAYS).contains(&gap) {
                continue;
            }

            reversals.push(ReversalPair {
                merchant: charge.merchant_name.clone(),
                amount: -charge.amount, // positive magnitude
                charge_date: charge.date.clone(),
                refund_date: refund.date.clone(),
            });
            // Mark this refund consumed so no other charge can claim it.
            consumed_refund_indices.insert(refund_idx);
            break;
        }
    }

    reversals
}

/// Find transactions with the same merchant, same amount, and same date.
/// Each such group is reported as one `DuplicateCharge` entry.
fn find_possible_duplicates(transactions: &[Transaction]) -> Vec<DuplicateCharge> {
    let mut seen: HashMap<(&str, i64, &str), usize> = HashMap::new();
    let mut duplicates: Vec<DuplicateCharge> = Vec::new();
    let mut already_flagged: std::collections::HashSet<(&str, i64, &str)> =
        std::collections::HashSet::new();

    for txn in transactions {
        // Use integer representation of amount (cents) to avoid float key issues
        let amount_cents = (txn.amount * 100.0).round() as i64;
        let key = (txn.merchant_name.as_str(), amount_cents, txn.date.as_str());

        let count = seen.entry(key).or_insert(0);
        *count += 1;

        if *count == 2 && !already_flagged.contains(&key) {
            already_flagged.insert(key);
            duplicates.push(DuplicateCharge {
                merchant: txn.merchant_name.clone(),
                amount: txn.amount,
                date: txn.date.clone(),
            });
        }
    }

    duplicates
}

// ---------------------------------------------------------------------------
// Shared true-spending helper — used by both spending_report and financial_overview
// ---------------------------------------------------------------------------

/// Sum expense magnitudes across transactions, excluding income and transfer groups.
///
/// "True spending" = money that actually left the family. Credit card payments
/// and transfers move money between the family's own accounts — they are
/// inter-account movements, not consumption. Income is an inflow.
///
/// Classification follows the same rules as [`transaction_spend_magnitude`]:
/// - `"expense"` group: magnitude of outflow (negative amount → positive value)
/// - `"income"` or `"transfer"` group: 0 (excluded entirely)
/// - `None` (unknown group): sign-based fallback — negative amounts count as spend
pub fn compute_true_spending(transactions: &[Transaction]) -> f64 {
    transactions.iter().map(transaction_spend_magnitude).sum()
}

// ---------------------------------------------------------------------------
// Tests — TDD: RED first, then GREEN
//
// Fixtures use the REAL Monarch sign convention:
//   - expense outflows: NEGATIVE amounts (e.g. -850.0 for dining)
//   - income: POSITIVE amounts (e.g. +5000.0 for a paycheck)
//   - refunds landing in expense categories: POSITIVE (e.g. +50.0 for a medical refund)
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::{Budget, Cashflow, Category, Transaction};

    /// Build an expense transaction (negative amount, group_type = "expense").
    fn make_expense_txn(merchant: &str, amount: f64, category: &str, date: &str) -> Transaction {
        Transaction {
            id: format!("{merchant}-{amount}-{date}"),
            amount,
            date: date.to_string(),
            merchant_name: merchant.to_string(),
            category: Category {
                name: category.to_string(),
                group_type: Some("expense".into()),
            },
            tags: vec![],
            notes: String::new(),
            needs_review: false,
        }
    }

    /// Build an income transaction (positive amount, group_type = "income").
    fn make_income_txn(merchant: &str, amount: f64, category: &str, date: &str) -> Transaction {
        Transaction {
            id: format!("{merchant}-{amount}-{date}"),
            amount,
            date: date.to_string(),
            merchant_name: merchant.to_string(),
            category: Category {
                name: category.to_string(),
                group_type: Some("income".into()),
            },
            tags: vec![],
            notes: String::new(),
            needs_review: false,
        }
    }

    /// Build a transfer transaction (positive on the receiving side, group_type = "transfer").
    fn make_transfer_txn(merchant: &str, amount: f64, category: &str, date: &str) -> Transaction {
        Transaction {
            id: format!("{merchant}-{amount}-{date}"),
            amount,
            date: date.to_string(),
            merchant_name: merchant.to_string(),
            category: Category {
                name: category.to_string(),
                group_type: Some("transfer".into()),
            },
            tags: vec![],
            notes: String::new(),
            needs_review: false,
        }
    }

    fn make_budget(category: &str, amount: f64) -> Budget {
        Budget {
            category: Category {
                name: category.to_string(),
                group_type: None,
            },
            amount,
        }
    }

    fn zero_cashflow() -> Cashflow {
        Cashflow {
            income: 0.0,
            spending: 0.0,
            prior_month_spending: 0.0,
        }
    }

    // -----------------------------------------------------------------------
    // Real sign convention: expense amounts are NEGATIVE in Monarch.
    // over-budget flag — spending magnitude strictly exceeds budget magnitude.
    // -----------------------------------------------------------------------

    #[test]
    fn negative_expense_over_budget_is_flagged() {
        // -850.0 dining against a 600.0 budget → magnitude 850 > 600 → over budget.
        let txns = vec![make_expense_txn(
            "Dining merchant",
            -850.0,
            "Dining",
            "2026-05-15",
        )];
        let budgets = vec![make_budget("Dining", 600.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            report
                .over_budget_categories
                .contains(&"Dining".to_string()),
            "expected Dining in over_budget_categories: {:?}",
            report.over_budget_categories
        );
    }

    #[test]
    fn negative_expense_exactly_at_budget_is_not_flagged() {
        let txns = vec![make_expense_txn(
            "Groceries merchant",
            -900.0,
            "Groceries",
            "2026-05-15",
        )];
        let budgets = vec![make_budget("Groceries", 900.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            !report
                .over_budget_categories
                .contains(&"Groceries".to_string()),
            "Groceries at 100% should not be flagged: {:?}",
            report.over_budget_categories
        );
    }

    #[test]
    fn negative_expense_under_budget_is_not_flagged() {
        let txns = vec![make_expense_txn(
            "Groceries merchant",
            -720.0,
            "Groceries",
            "2026-05-15",
        )];
        let budgets = vec![make_budget("Groceries", 900.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            !report
                .over_budget_categories
                .contains(&"Groceries".to_string()),
            "Groceries under budget should not be flagged"
        );
    }

    #[test]
    fn all_over_budget_expense_categories_are_flagged() {
        let txns = vec![
            make_expense_txn("Dining merchant", -850.0, "Dining", "2026-05-15"),
            make_expense_txn("Shopping merchant", -500.0, "Shopping", "2026-05-15"),
        ];
        let budgets = vec![make_budget("Dining", 600.0), make_budget("Shopping", 400.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            report
                .over_budget_categories
                .contains(&"Dining".to_string()),
            "Dining should be over budget"
        );
        assert!(
            report
                .over_budget_categories
                .contains(&"Shopping".to_string()),
            "Shopping should be over budget"
        );
    }

    // -----------------------------------------------------------------------
    // Income categories are NEVER flagged as over-budget (#24 core fix).
    // -----------------------------------------------------------------------

    #[test]
    fn income_category_is_never_flagged_as_over_budget() {
        // A large paycheck — positive amount, group_type = "income".
        // Even if there's a budget entry for it, income must not appear in over_budget.
        let txns = vec![make_income_txn(
            "Employer",
            5000.0,
            "Paychecks",
            "2026-05-15",
        )];
        let budgets = vec![make_budget("Paychecks", 100.0)]; // contrived tiny budget
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            !report
                .over_budget_categories
                .contains(&"Paychecks".to_string()),
            "income category Paychecks must never appear in over_budget_categories"
        );
    }

    // -----------------------------------------------------------------------
    // Transfer categories are NEVER included in total_spent or over-budget.
    // -----------------------------------------------------------------------

    #[test]
    fn transfer_category_is_excluded_from_spending() {
        // Credit-card payment — transfer group.
        let txns = vec![make_transfer_txn(
            "Chase CC Payment",
            2000.0,
            "Credit Card Payment",
            "2026-05-15",
        )];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        assert_eq!(
            report.total_spent, 0.0,
            "transfer category must not contribute to total_spent"
        );
        assert!(
            !report
                .over_budget_categories
                .contains(&"Credit Card Payment".to_string()),
            "transfer category must not appear in over_budget_categories"
        );
    }

    // -----------------------------------------------------------------------
    // total_spent reflects ONLY expense magnitudes (#24 core fix).
    // -----------------------------------------------------------------------

    #[test]
    fn total_spent_excludes_income_and_includes_only_expense_magnitudes() {
        let txns = vec![
            make_income_txn("Employer", 5000.0, "Paychecks", "2026-05-15"),
            make_expense_txn("Whole Foods", -365.0, "Groceries", "2026-05-16"),
        ];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        assert_eq!(
            report.total_spent, 365.0,
            "total_spent must equal grocery magnitude (365), not net 5000-365=4635"
        );
    }

    #[test]
    fn total_spent_is_sum_of_expense_magnitudes_only() {
        let txns = vec![
            make_expense_txn("Dining merchant", -850.0, "Dining", "2026-05-15"),
            make_expense_txn("Groceries merchant", -720.0, "Groceries", "2026-05-15"),
        ];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        assert_eq!(report.total_spent, 1570.0);
    }

    // -----------------------------------------------------------------------
    // Refund landing in an expense category (positive amount) contributes
    // zero spend magnitude — not flagged as over-budget (#24 core fix).
    // -----------------------------------------------------------------------

    #[test]
    fn expense_category_with_only_a_refund_is_not_flagged() {
        // Medical refund: positive amount but group_type = "expense".
        // The (-amount).max(0.0) logic produces 0 for this transaction.
        let txns = vec![make_expense_txn("Insurer", 50.0, "Medical", "2026-05-15")];
        let budgets = vec![make_budget("Medical", 200.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            !report
                .over_budget_categories
                .contains(&"Medical".to_string()),
            "expense category with only a positive refund must not be over-budget"
        );
        let cat = report.by_category.get("Medical").unwrap();
        assert_eq!(
            cat.spent, 0.0,
            "refund-only category must report 0 spend, not negative"
        );
    }

    // -----------------------------------------------------------------------
    // percent_of_budget is positive for real expense transactions (#24).
    // -----------------------------------------------------------------------

    #[test]
    fn percent_of_budget_is_positive_for_negative_expense() {
        // -850 spent against 600 budget → magnitude 850 / 600 = 141.67 → 142%.
        // Not -142% as the old code produced.
        assert_eq!(percent_of_budget(850.0, 600.0), Some(142));
        assert_eq!(percent_of_budget(900.0, 900.0), Some(100));
    }

    #[test]
    fn percent_of_budget_rounds_correctly() {
        assert_eq!(percent_of_budget(1.0, 3.0), Some(33));
        assert_eq!(percent_of_budget(2.0, 3.0), Some(67));
    }

    #[test]
    fn expense_category_report_includes_positive_percent() {
        let txns = vec![make_expense_txn(
            "Dining merchant",
            -850.0,
            "Dining",
            "2026-05-15",
        )];
        let budgets = vec![make_budget("Dining", 600.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        let cat = report.by_category.get("Dining").unwrap();
        assert_eq!(cat.percent_of_budget, Some(142));
        assert!(
            cat.spent >= 0.0,
            "spent must be non-negative magnitude, got {}",
            cat.spent
        );
    }

    // -----------------------------------------------------------------------
    // Unbudgeted expense category — reported but not flagged.
    // -----------------------------------------------------------------------

    #[test]
    fn unbudgeted_expense_category_is_not_flagged_as_over_budget() {
        let txns = vec![make_expense_txn(
            "Travel merchant",
            -300.0,
            "Travel",
            "2026-05-15",
        )];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        assert!(
            !report
                .over_budget_categories
                .contains(&"Travel".to_string()),
            "unbudgeted Travel should not be flagged"
        );
        let cat = report.by_category.get("Travel").unwrap();
        assert_eq!(cat.spent, 300.0);
        assert_eq!(cat.budget, None);
        assert_eq!(cat.percent_of_budget, None);
    }

    // -----------------------------------------------------------------------
    // Duplicate detection — same merchant + amount + date.
    // -----------------------------------------------------------------------

    #[test]
    fn identical_charges_same_day_flagged_as_duplicate() {
        let txns = vec![
            make_expense_txn("Acme Streaming", -49.99, "Subscriptions", "2026-05-14"),
            make_expense_txn("Acme Streaming", -49.99, "Subscriptions", "2026-05-14"),
        ];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        let merchants: Vec<&str> = report
            .possible_duplicates
            .iter()
            .map(|d| d.merchant.as_str())
            .collect();
        assert!(
            merchants.contains(&"Acme Streaming"),
            "expected Acme Streaming in duplicates: {:?}",
            merchants
        );
    }

    #[test]
    fn same_merchant_different_amount_not_a_duplicate() {
        let txns = vec![
            make_expense_txn("Acme Streaming", -49.99, "Subscriptions", "2026-05-14"),
            make_expense_txn("Acme Streaming", -9.99, "Subscriptions", "2026-05-14"),
        ];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        let merchants: Vec<&str> = report
            .possible_duplicates
            .iter()
            .map(|d| d.merchant.as_str())
            .collect();
        assert!(
            !merchants.contains(&"Acme Streaming"),
            "different amounts should not be a duplicate: {:?}",
            merchants
        );
    }

    // -----------------------------------------------------------------------
    // Prior-period delta — uses total_spent (expense magnitudes only).
    // -----------------------------------------------------------------------

    #[test]
    fn prior_period_delta_is_positive_when_spending_increased() {
        let txns = vec![make_expense_txn(
            "Various",
            -4600.0,
            "General",
            "2026-05-15",
        )];
        let cashflow = Cashflow {
            income: 0.0,
            spending: 0.0,
            prior_month_spending: 4000.0,
        };
        let report = compute_spending_report(&txns, &[], &cashflow);
        assert_eq!(report.vs_prior_month.delta, 600.0);
    }

    #[test]
    fn prior_period_delta_is_negative_when_spending_decreased() {
        let txns = vec![make_expense_txn(
            "Various",
            -3000.0,
            "General",
            "2026-05-15",
        )];
        let cashflow = Cashflow {
            income: 0.0,
            spending: 0.0,
            prior_month_spending: 4000.0,
        };
        let report = compute_spending_report(&txns, &[], &cashflow);
        assert_eq!(report.vs_prior_month.delta, -1000.0);
    }

    // -----------------------------------------------------------------------
    // possible_reversals — charge+refund pairs from the same merchant.
    // -----------------------------------------------------------------------

    #[test]
    fn charge_and_refund_same_merchant_within_14_days_is_paired() {
        let txns = vec![
            make_expense_txn("Banfield", -850.0, "Pets", "2026-05-01"),
            // Refund: positive amount in an expense category
            make_expense_txn("Banfield", 850.0, "Pets", "2026-05-10"),
        ];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        assert_eq!(
            report.possible_reversals.len(),
            1,
            "expected 1 reversal pair, got {:?}",
            report.possible_reversals
        );
        assert_eq!(report.possible_reversals[0].merchant, "Banfield");
        assert!((report.possible_reversals[0].amount - 850.0).abs() < 0.001);
        assert_eq!(report.possible_reversals[0].charge_date, "2026-05-01");
        assert_eq!(report.possible_reversals[0].refund_date, "2026-05-10");
    }

    #[test]
    fn two_same_amount_charges_without_refund_are_not_paired_as_reversal() {
        let txns = vec![
            make_expense_txn("Banfield", -850.0, "Pets", "2026-05-01"),
            make_expense_txn("Banfield", -850.0, "Pets", "2026-05-05"),
        ];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        assert!(
            report.possible_reversals.is_empty(),
            "two charges (no refund) must not be paired as a reversal: {:?}",
            report.possible_reversals
        );
    }

    #[test]
    fn charge_and_refund_beyond_14_days_are_not_paired() {
        let txns = vec![
            make_expense_txn("Banfield", -850.0, "Pets", "2026-05-01"),
            make_expense_txn("Banfield", 850.0, "Pets", "2026-05-20"),
        ];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        assert!(
            report.possible_reversals.is_empty(),
            "charge+refund beyond 14 days must not be paired: {:?}",
            report.possible_reversals
        );
    }

    #[test]
    fn charge_and_refund_different_merchants_are_not_paired() {
        let txns = vec![
            make_expense_txn("Banfield", -850.0, "Pets", "2026-05-01"),
            make_expense_txn("VetClinic", 850.0, "Pets", "2026-05-05"),
        ];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        assert!(
            report.possible_reversals.is_empty(),
            "different merchants must not be paired as a reversal: {:?}",
            report.possible_reversals
        );
    }

    #[test]
    fn one_charge_and_two_equal_refunds_produces_exactly_one_reversal_pair() {
        // One charge, two identical refunds: only the first refund is consumed.
        // The second refund remains unmatched — there is no second charge to claim it.
        let txns = vec![
            make_expense_txn("Banfield", -850.0, "Pets", "2026-05-01"),
            make_expense_txn("Banfield", 850.0, "Pets", "2026-05-05"),
            make_expense_txn("Banfield", 850.0, "Pets", "2026-05-06"),
        ];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        assert_eq!(
            report.possible_reversals.len(),
            1,
            "one charge + two refunds must yield exactly one reversal pair, got {:?}",
            report.possible_reversals
        );
    }

    #[test]
    fn two_charges_and_two_equal_refunds_produces_two_reversal_pairs() {
        // Two charges each get their own refund — two distinct pairs.
        let txns = vec![
            make_expense_txn("Banfield", -850.0, "Pets", "2026-05-01"),
            make_expense_txn("Banfield", -850.0, "Pets", "2026-05-02"),
            make_expense_txn("Banfield", 850.0, "Pets", "2026-05-05"),
            make_expense_txn("Banfield", 850.0, "Pets", "2026-05-06"),
        ];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        assert_eq!(
            report.possible_reversals.len(),
            2,
            "two charges + two matching refunds must yield two reversal pairs, got {:?}",
            report.possible_reversals
        );
    }

    #[test]
    fn reversal_pair_does_not_change_total_spent() {
        // The reversal is surfaced but NOT netted from totals.
        let txns = vec![
            make_expense_txn("Banfield", -850.0, "Pets", "2026-05-01"),
            make_expense_txn("Banfield", 850.0, "Pets", "2026-05-10"),
        ];
        let report = compute_spending_report(&txns, &[], &zero_cashflow());
        // The charge is 850 (magnitude), refund contributes 0 to spend.
        // Total spend = 850, not 0.
        assert_eq!(
            report.total_spent, 850.0,
            "reversal pair must not be netted from total_spent"
        );
    }

    // -----------------------------------------------------------------------
    // compute_true_spending — shared helper, tested directly.
    // -----------------------------------------------------------------------

    #[test]
    fn true_spending_sums_expense_magnitudes() {
        let txns = vec![
            make_expense_txn("Groceries", -365.0, "Groceries", "2026-05-10"),
            make_expense_txn("Dining", -200.0, "Dining", "2026-05-15"),
        ];
        assert_eq!(compute_true_spending(&txns), 565.0);
    }

    #[test]
    fn true_spending_excludes_income_group() {
        let txns = vec![
            make_income_txn("Employer", 5000.0, "Paychecks", "2026-05-01"),
            make_expense_txn("Groceries", -365.0, "Groceries", "2026-05-10"),
        ];
        assert_eq!(compute_true_spending(&txns), 365.0);
    }

    #[test]
    fn true_spending_excludes_transfer_group() {
        let txns = vec![
            make_transfer_txn("Chase", -3299.02, "Credit Card Payment", "2026-05-05"),
            make_expense_txn("Groceries", -731.27, "Groceries", "2026-05-10"),
        ];
        let result = compute_true_spending(&txns);
        // Only the grocery transaction should contribute
        assert!(
            (result - 731.27).abs() < 0.001,
            "expected 731.27, got {result}"
        );
    }

    #[test]
    fn true_spending_refund_in_expense_category_contributes_zero() {
        // A positive amount in an expense category is a refund → 0 spend
        let txns = vec![make_expense_txn("Insurer", 50.0, "Medical", "2026-05-15")];
        assert_eq!(compute_true_spending(&txns), 0.0);
    }

    #[test]
    fn true_spending_empty_slice_is_zero() {
        assert_eq!(compute_true_spending(&[]), 0.0);
    }

    // -----------------------------------------------------------------------
    // Empty period.
    // -----------------------------------------------------------------------

    #[test]
    fn empty_period_reports_zero_spend_and_no_flags() {
        let report = compute_spending_report(&[], &[], &zero_cashflow());
        assert_eq!(report.total_spent, 0.0);
        assert!(report.over_budget_categories.is_empty());
        assert!(report.by_category.is_empty());
        assert!(report.possible_duplicates.is_empty());
    }

    // -----------------------------------------------------------------------
    // Zero budget with nonzero expense spend.
    // -----------------------------------------------------------------------

    #[test]
    fn zero_budget_with_expense_spend_produces_no_percent_and_is_over_budget() {
        let txns = vec![make_expense_txn(
            "Netflix",
            -15.99,
            "Streaming",
            "2026-05-15",
        )];
        let budgets = vec![make_budget("Streaming", 0.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());

        let cat = report
            .by_category
            .get("Streaming")
            .expect("Streaming category must exist");
        assert_eq!(
            cat.percent_of_budget, None,
            "zero budget should yield no percent (division by zero)"
        );
        assert!(
            report
                .over_budget_categories
                .contains(&"Streaming".to_string()),
            "spending on a $0-budget category must still be classified over budget"
        );
    }

    // -----------------------------------------------------------------------
    // Negative-budget (loan-repayment style) — Monarch stores planned
    // outflows as negative plannedCashFlowAmount values. Transactions for
    // expense categories are negative amounts in the real sign convention.
    // -----------------------------------------------------------------------

    #[test]
    fn negative_budget_under_magnitude_is_not_over_budget() {
        // Planned: -1280 (loan repayment). Actual spend: -1000 → magnitude 1000 < 1280.
        let txns = vec![make_expense_txn(
            "Loan Co",
            -1000.0,
            "Loan Repayment",
            "2026-05-15",
        )];
        let budgets = vec![make_budget("Loan Repayment", -1280.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            !report
                .over_budget_categories
                .contains(&"Loan Repayment".to_string()),
            "spending 1000 against a -1280 budget should NOT be over budget (1000 < 1280)"
        );
    }

    #[test]
    fn negative_budget_over_magnitude_is_flagged_as_over_budget() {
        // Planned: -1280. Actual spend: -1400 → magnitude 1400 > 1280 → over budget.
        let txns = vec![make_expense_txn(
            "Loan Co",
            -1400.0,
            "Loan Repayment",
            "2026-05-15",
        )];
        let budgets = vec![make_budget("Loan Repayment", -1280.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            report
                .over_budget_categories
                .contains(&"Loan Repayment".to_string()),
            "spending 1400 against a -1280 budget SHOULD be over budget (1400 > 1280)"
        );
    }

    #[test]
    fn negative_budget_percent_of_budget_is_positive_and_sane() {
        // 1000 spent against -1280 budget → 1000/1280 * 100 = 78%  (not negative)
        assert_eq!(percent_of_budget(1000.0, -1280.0), Some(78));
    }

    #[test]
    fn negative_budget_exactly_at_magnitude_is_not_over_budget() {
        // Planned: -1280. Actual spend: -1280 → at budget, not over.
        let txns = vec![make_expense_txn(
            "Loan Co",
            -1280.0,
            "Loan Repayment",
            "2026-05-15",
        )];
        let budgets = vec![make_budget("Loan Repayment", -1280.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());
        assert!(
            !report
                .over_budget_categories
                .contains(&"Loan Repayment".to_string()),
            "spending exactly 1280 against a -1280 budget should NOT be over budget"
        );
        let cat = report.by_category.get("Loan Repayment").unwrap();
        assert_eq!(cat.percent_of_budget, Some(100));
    }

    #[test]
    fn negative_budget_zero_spend_is_not_over_budget() {
        let budgets = vec![make_budget("Loan Repayment", -1280.0)];
        let report = compute_spending_report(&[], &budgets, &zero_cashflow());
        assert!(
            !report
                .over_budget_categories
                .contains(&"Loan Repayment".to_string()),
            "zero spend against a negative budget should not be over budget"
        );
    }

    // -----------------------------------------------------------------------
    // Defensive fallback: group_type = None → treat sign alone.
    // -----------------------------------------------------------------------

    #[test]
    fn unknown_group_type_negative_amount_counts_as_expense_spend() {
        // A transaction whose group_type is missing (None) but whose amount is
        // negative falls back to the sign-based heuristic: treated as expense.
        let txn = Transaction {
            id: "unknown-1".into(),
            amount: -100.0,
            date: "2026-05-15".into(),
            merchant_name: "Mystery Co".into(),
            category: Category {
                name: "Unknown".into(),
                group_type: None,
            },
            tags: vec![],
            notes: String::new(),
            needs_review: false,
        };
        let report = compute_spending_report(&[txn], &[], &zero_cashflow());
        assert_eq!(
            report.total_spent, 100.0,
            "negative-amount transaction with no group_type must count as 100 spend"
        );
    }

    #[test]
    fn unknown_group_type_positive_amount_is_not_counted_as_spend() {
        // Unknown group_type with positive amount → treated as income/refund, 0 spend.
        let txn = Transaction {
            id: "unknown-2".into(),
            amount: 200.0,
            date: "2026-05-15".into(),
            merchant_name: "Mystery Refund".into(),
            category: Category {
                name: "Unknown".into(),
                group_type: None,
            },
            tags: vec![],
            notes: String::new(),
            needs_review: false,
        };
        let report = compute_spending_report(&[txn], &[], &zero_cashflow());
        assert_eq!(
            report.total_spent, 0.0,
            "positive-amount transaction with no group_type must not count as spend"
        );
    }

    // -----------------------------------------------------------------------
    // Zero budget with zero spend — no percent, not over-budget.
    // -----------------------------------------------------------------------

    #[test]
    fn zero_budget_with_zero_spend_produces_no_percent_and_is_not_over_budget() {
        let txns = vec![make_expense_txn("Netflix", 0.0, "Streaming", "2026-05-15")];
        let budgets = vec![make_budget("Streaming", 0.0)];
        let report = compute_spending_report(&txns, &budgets, &zero_cashflow());

        let cat = report
            .by_category
            .get("Streaming")
            .expect("Streaming category must exist");
        assert_eq!(
            cat.percent_of_budget, None,
            "zero budget with zero spend should yield None percent (0/0 = NaN, not 0)"
        );
        assert!(
            !report
                .over_budget_categories
                .contains(&"Streaming".to_string()),
            "zero spend on $0-budget category is not over budget"
        );
    }
}