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

            
6
use finance::error::ReportError;
7
use num_rational::Rational64;
8
use num_traits::CheckedAdd;
9
use server::command::report::size_order::magnitude;
10
use server::command::report::view::{
11
    AmountView, BreakdownPeriodView, PeriodActivityView, ReportRowView,
12
};
13

            
14
use crate::spec::{ChartKind, ChartSpec, Series, SeriesPoint};
15

            
16
// ---------- shared helpers ----------
17

            
18
37234
fn point(x: impl Into<String>, amount: Rational64) -> SeriesPoint {
19
37234
    SeriesPoint {
20
37234
        x: x.into(),
21
37234
        y_num: *amount.numer(),
22
37234
        y_denom: *amount.denom(),
23
37234
    }
24
37234
}
25

            
26
53201
fn amount_for(symbol: &str, amounts: &[AmountView]) -> Rational64 {
27
53201
    amounts
28
53201
        .iter()
29
52041
        .find(|a| a.commodity_symbol == symbol)
30
33613
        .map_or_else(|| Rational64::new(0, 1), |a| a.amount)
31
53201
}
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.
37
12304
fn pick_primary_commodity(symbols: &[String]) -> (String, Vec<String>) {
38
12304
    match symbols.split_first() {
39
11141
        Some((primary, rest)) => (primary.clone(), rest.to_vec()),
40
1163
        None => (String::new(), Vec::new()),
41
    }
42
12304
}
43

            
44
12303
fn multi_currency_note(elided: &[String]) -> Option<String> {
45
12303
    match elided.len() {
46
6325
        0 => None,
47
3654
        1 => Some(format!(
48
3654
            "Showing primary commodity only; {} hidden. Set a target currency to see all.",
49
3654
            elided[0],
50
3654
        )),
51
2324
        n => Some(format!(
52
2324
            "Showing primary commodity only; {n} others hidden. Set a target currency to see all.",
53
2324
        )),
54
    }
55
12303
}
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.
61
5651
fn sort_ranked<R: AccountLike>(ranked: &mut [(R, Rational64)], order: SortOrder) {
62
5651
    match order {
63
        SortOrder::MagnitudeDesc => {
64
24582
            ranked.sort_by_key(|entry| std::cmp::Reverse(entry.1));
65
        }
66
        SortOrder::MagnitudeAsc => {
67
6
            ranked.sort_by_key(|entry| entry.1);
68
        }
69
        SortOrder::NameAsc => {
70
3
            ranked.sort_by(|a, b| a.0.name().cmp(b.0.name()));
71
        }
72
        SortOrder::NameDesc => {
73
335
            ranked.sort_by(|a, b| b.0.name().cmp(a.0.name()));
74
        }
75
    }
76
5651
}
77

            
78
trait AccountLike {
79
    fn name(&self) -> &str;
80
}
81

            
82
impl AccountLike for &ReportRowView {
83
676
    fn name(&self) -> &str {
84
676
        &self.account_name
85
676
    }
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)]
95
pub enum SortOrder {
96
    #[default]
97
    MagnitudeDesc,
98
    MagnitudeAsc,
99
    NameAsc,
100
    NameDesc,
101
}
102

            
103
pub 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]
115
6815
pub fn balance_chart(rows: &[ReportRowView], opts: BalanceChartOpts) -> ChartSpec {
116
39196
    let top_level: Vec<&ReportRowView> = rows.iter().filter(|r| r.depth == 0).collect();
117

            
118
6815
    if top_level.is_empty() {
119
1164
        return ChartSpec {
120
1164
            title: "Balance".to_string(),
121
1164
            kind: opts.kind,
122
1164
            x_label: "Account".to_string(),
123
1164
            y_label: "Amount".to_string(),
124
1164
            series: vec![],
125
1164
            notes: vec!["No top-level accounts to chart.".to_string()],
126
1164
        };
127
5651
    }
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
5651
    let mut symbols: Vec<String> = Vec::new();
133
5651
    for row in &top_level {
134
15955
        for a in &row.amounts {
135
38200
            if !symbols.iter().any(|s| s == &a.commodity_symbol) {
136
10300
                symbols.push(a.commodity_symbol.clone());
137
14952
            }
138
        }
139
    }
140
5651
    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
5651
    let mut ranked: Vec<(&ReportRowView, Rational64)> = top_level
147
5651
        .into_iter()
148
15955
        .map(|row| (row, magnitude(amount_for(&primary, &row.amounts))))
149
        .collect();
150
5651
    sort_ranked(&mut ranked, opts.sort_order);
151

            
152
5651
    let clipped = ranked.len() > opts.top_n && opts.top_n > 0;
153
5651
    if opts.top_n > 0 {
154
5651
        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
5651
    let series: Vec<Series> = ranked
161
5651
        .iter()
162
        .map(|(row, _)| Series {
163
15953
            label: row.account_name.clone(),
164
15953
            commodity_symbol: primary.clone(),
165
15953
            points: vec![point(&row.account_name, amount_for(&primary, &row.amounts))],
166
15953
        })
167
        .collect();
168

            
169
5651
    let mut notes = Vec::new();
170
5651
    if let Some(n) = multi_currency_note(&elided) {
171
2325
        notes.push(n);
172
3326
    }
173
5651
    if clipped {
174
2
        notes.push(format!("Showing top {} accounts by magnitude.", opts.top_n));
175
5649
    }
176

            
177
5651
    ChartSpec {
178
5651
        title: "Balance".to_string(),
179
5651
        kind: opts.kind,
180
5651
        x_label: "Account".to_string(),
181
5651
        y_label: format!("Amount ({primary})"),
182
5651
        series,
183
5651
        notes,
184
5651
    }
185
6815
}
186

            
187
// ---------- Activity ----------
188

            
189
pub 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]
198
3988
pub fn activity_chart(periods: &[PeriodActivityView], opts: ActivityChartOpts) -> ChartSpec {
199
    // Pass 1: distinct commodities across every group total.
200
3988
    let mut symbols: Vec<String> = Vec::new();
201
3988
    for p in periods {
202
3988
        for g in &p.groups {
203
7476
            for a in &g.total {
204
6979
                if !symbols.iter().any(|s| s == &a.commodity_symbol) {
205
2328
                    symbols.push(a.commodity_symbol.clone());
206
4651
                }
207
            }
208
7476
            for a in &p.net {
209
10632
                if !symbols.iter().any(|s| s == &a.commodity_symbol) {
210
2822
                    symbols.push(a.commodity_symbol.clone());
211
6979
                }
212
            }
213
        }
214
    }
215
3988
    let (primary, elided) = pick_primary_commodity(&symbols);
216

            
217
    // Pass 2: group labels in insertion order.
218
3988
    let mut group_labels: Vec<String> = Vec::new();
219
3988
    for p in periods {
220
3988
        for g in &p.groups {
221
7476
            if !group_labels.iter().any(|s| s == &g.label) {
222
7474
                group_labels.push(g.label.clone());
223
2
            }
224
        }
225
    }
226

            
227
3988
    let mut series: Vec<Series> = group_labels
228
3988
        .iter()
229
        .map(|label| Series {
230
7474
            label: label.clone(),
231
7474
            commodity_symbol: primary.clone(),
232
7474
            points: periods
233
7474
                .iter()
234
7476
                .map(|p| {
235
7476
                    let amount = p
236
7476
                        .groups
237
7476
                        .iter()
238
10964
                        .find(|g| &g.label == label)
239
7476
                        .map_or_else(|| Rational64::new(0, 1), |g| amount_for(&primary, &g.total));
240
7476
                    point(&p.label, amount)
241
7476
                })
242
                .collect(),
243
7474
        })
244
        .collect();
245

            
246
3988
    if opts.include_net {
247
3654
        series.push(Series {
248
3654
            label: "Net".to_string(),
249
3654
            commodity_symbol: primary.clone(),
250
3654
            points: periods
251
3654
                .iter()
252
3654
                .map(|p| point(&p.label, amount_for(&primary, &p.net)))
253
                .collect(),
254
        });
255
334
    }
256

            
257
3988
    let mut notes = Vec::new();
258
3988
    if let Some(n) = multi_currency_note(&elided) {
259
1827
        notes.push(n);
260
2161
    }
261
3988
    if periods.is_empty() {
262
1
        notes.push("No periods in range.".to_string());
263
3987
    }
264

            
265
3988
    ChartSpec {
266
3988
        title: "Activity".to_string(),
267
3988
        kind: opts.kind,
268
3988
        x_label: "Period".to_string(),
269
3988
        y_label: format!("Amount ({primary})"),
270
3988
        series,
271
3988
        notes,
272
3988
    }
273
3988
}
274

            
275
// ---------- Category Breakdown ----------
276

            
277
pub 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.
284
2665
fn tag_totals(
285
2665
    periods: &[BreakdownPeriodView],
286
2665
    primary: &str,
287
2665
) -> Result<Vec<(String, Rational64)>, ReportError> {
288
2665
    let mut totals: Vec<(String, Rational64)> = Vec::new();
289
2669
    for row in periods.iter().flat_map(|p| &p.rows) {
290
10152
        let amount = amount_for(primary, &row.amounts);
291
19282
        match totals.iter_mut().find(|(tag, _)| *tag == row.tag_value) {
292
            Some((_, total)) => {
293
5
                *total = total
294
5
                    .checked_add(&amount)
295
5
                    .ok_or(ReportError::AmountOverflow)?;
296
            }
297
10147
            None => totals.push((row.tag_value.clone(), amount)),
298
        }
299
    }
300
2664
    Ok(totals)
301
2665
}
302

            
303
/// Keeps the `top_n` largest totals by magnitude, in their listed order.
304
1
fn keep_largest(ranked: &mut Vec<(String, Rational64)>, top_n: usize) {
305
1
    let mut by_size: Vec<usize> = (0..ranked.len()).collect();
306
12
    by_size.sort_by_key(|&i| std::cmp::Reverse(magnitude(ranked[i].1)));
307
1
    by_size.truncate(top_n);
308
1
    *ranked = std::mem::take(ranked)
309
1
        .into_iter()
310
1
        .enumerate()
311
4
        .filter_map(|(i, entry)| by_size.contains(&i).then_some(entry))
312
        .collect();
313
1
}
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.
325
2665
pub fn breakdown_chart(
326
2665
    periods: &[BreakdownPeriodView],
327
2665
    opts: BreakdownChartOpts,
328
2665
) -> Result<ChartSpec, ReportError> {
329
2665
    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
2665
    }
339

            
340
2665
    let mut symbols: Vec<String> = Vec::new();
341
2665
    for p in periods {
342
2669
        for row in &p.rows {
343
10152
            for a in &row.amounts {
344
13472
                if !symbols.iter().any(|s| s == &a.commodity_symbol) {
345
3993
                    symbols.push(a.commodity_symbol.clone());
346
6159
                }
347
            }
348
        }
349
    }
350
2665
    let (primary, elided) = pick_primary_commodity(&symbols);
351

            
352
2665
    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
2665
        std::collections::HashSet::new();
358
2665
    for p in periods {
359
2669
        for row in &p.rows {
360
10152
            if row.is_uncategorized {
361
2159
                uncategorized_tags.insert(row.tag_value.clone());
362
7993
            }
363
        }
364
    }
365

            
366
2665
    let mut ranked = tag_totals(periods, &primary)?;
367
2664
    let clipped = ranked.len() > opts.top_n && opts.top_n > 0;
368
2664
    if clipped {
369
1
        keep_largest(&mut ranked, opts.top_n);
370
2663
    }
371

            
372
20281
    let pretty_tag = |tag: &str| -> String {
373
20281
        if uncategorized_tags.contains(tag) {
374
4318
            "(uncategorized)".to_string()
375
        } else {
376
15963
            tag.to_string()
377
        }
378
20281
    };
379

            
380
2664
    let mut notes = Vec::new();
381
2664
    if let Some(n) = multi_currency_note(&elided) {
382
1826
        notes.push(n);
383
838
    }
384
2664
    if clipped {
385
1
        notes.push(format!("Showing top {} categories.", opts.top_n));
386
2663
    }
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
2664
    let series = if flat {
393
2661
        ranked
394
2661
            .iter()
395
            .map(|(name, amount)| Series {
396
10137
                label: pretty_tag(name),
397
10137
                commodity_symbol: primary.clone(),
398
10137
                points: vec![point(pretty_tag(name), *amount)],
399
10137
            })
400
            .collect()
401
    } else {
402
3
        ranked
403
3
            .iter()
404
            .map(|(tag, _)| Series {
405
7
                label: pretty_tag(tag),
406
7
                commodity_symbol: primary.clone(),
407
7
                points: periods
408
7
                    .iter()
409
14
                    .map(|p| {
410
21
                        let amount = p.rows.iter().find(|r| &r.tag_value == tag).map_or_else(
411
3
                            || Rational64::new(0, 1),
412
11
                            |r| amount_for(&primary, &r.amounts),
413
                        );
414
14
                        point(&p.label, amount)
415
14
                    })
416
                    .collect(),
417
7
            })
418
            .collect()
419
    };
420

            
421
2664
    let kind = match (flat, opts.kind) {
422
1664
        (true, ChartKind::Bar) => ChartKind::HBar,
423
1000
        (_, kind) => kind,
424
    };
425
    Ok(ChartSpec {
426
2664
        title: "Category Breakdown".to_string(),
427
2664
        kind,
428
2664
        x_label: if flat {
429
2661
            "Category".to_string()
430
        } else {
431
3
            "Period".to_string()
432
        },
433
2664
        y_label: format!("Amount ({primary})"),
434
2664
        series,
435
2664
        notes,
436
    })
437
2665
}
438

            
439
#[cfg(test)]
440
mod hbar_tests;
441

            
442
#[cfg(test)]
443
mod tests {
444
    use server::command::report::view::{BreakdownRowView, GroupView};
445
    use uuid::Uuid;
446

            
447
    use super::*;
448

            
449
42
    fn amt(sym: &str, n: i64) -> AmountView {
450
42
        AmountView {
451
42
            commodity_symbol: sym.to_string(),
452
42
            amount: Rational64::new(n, 1),
453
42
        }
454
42
    }
455

            
456
11
    fn row(name: &str, depth: usize, amounts: Vec<AmountView>) -> ReportRowView {
457
11
        ReportRowView {
458
11
            account_id: Uuid::new_v4(),
459
11
            parent_id: None,
460
11
            account_name: name.to_string(),
461
11
            depth,
462
11
            has_children: false,
463
11
            amounts,
464
11
            own: vec![],
465
11
        }
466
11
    }
467

            
468
    // ---- Balance ----
469

            
470
    #[test]
471
1
    fn balance_chart_ranks_and_clips_to_top_n() {
472
1
        let rows = vec![
473
1
            row("Cash", 0, vec![amt("USD", 100)]),
474
1
            row("Bank", 0, vec![amt("USD", 5000)]),
475
1
            row("Credit", 0, vec![amt("USD", -2000)]),
476
1
            row("Checking", 1, vec![amt("USD", 3000)]), // depth 1 — ignored
477
        ];
478

            
479
1
        let spec = balance_chart(
480
1
            &rows,
481
1
            BalanceChartOpts {
482
1
                kind: ChartKind::Bar,
483
1
                top_n: 2,
484
1
                sort_order: SortOrder::MagnitudeDesc,
485
1
            },
486
1
        );
487

            
488
        // One series per account so each bar gets its own palette
489
        // colour. Account order matches absolute-amount ranking.
490
1
        assert_eq!(spec.series.len(), 2, "one series per top-N account");
491
2
        let labels: Vec<&str> = spec.series.iter().map(|s| s.label.as_str()).collect();
492
1
        assert_eq!(labels, ["Bank", "Credit"]);
493
1
        assert_eq!(spec.series[0].points[0].x, "Bank");
494
1
        assert_eq!(spec.series[0].points[0].y_num, 5000);
495
1
        assert_eq!(spec.series[1].points[0].y_num, -2000);
496
1
        assert!(spec.notes.iter().any(|n| n.contains("top 2")));
497
1
    }
498

            
499
    #[test]
500
1
    fn balance_chart_sort_order_variants() {
501
1
        let rows = vec![
502
1
            row("Gamma", 0, vec![amt("USD", 300)]),
503
1
            row("Alpha", 0, vec![amt("USD", 500)]),
504
1
            row("Beta", 0, vec![amt("USD", -100)]),
505
        ];
506

            
507
4
        let order_labels = |order: SortOrder| -> Vec<String> {
508
4
            balance_chart(
509
4
                &rows,
510
4
                BalanceChartOpts {
511
4
                    kind: ChartKind::Bar,
512
4
                    top_n: 10,
513
4
                    sort_order: order,
514
4
                },
515
4
            )
516
4
            .series
517
4
            .iter()
518
12
            .map(|s| s.label.clone())
519
            .collect()
520
4
        };
521

            
522
1
        assert_eq!(
523
1
            order_labels(SortOrder::MagnitudeDesc),
524
1
            vec!["Alpha", "Gamma", "Beta"],
525
            "default: largest absolute amount first"
526
        );
527
1
        assert_eq!(
528
1
            order_labels(SortOrder::MagnitudeAsc),
529
1
            vec!["Beta", "Gamma", "Alpha"],
530
            "ascending walks smallest first"
531
        );
532
1
        assert_eq!(
533
1
            order_labels(SortOrder::NameAsc),
534
1
            vec!["Alpha", "Beta", "Gamma"],
535
            "alphabetical"
536
        );
537
1
        assert_eq!(
538
1
            order_labels(SortOrder::NameDesc),
539
1
            vec!["Gamma", "Beta", "Alpha"],
540
            "reverse alphabetical"
541
        );
542
1
    }
543

            
544
    #[test]
545
1
    fn balance_chart_handles_multi_currency() {
546
1
        let rows = vec![
547
1
            row("Cash", 0, vec![amt("USD", 100)]),
548
1
            row("Bank", 0, vec![amt("EUR", 200), amt("USD", 50)]),
549
        ];
550

            
551
1
        let spec = balance_chart(
552
1
            &rows,
553
1
            BalanceChartOpts {
554
1
                kind: ChartKind::Bar,
555
1
                top_n: 10,
556
1
                sort_order: SortOrder::MagnitudeDesc,
557
1
            },
558
1
        );
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
1
        assert_eq!(spec.series.len(), 2, "one series per account");
564
1
        assert_eq!(spec.y_label, "Amount (USD)");
565
1
        let cash = spec.series.iter().find(|s| s.label == "Cash").unwrap();
566
2
        let bank = spec.series.iter().find(|s| s.label == "Bank").unwrap();
567
1
        assert_eq!(cash.points[0].y_num, 100);
568
1
        assert_eq!(bank.points[0].y_num, 50);
569
1
        assert!(
570
1
            spec.notes
571
1
                .iter()
572
1
                .any(|n| n.contains("EUR") && n.contains("hidden")),
573
            "notes mention the elided commodity"
574
        );
575
1
    }
576

            
577
    #[test]
578
1
    fn balance_chart_empty_rows_is_graceful() {
579
1
        let spec = balance_chart(
580
1
            &[],
581
1
            BalanceChartOpts {
582
1
                kind: ChartKind::Bar,
583
1
                top_n: 5,
584
1
                sort_order: SortOrder::MagnitudeDesc,
585
1
            },
586
1
        );
587
1
        assert!(spec.series.is_empty());
588
1
        assert!(spec.notes.iter().any(|n| n.contains("No top-level")));
589
1
    }
590

            
591
    // ---- Activity ----
592

            
593
    #[test]
594
1
    fn activity_chart_emits_series_per_group_and_optional_net() {
595
1
        let periods = vec![
596
1
            PeriodActivityView {
597
1
                label: "2026-01".to_string(),
598
1
                groups: vec![
599
1
                    GroupView {
600
1
                        label: "Income".to_string(),
601
1
                        flip_sign: true,
602
1
                        rows: vec![],
603
1
                        total: vec![amt("USD", 3200)],
604
1
                    },
605
1
                    GroupView {
606
1
                        label: "Expense".to_string(),
607
1
                        flip_sign: false,
608
1
                        rows: vec![],
609
1
                        total: vec![amt("USD", 2100)],
610
1
                    },
611
1
                ],
612
1
                net: vec![amt("USD", 1100)],
613
1
            },
614
1
            PeriodActivityView {
615
1
                label: "2026-02".to_string(),
616
1
                groups: vec![
617
1
                    GroupView {
618
1
                        label: "Income".to_string(),
619
1
                        flip_sign: true,
620
1
                        rows: vec![],
621
1
                        total: vec![amt("USD", 2800)],
622
1
                    },
623
1
                    GroupView {
624
1
                        label: "Expense".to_string(),
625
1
                        flip_sign: false,
626
1
                        rows: vec![],
627
1
                        total: vec![amt("USD", 1900)],
628
1
                    },
629
1
                ],
630
1
                net: vec![amt("USD", 900)],
631
1
            },
632
        ];
633

            
634
1
        let spec = activity_chart(
635
1
            &periods,
636
1
            ActivityChartOpts {
637
1
                kind: ChartKind::StackedBar,
638
1
                include_net: true,
639
1
            },
640
1
        );
641

            
642
1
        assert_eq!(spec.series.len(), 3, "Income, Expense, Net — three series");
643
1
        let income = spec.series.iter().find(|s| s.label == "Income").unwrap();
644
2
        let xs: Vec<&str> = income.points.iter().map(|p| p.x.as_str()).collect();
645
1
        assert_eq!(xs, vec!["2026-01", "2026-02"]);
646
2
        let ys: Vec<i64> = income.points.iter().map(|p| p.y_num).collect();
647
1
        assert_eq!(ys, vec![3200, 2800]);
648

            
649
3
        let net = spec.series.iter().find(|s| s.label == "Net").unwrap();
650
1
        assert_eq!(net.points[0].y_num, 1100);
651
1
        assert_eq!(net.points[1].y_num, 900);
652
1
    }
653

            
654
    #[test]
655
1
    fn activity_chart_without_net_omits_the_net_series() {
656
1
        let periods = vec![PeriodActivityView {
657
1
            label: "2026-04".to_string(),
658
1
            groups: vec![GroupView {
659
1
                label: "Income".to_string(),
660
1
                flip_sign: true,
661
1
                rows: vec![],
662
1
                total: vec![amt("USD", 1000)],
663
1
            }],
664
1
            net: vec![amt("USD", 1000)],
665
1
        }];
666

            
667
1
        let spec = activity_chart(
668
1
            &periods,
669
1
            ActivityChartOpts {
670
1
                kind: ChartKind::Bar,
671
1
                include_net: false,
672
1
            },
673
1
        );
674

            
675
1
        assert!(spec.series.iter().all(|s| s.label != "Net"));
676
1
    }
677

            
678
    #[test]
679
1
    fn activity_chart_multi_currency_notes_omission() {
680
1
        let periods = vec![PeriodActivityView {
681
1
            label: "2026-04".to_string(),
682
1
            groups: vec![GroupView {
683
1
                label: "Income".to_string(),
684
1
                flip_sign: true,
685
1
                rows: vec![],
686
1
                total: vec![amt("USD", 100), amt("EUR", 80)],
687
1
            }],
688
1
            net: vec![amt("USD", 100), amt("EUR", 80)],
689
1
        }];
690

            
691
1
        let spec = activity_chart(
692
1
            &periods,
693
1
            ActivityChartOpts {
694
1
                kind: ChartKind::Bar,
695
1
                include_net: false,
696
1
            },
697
1
        );
698

            
699
1
        assert_eq!(spec.series[0].commodity_symbol, "USD");
700
1
        assert!(
701
1
            spec.notes
702
1
                .iter()
703
1
                .any(|n| n.contains("EUR") && n.contains("hidden")),
704
            "notes mention the elided commodity"
705
        );
706
1
    }
707

            
708
    // ---- Breakdown ----
709

            
710
17
    fn brow(tag: &str, amounts: Vec<AmountView>) -> BreakdownRowView {
711
17
        BreakdownRowView {
712
17
            tag_value: tag.to_string(),
713
17
            is_uncategorized: false,
714
17
            amounts,
715
17
        }
716
17
    }
717

            
718
    #[test]
719
1
    fn breakdown_chart_flat_shape_single_series() {
720
1
        let periods = vec![BreakdownPeriodView {
721
1
            label: String::new(),
722
1
            rows: vec![
723
1
                brow("food", vec![amt("USD", 400)]),
724
1
                brow("transport", vec![amt("USD", 150)]),
725
1
                brow("rent", vec![amt("USD", 1200)]),
726
1
            ],
727
1
        }];
728

            
729
1
        let spec = breakdown_chart(
730
1
            &periods,
731
1
            BreakdownChartOpts {
732
1
                kind: ChartKind::Bar,
733
1
                top_n: 10,
734
1
            },
735
1
        )
736
1
        .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
1
        assert_eq!(spec.series.len(), 3, "one series per category");
741
3
        let labels: Vec<&str> = spec.series.iter().map(|s| s.label.as_str()).collect();
742
1
        assert_eq!(labels, ["food", "transport", "rent"]);
743
1
        let rent = &spec.series[2];
744
1
        assert_eq!(rent.points.len(), 1, "single point per flat series");
745
1
        assert_eq!(rent.points[0].y_num, 1200);
746
1
        assert_eq!(spec.x_label, "Category");
747
1
    }
748

            
749
    #[test]
750
1
    fn breakdown_chart_period_shape_one_series_per_category() {
751
1
        let periods = vec![
752
1
            BreakdownPeriodView {
753
1
                label: "2026-01".to_string(),
754
1
                rows: vec![
755
1
                    brow("food", vec![amt("USD", 300)]),
756
1
                    brow("transport", vec![amt("USD", 100)]),
757
1
                ],
758
1
            },
759
1
            BreakdownPeriodView {
760
1
                label: "2026-02".to_string(),
761
1
                rows: vec![brow("food", vec![amt("USD", 350)])],
762
1
            },
763
        ];
764

            
765
1
        let spec = breakdown_chart(
766
1
            &periods,
767
1
            BreakdownChartOpts {
768
1
                kind: ChartKind::Line,
769
1
                top_n: 5,
770
1
            },
771
1
        )
772
1
        .expect("chart");
773

            
774
1
        assert_eq!(spec.series.len(), 2, "food + transport");
775
1
        let food = spec.series.iter().find(|s| s.label == "food").unwrap();
776
2
        let transport = spec.series.iter().find(|s| s.label == "transport").unwrap();
777
1
        assert_eq!(food.points[0].y_num, 300);
778
1
        assert_eq!(food.points[1].y_num, 350);
779
1
        assert_eq!(transport.points[0].y_num, 100);
780
1
        assert_eq!(
781
1
            transport.points[1].y_num, 0,
782
            "missing periods fill with zero"
783
        );
784
1
        assert_eq!(spec.x_label, "Period");
785
1
    }
786

            
787
    #[test]
788
1
    fn breakdown_chart_clips_to_top_n_and_notes() {
789
1
        let periods = vec![BreakdownPeriodView {
790
1
            label: String::new(),
791
1
            rows: vec![
792
1
                brow("a", vec![amt("USD", 100)]),
793
1
                brow("b", vec![amt("USD", 200)]),
794
1
                brow("c", vec![amt("USD", 300)]),
795
1
                brow("d", vec![amt("USD", 400)]),
796
1
            ],
797
1
        }];
798

            
799
1
        let spec = breakdown_chart(
800
1
            &periods,
801
1
            BreakdownChartOpts {
802
1
                kind: ChartKind::Bar,
803
1
                top_n: 2,
804
1
            },
805
1
        )
806
1
        .expect("chart");
807

            
808
        // Top-2 clip leaves the two largest categories, in their listed order.
809
2
        let labels: Vec<&str> = spec.series.iter().map(|s| s.label.as_str()).collect();
810
1
        assert_eq!(labels, ["c", "d"]);
811
1
        assert!(spec.notes.iter().any(|n| n.contains("top 2")));
812
1
    }
813

            
814
    #[test]
815
1
    fn breakdown_chart_keeps_the_report_order_across_periods() {
816
1
        let periods = vec![
817
1
            BreakdownPeriodView {
818
1
                label: "2025-Q1".to_string(),
819
1
                rows: vec![
820
1
                    brow("food", vec![amt("USD", 150)]),
821
1
                    brow("salary", vec![amt("USD", -3000)]),
822
1
                ],
823
1
            },
824
1
            BreakdownPeriodView {
825
1
                label: "2025-Q2".to_string(),
826
1
                rows: vec![
827
1
                    brow("housing", vec![amt("USD", 800)]),
828
1
                    brow("salary", vec![amt("USD", -3000)]),
829
1
                ],
830
1
            },
831
        ];
832

            
833
1
        let spec = breakdown_chart(
834
1
            &periods,
835
1
            BreakdownChartOpts {
836
1
                kind: ChartKind::Bar,
837
1
                top_n: 10,
838
1
            },
839
1
        )
840
1
        .expect("chart");
841

            
842
3
        let labels: Vec<&str> = spec.series.iter().map(|s| s.label.as_str()).collect();
843
1
        assert_eq!(labels, ["food", "salary", "housing"]);
844
1
    }
845

            
846
    #[test]
847
1
    fn breakdown_chart_flat_relabels_uncategorized_sentinel() {
848
1
        let periods = vec![BreakdownPeriodView {
849
1
            label: String::new(),
850
1
            rows: vec![
851
1
                brow("food", vec![amt("USD", 400)]),
852
1
                BreakdownRowView {
853
1
                    tag_value: "__uncategorized__".to_string(),
854
1
                    is_uncategorized: true,
855
1
                    amounts: vec![amt("USD", 50)],
856
1
                },
857
1
            ],
858
1
        }];
859

            
860
1
        let spec = breakdown_chart(
861
1
            &periods,
862
1
            BreakdownChartOpts {
863
1
                kind: ChartKind::Bar,
864
1
                top_n: 10,
865
1
            },
866
1
        )
867
1
        .expect("chart");
868

            
869
1
        let uncategorized = spec
870
1
            .series
871
1
            .iter()
872
2
            .find(|s| s.label == "(uncategorized)")
873
1
            .expect("pretty label replaces sentinel");
874
1
        assert_eq!(uncategorized.points[0].x, "(uncategorized)");
875
1
        assert!(
876
2
            !spec.series.iter().any(|s| s.label == "__uncategorized__"),
877
            "sentinel must not leak into the chart"
878
        );
879
1
    }
880

            
881
    #[test]
882
1
    fn a_tag_whose_period_totals_overflow_is_a_report_error() {
883
        let period = |label: &str| BreakdownPeriodView {
884
2
            label: label.to_string(),
885
2
            rows: vec![brow("food", vec![amt("USD", i64::MAX)])],
886
2
        };
887
1
        let err = breakdown_chart(
888
1
            &[period("Q1"), period("Q2")],
889
1
            BreakdownChartOpts {
890
1
                kind: ChartKind::Bar,
891
1
                top_n: 10,
892
1
            },
893
1
        )
894
1
        .unwrap_err();
895
1
        assert!(matches!(err, ReportError::AmountOverflow), "{err:?}");
896
1
    }
897

            
898
    #[test]
899
1
    fn an_i64_min_balance_ranks_as_the_largest_without_wrapping() {
900
1
        let rows = vec![
901
1
            row("Debt", 0, vec![amt("USD", i64::MIN)]),
902
1
            row("Cash", 0, vec![amt("USD", 100)]),
903
        ];
904
1
        let spec = balance_chart(
905
1
            &rows,
906
1
            BalanceChartOpts {
907
1
                kind: ChartKind::Bar,
908
1
                top_n: 1,
909
1
                sort_order: SortOrder::MagnitudeDesc,
910
1
            },
911
1
        );
912
1
        assert_eq!(spec.series[0].points[0].x, "Debt");
913
1
    }
914
}