Skip to main content

plotting/
adapters.rs

1//! Turn view projections into chart specs. Adapters are pure functions
2//! that handle top-N clipping, multi-currency scaling decisions, and
3//! layout choices (x-axis assignment, series arrangement) so renderers
4//! only have to draw.
5
6use finance::error::ReportError;
7use num_rational::Rational64;
8use num_traits::CheckedAdd;
9use server::command::report::size_order::magnitude;
10use server::command::report::view::{
11    AmountView, BreakdownPeriodView, PeriodActivityView, ReportRowView,
12};
13
14use crate::spec::{ChartKind, ChartSpec, Series, SeriesPoint};
15
16// ---------- shared helpers ----------
17
18fn point(x: impl Into<String>, amount: Rational64) -> SeriesPoint {
19    SeriesPoint {
20        x: x.into(),
21        y_num: *amount.numer(),
22        y_denom: *amount.denom(),
23    }
24}
25
26fn amount_for(symbol: &str, amounts: &[AmountView]) -> Rational64 {
27    amounts
28        .iter()
29        .find(|a| a.commodity_symbol == symbol)
30        .map_or_else(|| Rational64::new(0, 1), |a| a.amount)
31}
32
33/// Pick the commodity to plot. When the report already targeted a single
34/// commodity there's usually only one symbol; otherwise the adapter
35/// picks the one that first appears and appends a note listing the
36/// elided symbols so the display can warn the user.
37fn pick_primary_commodity(symbols: &[String]) -> (String, Vec<String>) {
38    match symbols.split_first() {
39        Some((primary, rest)) => (primary.clone(), rest.to_vec()),
40        None => (String::new(), Vec::new()),
41    }
42}
43
44fn multi_currency_note(elided: &[String]) -> Option<String> {
45    match elided.len() {
46        0 => None,
47        1 => Some(format!(
48            "Showing primary commodity only; {} hidden. Set a target currency to see all.",
49            elided[0],
50        )),
51        n => Some(format!(
52            "Showing primary commodity only; {n} others hidden. Set a target currency to see all.",
53        )),
54    }
55}
56
57/// Sort ranked `(row, magnitude)` pairs in place according to the
58/// requested order. Uses the balance adapter's data shape — callers
59/// that need this for other adapters can swap the row type via the
60/// tuple's first field; the function is generic in the row ref.
61fn sort_ranked<R: AccountLike>(ranked: &mut [(R, Rational64)], order: SortOrder) {
62    match order {
63        SortOrder::MagnitudeDesc => {
64            ranked.sort_by_key(|entry| std::cmp::Reverse(entry.1));
65        }
66        SortOrder::MagnitudeAsc => {
67            ranked.sort_by_key(|entry| entry.1);
68        }
69        SortOrder::NameAsc => {
70            ranked.sort_by(|a, b| a.0.name().cmp(b.0.name()));
71        }
72        SortOrder::NameDesc => {
73            ranked.sort_by(|a, b| b.0.name().cmp(a.0.name()));
74        }
75    }
76}
77
78trait AccountLike {
79    fn name(&self) -> &str;
80}
81
82impl AccountLike for &ReportRowView {
83    fn name(&self) -> &str {
84        &self.account_name
85    }
86}
87
88// ---------- Balance ----------
89
90/// Sort key applied to a ranked set of rows. Shared by the balance
91/// adapter and (via the web handler) the balance table rendering —
92/// keeping them on one enum means the chart can't drift from the
93/// table ordering.
94#[derive(Debug, Clone, Copy, Default)]
95pub enum SortOrder {
96    #[default]
97    MagnitudeDesc,
98    MagnitudeAsc,
99    NameAsc,
100    NameDesc,
101}
102
103pub struct BalanceChartOpts {
104    pub kind: ChartKind,
105    pub top_n: usize,
106    pub sort_order: SortOrder,
107}
108
109/// Balance chart: one series per commodity, x = top-level account names.
110/// When more than one commodity is present and the `top_n` most-active
111/// accounts span several commodities, we still render all bars — each
112/// series places a bar in the x-slot for its account and zero elsewhere,
113/// so a mixed-currency report reads as a grouped / stacked bar chart.
114#[must_use]
115pub fn balance_chart(rows: &[ReportRowView], opts: BalanceChartOpts) -> ChartSpec {
116    let top_level: Vec<&ReportRowView> = rows.iter().filter(|r| r.depth == 0).collect();
117
118    if top_level.is_empty() {
119        return ChartSpec {
120            title: "Balance".to_string(),
121            kind: opts.kind,
122            x_label: "Account".to_string(),
123            y_label: "Amount".to_string(),
124            series: vec![],
125            notes: vec!["No top-level accounts to chart.".to_string()],
126        };
127    }
128
129    // Gather commodity symbols in insertion order, then pick the
130    // primary for plotting. A mixed-currency balance notes the elided
131    // commodities rather than silently mashing them together.
132    let mut symbols: Vec<String> = Vec::new();
133    for row in &top_level {
134        for a in &row.amounts {
135            if !symbols.iter().any(|s| s == &a.commodity_symbol) {
136                symbols.push(a.commodity_symbol.clone());
137            }
138        }
139    }
140    let (primary, elided) = pick_primary_commodity(&symbols);
141
142    // Rank accounts by the primary commodity's absolute amount and
143    // then apply the caller's sort choice. Keeping magnitude as the
144    // secondary key means name-sorted charts still break ties
145    // sensibly.
146    let mut ranked: Vec<(&ReportRowView, Rational64)> = top_level
147        .into_iter()
148        .map(|row| (row, magnitude(amount_for(&primary, &row.amounts))))
149        .collect();
150    sort_ranked(&mut ranked, opts.sort_order);
151
152    let clipped = ranked.len() > opts.top_n && opts.top_n > 0;
153    if opts.top_n > 0 {
154        ranked.truncate(opts.top_n);
155    }
156
157    // One series per account so each bar reads as its own colour and
158    // the legend names the account. Each series holds a single point
159    // anchored at the account name.
160    let series: Vec<Series> = ranked
161        .iter()
162        .map(|(row, _)| Series {
163            label: row.account_name.clone(),
164            commodity_symbol: primary.clone(),
165            points: vec![point(&row.account_name, amount_for(&primary, &row.amounts))],
166        })
167        .collect();
168
169    let mut notes = Vec::new();
170    if let Some(n) = multi_currency_note(&elided) {
171        notes.push(n);
172    }
173    if clipped {
174        notes.push(format!("Showing top {} accounts by magnitude.", opts.top_n));
175    }
176
177    ChartSpec {
178        title: "Balance".to_string(),
179        kind: opts.kind,
180        x_label: "Account".to_string(),
181        y_label: format!("Amount ({primary})"),
182        series,
183        notes,
184    }
185}
186
187// ---------- Activity ----------
188
189pub struct ActivityChartOpts {
190    pub kind: ChartKind,
191    pub include_net: bool,
192}
193
194/// Activity chart: x = period label, one series per group label, plus
195/// an optional Net series. Picks a single commodity when multiple are
196/// present and notes the omission.
197#[must_use]
198pub fn activity_chart(periods: &[PeriodActivityView], opts: ActivityChartOpts) -> ChartSpec {
199    // Pass 1: distinct commodities across every group total.
200    let mut symbols: Vec<String> = Vec::new();
201    for p in periods {
202        for g in &p.groups {
203            for a in &g.total {
204                if !symbols.iter().any(|s| s == &a.commodity_symbol) {
205                    symbols.push(a.commodity_symbol.clone());
206                }
207            }
208            for a in &p.net {
209                if !symbols.iter().any(|s| s == &a.commodity_symbol) {
210                    symbols.push(a.commodity_symbol.clone());
211                }
212            }
213        }
214    }
215    let (primary, elided) = pick_primary_commodity(&symbols);
216
217    // Pass 2: group labels in insertion order.
218    let mut group_labels: Vec<String> = Vec::new();
219    for p in periods {
220        for g in &p.groups {
221            if !group_labels.iter().any(|s| s == &g.label) {
222                group_labels.push(g.label.clone());
223            }
224        }
225    }
226
227    let mut series: Vec<Series> = group_labels
228        .iter()
229        .map(|label| Series {
230            label: label.clone(),
231            commodity_symbol: primary.clone(),
232            points: periods
233                .iter()
234                .map(|p| {
235                    let amount = p
236                        .groups
237                        .iter()
238                        .find(|g| &g.label == label)
239                        .map_or_else(|| Rational64::new(0, 1), |g| amount_for(&primary, &g.total));
240                    point(&p.label, amount)
241                })
242                .collect(),
243        })
244        .collect();
245
246    if opts.include_net {
247        series.push(Series {
248            label: "Net".to_string(),
249            commodity_symbol: primary.clone(),
250            points: periods
251                .iter()
252                .map(|p| point(&p.label, amount_for(&primary, &p.net)))
253                .collect(),
254        });
255    }
256
257    let mut notes = Vec::new();
258    if let Some(n) = multi_currency_note(&elided) {
259        notes.push(n);
260    }
261    if periods.is_empty() {
262        notes.push("No periods in range.".to_string());
263    }
264
265    ChartSpec {
266        title: "Activity".to_string(),
267        kind: opts.kind,
268        x_label: "Period".to_string(),
269        y_label: format!("Amount ({primary})"),
270        series,
271        notes,
272    }
273}
274
275// ---------- Category Breakdown ----------
276
277pub struct BreakdownChartOpts {
278    pub kind: ChartKind,
279    pub top_n: usize,
280}
281
282/// Per-tag totals in the order the report lists its rows, which is the sort
283/// the report was asked for.
284fn tag_totals(
285    periods: &[BreakdownPeriodView],
286    primary: &str,
287) -> Result<Vec<(String, Rational64)>, ReportError> {
288    let mut totals: Vec<(String, Rational64)> = Vec::new();
289    for row in periods.iter().flat_map(|p| &p.rows) {
290        let amount = amount_for(primary, &row.amounts);
291        match totals.iter_mut().find(|(tag, _)| *tag == row.tag_value) {
292            Some((_, total)) => {
293                *total = total
294                    .checked_add(&amount)
295                    .ok_or(ReportError::AmountOverflow)?;
296            }
297            None => totals.push((row.tag_value.clone(), amount)),
298        }
299    }
300    Ok(totals)
301}
302
303/// Keeps the `top_n` largest totals by magnitude, in their listed order.
304fn keep_largest(ranked: &mut Vec<(String, Rational64)>, top_n: usize) {
305    let mut by_size: Vec<usize> = (0..ranked.len()).collect();
306    by_size.sort_by_key(|&i| std::cmp::Reverse(magnitude(ranked[i].1)));
307    by_size.truncate(top_n);
308    *ranked = std::mem::take(ranked)
309        .into_iter()
310        .enumerate()
311        .filter_map(|(i, entry)| by_size.contains(&i).then_some(entry))
312        .collect();
313}
314
315/// Breakdown chart. Two shapes depending on whether the breakdown has
316/// period grouping:
317///
318/// - **With periods** (len > 1, or the single label is non-empty):
319///   x = period label, one series per top-N tag value.
320/// - **Flat** (single period, empty label — meaning no `period_grouping`):
321///   x = tag value, a single series.
322///
323/// # Errors
324/// [`ReportError::AmountOverflow`] when a tag's totals across periods do not fit.
325pub fn breakdown_chart(
326    periods: &[BreakdownPeriodView],
327    opts: BreakdownChartOpts,
328) -> Result<ChartSpec, ReportError> {
329    if periods.is_empty() {
330        return Ok(ChartSpec {
331            title: "Category Breakdown".to_string(),
332            kind: opts.kind,
333            x_label: "Category".to_string(),
334            y_label: "Amount".to_string(),
335            series: vec![],
336            notes: vec!["No rows in range.".to_string()],
337        });
338    }
339
340    let mut symbols: Vec<String> = Vec::new();
341    for p in periods {
342        for row in &p.rows {
343            for a in &row.amounts {
344                if !symbols.iter().any(|s| s == &a.commodity_symbol) {
345                    symbols.push(a.commodity_symbol.clone());
346                }
347            }
348        }
349    }
350    let (primary, elided) = pick_primary_commodity(&symbols);
351
352    let flat = periods.len() == 1 && periods[0].label.is_empty();
353
354    // Pull the uncategorized flag off each tag-value up front so flat
355    // and period shapes can relabel "__uncategorized__" consistently.
356    let mut uncategorized_tags: std::collections::HashSet<String> =
357        std::collections::HashSet::new();
358    for p in periods {
359        for row in &p.rows {
360            if row.is_uncategorized {
361                uncategorized_tags.insert(row.tag_value.clone());
362            }
363        }
364    }
365
366    let mut ranked = tag_totals(periods, &primary)?;
367    let clipped = ranked.len() > opts.top_n && opts.top_n > 0;
368    if clipped {
369        keep_largest(&mut ranked, opts.top_n);
370    }
371
372    let pretty_tag = |tag: &str| -> String {
373        if uncategorized_tags.contains(tag) {
374            "(uncategorized)".to_string()
375        } else {
376            tag.to_string()
377        }
378    };
379
380    let mut notes = Vec::new();
381    if let Some(n) = multi_currency_note(&elided) {
382        notes.push(n);
383    }
384    if clipped {
385        notes.push(format!("Showing top {} categories.", opts.top_n));
386    }
387
388    // Flat shape: one series per category so each bar reads as a
389    // distinct colour. Each series holds a single point anchored at
390    // its own tag name. Period shape: one series per category across
391    // period x-slots.
392    let series = if flat {
393        ranked
394            .iter()
395            .map(|(name, amount)| Series {
396                label: pretty_tag(name),
397                commodity_symbol: primary.clone(),
398                points: vec![point(pretty_tag(name), *amount)],
399            })
400            .collect()
401    } else {
402        ranked
403            .iter()
404            .map(|(tag, _)| Series {
405                label: pretty_tag(tag),
406                commodity_symbol: primary.clone(),
407                points: periods
408                    .iter()
409                    .map(|p| {
410                        let amount = p.rows.iter().find(|r| &r.tag_value == tag).map_or_else(
411                            || Rational64::new(0, 1),
412                            |r| amount_for(&primary, &r.amounts),
413                        );
414                        point(&p.label, amount)
415                    })
416                    .collect(),
417            })
418            .collect()
419    };
420
421    let kind = match (flat, opts.kind) {
422        (true, ChartKind::Bar) => ChartKind::HBar,
423        (_, kind) => kind,
424    };
425    Ok(ChartSpec {
426        title: "Category Breakdown".to_string(),
427        kind,
428        x_label: if flat {
429            "Category".to_string()
430        } else {
431            "Period".to_string()
432        },
433        y_label: format!("Amount ({primary})"),
434        series,
435        notes,
436    })
437}
438
439#[cfg(test)]
440mod hbar_tests;
441
442#[cfg(test)]
443mod tests {
444    use server::command::report::view::{BreakdownRowView, GroupView};
445    use uuid::Uuid;
446
447    use super::*;
448
449    fn amt(sym: &str, n: i64) -> AmountView {
450        AmountView {
451            commodity_symbol: sym.to_string(),
452            amount: Rational64::new(n, 1),
453        }
454    }
455
456    fn row(name: &str, depth: usize, amounts: Vec<AmountView>) -> ReportRowView {
457        ReportRowView {
458            account_id: Uuid::new_v4(),
459            parent_id: None,
460            account_name: name.to_string(),
461            depth,
462            has_children: false,
463            amounts,
464            own: vec![],
465        }
466    }
467
468    // ---- Balance ----
469
470    #[test]
471    fn balance_chart_ranks_and_clips_to_top_n() {
472        let rows = vec![
473            row("Cash", 0, vec![amt("USD", 100)]),
474            row("Bank", 0, vec![amt("USD", 5000)]),
475            row("Credit", 0, vec![amt("USD", -2000)]),
476            row("Checking", 1, vec![amt("USD", 3000)]), // depth 1 — ignored
477        ];
478
479        let spec = balance_chart(
480            &rows,
481            BalanceChartOpts {
482                kind: ChartKind::Bar,
483                top_n: 2,
484                sort_order: SortOrder::MagnitudeDesc,
485            },
486        );
487
488        // One series per account so each bar gets its own palette
489        // colour. Account order matches absolute-amount ranking.
490        assert_eq!(spec.series.len(), 2, "one series per top-N account");
491        let labels: Vec<&str> = spec.series.iter().map(|s| s.label.as_str()).collect();
492        assert_eq!(labels, ["Bank", "Credit"]);
493        assert_eq!(spec.series[0].points[0].x, "Bank");
494        assert_eq!(spec.series[0].points[0].y_num, 5000);
495        assert_eq!(spec.series[1].points[0].y_num, -2000);
496        assert!(spec.notes.iter().any(|n| n.contains("top 2")));
497    }
498
499    #[test]
500    fn balance_chart_sort_order_variants() {
501        let rows = vec![
502            row("Gamma", 0, vec![amt("USD", 300)]),
503            row("Alpha", 0, vec![amt("USD", 500)]),
504            row("Beta", 0, vec![amt("USD", -100)]),
505        ];
506
507        let order_labels = |order: SortOrder| -> Vec<String> {
508            balance_chart(
509                &rows,
510                BalanceChartOpts {
511                    kind: ChartKind::Bar,
512                    top_n: 10,
513                    sort_order: order,
514                },
515            )
516            .series
517            .iter()
518            .map(|s| s.label.clone())
519            .collect()
520        };
521
522        assert_eq!(
523            order_labels(SortOrder::MagnitudeDesc),
524            vec!["Alpha", "Gamma", "Beta"],
525            "default: largest absolute amount first"
526        );
527        assert_eq!(
528            order_labels(SortOrder::MagnitudeAsc),
529            vec!["Beta", "Gamma", "Alpha"],
530            "ascending walks smallest first"
531        );
532        assert_eq!(
533            order_labels(SortOrder::NameAsc),
534            vec!["Alpha", "Beta", "Gamma"],
535            "alphabetical"
536        );
537        assert_eq!(
538            order_labels(SortOrder::NameDesc),
539            vec!["Gamma", "Beta", "Alpha"],
540            "reverse alphabetical"
541        );
542    }
543
544    #[test]
545    fn balance_chart_handles_multi_currency() {
546        let rows = vec![
547            row("Cash", 0, vec![amt("USD", 100)]),
548            row("Bank", 0, vec![amt("EUR", 200), amt("USD", 50)]),
549        ];
550
551        let spec = balance_chart(
552            &rows,
553            BalanceChartOpts {
554                kind: ChartKind::Bar,
555                top_n: 10,
556                sort_order: SortOrder::MagnitudeDesc,
557            },
558        );
559
560        // Mixed currency picks the primary (USD, the first-seen),
561        // notes the elided one, and charts account bars using the
562        // primary's amount.
563        assert_eq!(spec.series.len(), 2, "one series per account");
564        assert_eq!(spec.y_label, "Amount (USD)");
565        let cash = spec.series.iter().find(|s| s.label == "Cash").unwrap();
566        let bank = spec.series.iter().find(|s| s.label == "Bank").unwrap();
567        assert_eq!(cash.points[0].y_num, 100);
568        assert_eq!(bank.points[0].y_num, 50);
569        assert!(
570            spec.notes
571                .iter()
572                .any(|n| n.contains("EUR") && n.contains("hidden")),
573            "notes mention the elided commodity"
574        );
575    }
576
577    #[test]
578    fn balance_chart_empty_rows_is_graceful() {
579        let spec = balance_chart(
580            &[],
581            BalanceChartOpts {
582                kind: ChartKind::Bar,
583                top_n: 5,
584                sort_order: SortOrder::MagnitudeDesc,
585            },
586        );
587        assert!(spec.series.is_empty());
588        assert!(spec.notes.iter().any(|n| n.contains("No top-level")));
589    }
590
591    // ---- Activity ----
592
593    #[test]
594    fn activity_chart_emits_series_per_group_and_optional_net() {
595        let periods = vec![
596            PeriodActivityView {
597                label: "2026-01".to_string(),
598                groups: vec![
599                    GroupView {
600                        label: "Income".to_string(),
601                        flip_sign: true,
602                        rows: vec![],
603                        total: vec![amt("USD", 3200)],
604                    },
605                    GroupView {
606                        label: "Expense".to_string(),
607                        flip_sign: false,
608                        rows: vec![],
609                        total: vec![amt("USD", 2100)],
610                    },
611                ],
612                net: vec![amt("USD", 1100)],
613            },
614            PeriodActivityView {
615                label: "2026-02".to_string(),
616                groups: vec![
617                    GroupView {
618                        label: "Income".to_string(),
619                        flip_sign: true,
620                        rows: vec![],
621                        total: vec![amt("USD", 2800)],
622                    },
623                    GroupView {
624                        label: "Expense".to_string(),
625                        flip_sign: false,
626                        rows: vec![],
627                        total: vec![amt("USD", 1900)],
628                    },
629                ],
630                net: vec![amt("USD", 900)],
631            },
632        ];
633
634        let spec = activity_chart(
635            &periods,
636            ActivityChartOpts {
637                kind: ChartKind::StackedBar,
638                include_net: true,
639            },
640        );
641
642        assert_eq!(spec.series.len(), 3, "Income, Expense, Net — three series");
643        let income = spec.series.iter().find(|s| s.label == "Income").unwrap();
644        let xs: Vec<&str> = income.points.iter().map(|p| p.x.as_str()).collect();
645        assert_eq!(xs, vec!["2026-01", "2026-02"]);
646        let ys: Vec<i64> = income.points.iter().map(|p| p.y_num).collect();
647        assert_eq!(ys, vec![3200, 2800]);
648
649        let net = spec.series.iter().find(|s| s.label == "Net").unwrap();
650        assert_eq!(net.points[0].y_num, 1100);
651        assert_eq!(net.points[1].y_num, 900);
652    }
653
654    #[test]
655    fn activity_chart_without_net_omits_the_net_series() {
656        let periods = vec![PeriodActivityView {
657            label: "2026-04".to_string(),
658            groups: vec![GroupView {
659                label: "Income".to_string(),
660                flip_sign: true,
661                rows: vec![],
662                total: vec![amt("USD", 1000)],
663            }],
664            net: vec![amt("USD", 1000)],
665        }];
666
667        let spec = activity_chart(
668            &periods,
669            ActivityChartOpts {
670                kind: ChartKind::Bar,
671                include_net: false,
672            },
673        );
674
675        assert!(spec.series.iter().all(|s| s.label != "Net"));
676    }
677
678    #[test]
679    fn activity_chart_multi_currency_notes_omission() {
680        let periods = vec![PeriodActivityView {
681            label: "2026-04".to_string(),
682            groups: vec![GroupView {
683                label: "Income".to_string(),
684                flip_sign: true,
685                rows: vec![],
686                total: vec![amt("USD", 100), amt("EUR", 80)],
687            }],
688            net: vec![amt("USD", 100), amt("EUR", 80)],
689        }];
690
691        let spec = activity_chart(
692            &periods,
693            ActivityChartOpts {
694                kind: ChartKind::Bar,
695                include_net: false,
696            },
697        );
698
699        assert_eq!(spec.series[0].commodity_symbol, "USD");
700        assert!(
701            spec.notes
702                .iter()
703                .any(|n| n.contains("EUR") && n.contains("hidden")),
704            "notes mention the elided commodity"
705        );
706    }
707
708    // ---- Breakdown ----
709
710    fn brow(tag: &str, amounts: Vec<AmountView>) -> BreakdownRowView {
711        BreakdownRowView {
712            tag_value: tag.to_string(),
713            is_uncategorized: false,
714            amounts,
715        }
716    }
717
718    #[test]
719    fn breakdown_chart_flat_shape_single_series() {
720        let periods = vec![BreakdownPeriodView {
721            label: String::new(),
722            rows: vec![
723                brow("food", vec![amt("USD", 400)]),
724                brow("transport", vec![amt("USD", 150)]),
725                brow("rent", vec![amt("USD", 1200)]),
726            ],
727        }];
728
729        let spec = breakdown_chart(
730            &periods,
731            BreakdownChartOpts {
732                kind: ChartKind::Bar,
733                top_n: 10,
734            },
735        )
736        .expect("chart");
737
738        // Flat shape emits one series per category so bars read as
739        // distinct colours, in the order the report sorted its rows.
740        assert_eq!(spec.series.len(), 3, "one series per category");
741        let labels: Vec<&str> = spec.series.iter().map(|s| s.label.as_str()).collect();
742        assert_eq!(labels, ["food", "transport", "rent"]);
743        let rent = &spec.series[2];
744        assert_eq!(rent.points.len(), 1, "single point per flat series");
745        assert_eq!(rent.points[0].y_num, 1200);
746        assert_eq!(spec.x_label, "Category");
747    }
748
749    #[test]
750    fn breakdown_chart_period_shape_one_series_per_category() {
751        let periods = vec![
752            BreakdownPeriodView {
753                label: "2026-01".to_string(),
754                rows: vec![
755                    brow("food", vec![amt("USD", 300)]),
756                    brow("transport", vec![amt("USD", 100)]),
757                ],
758            },
759            BreakdownPeriodView {
760                label: "2026-02".to_string(),
761                rows: vec![brow("food", vec![amt("USD", 350)])],
762            },
763        ];
764
765        let spec = breakdown_chart(
766            &periods,
767            BreakdownChartOpts {
768                kind: ChartKind::Line,
769                top_n: 5,
770            },
771        )
772        .expect("chart");
773
774        assert_eq!(spec.series.len(), 2, "food + transport");
775        let food = spec.series.iter().find(|s| s.label == "food").unwrap();
776        let transport = spec.series.iter().find(|s| s.label == "transport").unwrap();
777        assert_eq!(food.points[0].y_num, 300);
778        assert_eq!(food.points[1].y_num, 350);
779        assert_eq!(transport.points[0].y_num, 100);
780        assert_eq!(
781            transport.points[1].y_num, 0,
782            "missing periods fill with zero"
783        );
784        assert_eq!(spec.x_label, "Period");
785    }
786
787    #[test]
788    fn breakdown_chart_clips_to_top_n_and_notes() {
789        let periods = vec![BreakdownPeriodView {
790            label: String::new(),
791            rows: vec![
792                brow("a", vec![amt("USD", 100)]),
793                brow("b", vec![amt("USD", 200)]),
794                brow("c", vec![amt("USD", 300)]),
795                brow("d", vec![amt("USD", 400)]),
796            ],
797        }];
798
799        let spec = breakdown_chart(
800            &periods,
801            BreakdownChartOpts {
802                kind: ChartKind::Bar,
803                top_n: 2,
804            },
805        )
806        .expect("chart");
807
808        // Top-2 clip leaves the two largest categories, in their listed order.
809        let labels: Vec<&str> = spec.series.iter().map(|s| s.label.as_str()).collect();
810        assert_eq!(labels, ["c", "d"]);
811        assert!(spec.notes.iter().any(|n| n.contains("top 2")));
812    }
813
814    #[test]
815    fn breakdown_chart_keeps_the_report_order_across_periods() {
816        let periods = vec![
817            BreakdownPeriodView {
818                label: "2025-Q1".to_string(),
819                rows: vec![
820                    brow("food", vec![amt("USD", 150)]),
821                    brow("salary", vec![amt("USD", -3000)]),
822                ],
823            },
824            BreakdownPeriodView {
825                label: "2025-Q2".to_string(),
826                rows: vec![
827                    brow("housing", vec![amt("USD", 800)]),
828                    brow("salary", vec![amt("USD", -3000)]),
829                ],
830            },
831        ];
832
833        let spec = breakdown_chart(
834            &periods,
835            BreakdownChartOpts {
836                kind: ChartKind::Bar,
837                top_n: 10,
838            },
839        )
840        .expect("chart");
841
842        let labels: Vec<&str> = spec.series.iter().map(|s| s.label.as_str()).collect();
843        assert_eq!(labels, ["food", "salary", "housing"]);
844    }
845
846    #[test]
847    fn breakdown_chart_flat_relabels_uncategorized_sentinel() {
848        let periods = vec![BreakdownPeriodView {
849            label: String::new(),
850            rows: vec![
851                brow("food", vec![amt("USD", 400)]),
852                BreakdownRowView {
853                    tag_value: "__uncategorized__".to_string(),
854                    is_uncategorized: true,
855                    amounts: vec![amt("USD", 50)],
856                },
857            ],
858        }];
859
860        let spec = breakdown_chart(
861            &periods,
862            BreakdownChartOpts {
863                kind: ChartKind::Bar,
864                top_n: 10,
865            },
866        )
867        .expect("chart");
868
869        let uncategorized = spec
870            .series
871            .iter()
872            .find(|s| s.label == "(uncategorized)")
873            .expect("pretty label replaces sentinel");
874        assert_eq!(uncategorized.points[0].x, "(uncategorized)");
875        assert!(
876            !spec.series.iter().any(|s| s.label == "__uncategorized__"),
877            "sentinel must not leak into the chart"
878        );
879    }
880
881    #[test]
882    fn a_tag_whose_period_totals_overflow_is_a_report_error() {
883        let period = |label: &str| BreakdownPeriodView {
884            label: label.to_string(),
885            rows: vec![brow("food", vec![amt("USD", i64::MAX)])],
886        };
887        let err = breakdown_chart(
888            &[period("Q1"), period("Q2")],
889            BreakdownChartOpts {
890                kind: ChartKind::Bar,
891                top_n: 10,
892            },
893        )
894        .unwrap_err();
895        assert!(matches!(err, ReportError::AmountOverflow), "{err:?}");
896    }
897
898    #[test]
899    fn an_i64_min_balance_ranks_as_the_largest_without_wrapping() {
900        let rows = vec![
901            row("Debt", 0, vec![amt("USD", i64::MIN)]),
902            row("Cash", 0, vec![amt("USD", 100)]),
903        ];
904        let spec = balance_chart(
905            &rows,
906            BalanceChartOpts {
907                kind: ChartKind::Bar,
908                top_n: 1,
909                sort_order: SortOrder::MagnitudeDesc,
910            },
911        );
912        assert_eq!(spec.series[0].points[0].x, "Debt");
913    }
914}