1
//! The reports tab shows each report as an exact table, in the server's row order.
2

            
3
use super::*;
4
use crate::event::Intent;
5
use ratatui::Terminal;
6
use ratatui::backend::TestBackend;
7

            
8
const ID: &str = "00000000-0000-0000-0000-000000000000";
9
const LONG: &str = "123456789012345/1000";
10
const LONG_SHOWN: &str = "123456789012.345";
11

            
12
14
fn envelope(body: &str) -> String {
13
14
    let escaped = body.replace('\\', "\\\\").replace('"', "\\\"");
14
14
    format!("(:id 1 :value \"{escaped}\")")
15
14
}
16

            
17
218
fn amounts(amount: &str) -> String {
18
218
    format!("((:commodity-id \"{ID}\" :symbol \"USD\" :amount {amount}))")
19
218
}
20

            
21
4
fn amount_entry(symbol: &str, amount: &str) -> String {
22
4
    format!("(:commodity-id \"{ID}\" :symbol \"{symbol}\" :amount {amount})")
23
4
}
24

            
25
6
fn root(name: &str, amount: &str) -> String {
26
6
    format!(
27
6
        "(:account-id \"{ID}\" :account-name \"{name}\" :account-path \"{name}\" :depth 0 \
28
         :account-type nil :amounts {} :own-amounts {} :children ())",
29
6
        amounts(amount),
30
6
        amounts(amount)
31
    )
32
6
}
33

            
34
13
fn loaded(kind: ReportKind, body: &str) -> ReportsTab {
35
13
    let mut tab = ReportsTab::new();
36
13
    tab.on_reply(&envelope(body), kind, FormValues::default());
37
13
    assert!(matches!(tab.state, Fetch::Loaded(_)), "{:?}", tab.state);
38
13
    tab
39
13
}
40

            
41
12
fn screen(tab: &ReportsTab) -> Vec<String> {
42
12
    let mut terminal = Terminal::new(TestBackend::new(100, 20)).expect("test terminal");
43
12
    terminal
44
12
        .draw(|frame| {
45
12
            let area = frame.area();
46
12
            tab.draw(
47
12
                frame.buffer_mut(),
48
12
                area,
49
12
                &mut crate::test_support::draw_ctx(
50
12
                    &crate::test_support::dn_theme(),
51
12
                    &mut crate::hits::Hits::default(),
52
12
                ),
53
12
            )
54
12
        })
55
12
        .expect("draw");
56
12
    let buffer = terminal.backend().buffer();
57
12
    buffer
58
12
        .content()
59
12
        .chunks(100)
60
24000
        .map(|row| row.iter().map(|c| c.symbol()).collect::<String>())
61
        .collect()
62
12
}
63

            
64
2
fn line_count(tab: &ReportsTab) -> usize {
65
2
    match &tab.state {
66
2
        Fetch::Loaded(lines) => lines.len(),
67
        _ => 0,
68
    }
69
2
}
70

            
71
8
fn row_of(lines: &[String], label: &str) -> usize {
72
8
    lines
73
8
        .iter()
74
36
        .position(|l| l.contains(label))
75
        .unwrap_or_else(|| panic!("{label} missing in {lines:#?}"))
76
8
}
77

            
78
3
fn assert_exact_values(lines: &[String], negative: &str, fraction: &str) {
79
3
    let text = lines.join("\n");
80
3
    assert!(text.contains(negative), "{text}");
81
3
    assert!(text.contains(fraction), "{text}");
82
3
    assert!(text.contains(LONG_SHOWN), "{text}");
83
3
    assert!(!text.contains('█'), "{text}");
84
3
}
85

            
86
#[test]
87
1
fn balance_table_shows_negative_fractional_and_long_amounts() {
88
1
    let roots = [
89
1
        root("Assets", LONG),
90
1
        root("Debts", "-7"),
91
1
        root("Loan", "1/3"),
92
1
    ]
93
1
    .join(" ");
94
1
    let tab = loaded(
95
1
        ReportKind::Balance,
96
1
        &format!("(:balance-report :periods ((:label nil :roots ({roots}))))"),
97
1
    );
98
1
    assert_exact_values(&screen(&tab), "-7", "1/3");
99
1
}
100

            
101
#[test]
102
1
fn activity_table_shows_negative_fractional_and_long_amounts() {
103
3
    let group = |label: &str, flip: &str, amount: &str| {
104
3
        format!(
105
3
            "(:label \"{label}\" :flip-sign {flip} :roots ({}) :total ())",
106
3
            root("Acc", amount)
107
        )
108
3
    };
109
1
    let groups = [
110
1
        group("Big", "nil", LONG),
111
1
        group("Spend", "nil", "-7"),
112
1
        group("Third", "nil", "1/3"),
113
1
    ]
114
1
    .join(" ");
115
1
    let tab = loaded(
116
1
        ReportKind::Activity,
117
1
        &format!(
118
1
            "(:activity-report :meta nil :periods ((:label \"Q1\" :groups ({groups}) :net ())))"
119
1
        ),
120
1
    );
121
1
    let lines = screen(&tab);
122
1
    assert_exact_values(&lines, "-7", "1/3");
123
1
    assert!(row_of(&lines, "Big") < row_of(&lines, "Spend"));
124
1
    assert!(row_of(&lines, "Spend") < row_of(&lines, "Third"));
125
1
}
126

            
127
#[test]
128
1
fn category_table_keeps_the_server_row_order() {
129
3
    let row = |tag: &str, amount: &str| {
130
3
        format!(
131
3
            "(:tag-value \"{tag}\" :uncategorized nil :amounts {})",
132
3
            amounts(amount)
133
        )
134
3
    };
135
1
    let rows = [row("Zeta", "-7"), row("Alpha", "1/3"), row("Mid", LONG)].join(" ");
136
1
    let tab = loaded(
137
1
        ReportKind::Breakdown,
138
1
        &format!(
139
1
            "(:category-breakdown :meta nil :tag-name \"category\" :periods ((:label nil :rows ({rows}))))"
140
1
        ),
141
1
    );
142
1
    let lines = screen(&tab);
143
1
    assert_exact_values(&lines, "-7", "1/3");
144
1
    assert!(row_of(&lines, "Zeta") < row_of(&lines, "Alpha"));
145
1
    assert!(row_of(&lines, "Alpha") < row_of(&lines, "Mid"));
146
1
}
147

            
148
6
fn tall_category(rows: usize) -> ReportsTab {
149
6
    let body: Vec<String> = (0..rows)
150
203
        .map(|i| {
151
203
            format!(
152
203
                "(:tag-value \"Row{i:02}\" :uncategorized nil :amounts {})",
153
203
                amounts(&format!("{i}"))
154
            )
155
203
        })
156
        .collect();
157
6
    loaded(
158
6
        ReportKind::Breakdown,
159
6
        &format!(
160
6
            "(:category-breakdown :meta nil :tag-name \"category\" :periods ((:label nil :rows ({}))))",
161
6
            body.join(" ")
162
6
        ),
163
6
    )
164
6
}
165

            
166
#[test]
167
1
fn a_report_taller_than_the_pane_keeps_every_row_and_scrolls_to_the_last() {
168
1
    let tab = tall_category(40);
169
1
    let first = screen(&tab).join("\n");
170
1
    assert!(
171
1
        first.contains("Row00") && !first.contains("Row39"),
172
        "{first}"
173
    );
174
1
    for _ in 0..10 {
175
10
        assert!(tab.scroll_by(Intent::ScrollPageDown));
176
    }
177
1
    let last = screen(&tab).join("\n");
178
1
    assert!(last.contains("Row39") && !last.contains("Row00"), "{last}");
179
1
    assert!(tab.scroll_by(Intent::ScrollLineUp));
180
1
    assert!(screen(&tab).join("\n").contains("Row38"));
181
1
}
182

            
183
#[test]
184
1
fn scroll_stops_at_the_first_and_last_line() {
185
1
    let tab = tall_category(40);
186
1
    screen(&tab);
187
1
    assert!(tab.scroll_by(Intent::ScrollLineUp));
188
1
    assert_eq!(tab.scroll.top(), 0);
189
1
    for _ in 0..20 {
190
20
        assert!(tab.scroll_by(Intent::ScrollPageDown));
191
    }
192
1
    assert_eq!(tab.scroll.top(), line_count(&tab) - 18);
193
1
}
194

            
195
#[test]
196
1
fn a_new_report_resets_the_scroll() {
197
1
    let mut tab = tall_category(40);
198
1
    screen(&tab);
199
1
    assert!(tab.scroll_by(Intent::ScrollPageDown));
200
1
    assert!(tab.scroll.top() > 0);
201
1
    tab.set_loading(2, ReportKind::Breakdown, &FormValues::default());
202
1
    assert_eq!(tab.scroll.top(), 0);
203
1
    assert!(tab.scroll_by(Intent::ScrollPageDown));
204
1
    tab.on_reply(
205
1
        &envelope("(:category-breakdown :meta nil :tag-name \"category\" :periods nil)"),
206
1
        ReportKind::Breakdown,
207
1
        FormValues::default(),
208
1
    );
209
1
    assert_eq!(tab.scroll.top(), 0);
210
1
}
211

            
212
#[test]
213
1
fn non_scroll_intents_are_not_consumed() {
214
1
    assert!(!ReportsTab::new().scroll_by(Intent::ListSelectNext));
215
1
}
216

            
217
const EUR_ID: &str = "11111111-1111-1111-1111-111111111111";
218

            
219
20
fn money(entries: &[(&str, &str)]) -> String {
220
20
    let items: Vec<String> = entries
221
20
        .iter()
222
25
        .map(|(sym, amount)| {
223
25
            let id = if *sym == "EUR" { EUR_ID } else { ID };
224
25
            format!("(:commodity-id \"{id}\" :symbol \"{sym}\" :amount {amount})")
225
25
        })
226
        .collect();
227
20
    format!("({})", items.join(" "))
228
20
}
229

            
230
8
fn node(name: &str, depth: usize, entries: &[(&str, &str)], children: &[String]) -> String {
231
8
    format!(
232
8
        "(:account-id \"{ID}\" :account-name \"{name}\" :account-path \"{name}\" :depth {depth} \
233
         :account-type nil :amounts {} :own-amounts {} :children ({}))",
234
8
        money(entries),
235
8
        money(entries),
236
8
        children.join(" ")
237
    )
238
8
}
239

            
240
2
fn nested_roots() -> String {
241
2
    let checking = node("Checking", 1, &[("USD", "100")], &[]);
242
2
    let euro = node("Euro", 1, &[("EUR", "-5/3")], &[]);
243
2
    let assets = node(
244
2
        "Assets",
245
2
        0,
246
2
        &[("USD", "100"), ("EUR", "-5/3")],
247
2
        &[checking, euro],
248
2
    );
249
2
    let rent = node("Rent", 0, &[("USD", "7")], &[]);
250
2
    [assets, rent].join(" ")
251
2
}
252

            
253
4
fn lines_of(tab: &ReportsTab) -> Vec<String> {
254
4
    match &tab.state {
255
4
        Fetch::Loaded(lines) => lines.clone(),
256
        other => panic!("expected Loaded, got {other:?}"),
257
    }
258
4
}
259

            
260
#[test]
261
1
fn balance_table_lists_sub_accounts_and_every_commodity_in_reply_order() {
262
1
    let tab = loaded(
263
1
        ReportKind::Balance,
264
1
        &format!(
265
1
            "(:balance-report :periods ((:label nil :roots ({}))))",
266
1
            nested_roots()
267
1
        ),
268
1
    );
269
1
    assert_eq!(
270
1
        lines_of(&tab),
271
1
        [
272
1
            "  Assets      100.00 USD, -5/3 EUR",
273
1
            "    Checking  100.00 USD",
274
1
            "    Euro      -5/3 EUR",
275
1
            "  Rent        7.00 USD",
276
1
        ]
277
    );
278
1
}
279

            
280
#[test]
281
1
fn activity_table_lists_sub_accounts_and_every_commodity() {
282
1
    let group = format!(
283
        "(:label \"Spend\" :flip-sign nil :roots ({}) :total ({USD} {EUR}))",
284
1
        nested_roots(),
285
1
        USD = amount_entry("USD", "107"),
286
1
        EUR = amount_entry("EUR", "-5/3"),
287
    );
288
1
    let tab = loaded(
289
1
        ReportKind::Activity,
290
1
        &format!(
291
1
            "(:activity-report :meta nil :periods ((:label \"Q1\" :groups ({group}) :net ({} {}))))",
292
1
            amount_entry("USD", "-107"),
293
1
            amount_entry("EUR", "5/3"),
294
1
        ),
295
1
    );
296
1
    assert_eq!(
297
1
        lines_of(&tab),
298
1
        [
299
1
            "Q1",
300
1
            "Spend",
301
1
            "  Assets      100.00 USD, -5/3 EUR",
302
1
            "    Checking  100.00 USD",
303
1
            "    Euro      -5/3 EUR",
304
1
            "  Rent        7.00 USD",
305
1
            "  Total       107.00 USD, -5/3 EUR",
306
1
            "  Net         -107.00 USD, 5/3 EUR",
307
1
        ]
308
    );
309
1
}
310

            
311
#[test]
312
1
fn category_table_lists_every_commodity_of_a_row() {
313
2
    let row = |tag: &str, entries: &[(&str, &str)]| {
314
2
        format!(
315
2
            "(:tag-value \"{tag}\" :uncategorized nil :amounts {})",
316
2
            money(entries)
317
        )
318
2
    };
319
1
    let rows = [
320
1
        row("Food", &[("USD", "3"), ("EUR", "1/3")]),
321
1
        row("Fun", &[("EUR", "2")]),
322
1
    ]
323
1
    .join(" ");
324
1
    let tab = loaded(
325
1
        ReportKind::Breakdown,
326
1
        &format!(
327
1
            "(:category-breakdown :meta nil :tag-name \"category\" :periods ((:label nil :rows ({rows}))))"
328
1
        ),
329
1
    );
330
1
    assert_eq!(
331
1
        lines_of(&tab),
332
1
        ["  Food  3.00 USD, 1/3 EUR", "  Fun   2.00 EUR"]
333
    );
334
1
}
335

            
336
#[test]
337
1
fn category_table_labels_the_uncategorized_row_as_the_web_does() {
338
1
    let rows = format!(
339
        "(:tag-value \"Food\" :uncategorized nil :amounts {}) \
340
         (:tag-value \"__uncategorized__\" :uncategorized t :amounts {})",
341
1
        money(&[("USD", "3")]),
342
1
        money(&[("USD", "4")])
343
    );
344
1
    let tab = loaded(
345
1
        ReportKind::Breakdown,
346
1
        &format!(
347
1
            "(:category-breakdown :meta nil :tag-name \"category\" :periods ((:label nil :rows ({rows}))))"
348
1
        ),
349
1
    );
350
1
    assert_eq!(
351
1
        lines_of(&tab),
352
1
        ["  Food             3.00 USD", "  (uncategorized)  4.00 USD"]
353
    );
354
1
}
355

            
356
#[test]
357
1
fn a_long_report_shows_the_bar_and_the_visible_range_and_stops_at_the_last_page() {
358
1
    let tab = tall_category(40);
359
1
    let total = line_count(&tab);
360
1
    let first = screen(&tab);
361
1
    assert!(
362
1
        first[0].contains('▲') || first[1].contains('▲'),
363
        "{first:?}"
364
    );
365
1
    assert!(
366
1
        first[19].contains(&format!("1\u{2013}18 of {total}")),
367
        "{}",
368
        first[19]
369
    );
370
1
    for _ in 0..20 {
371
20
        assert!(tab.scroll_by(Intent::ScrollPageDown));
372
    }
373
1
    let last = screen(&tab);
374
1
    assert_eq!(tab.scroll.top(), total - 18);
375
1
    assert!(last[18].contains("Row39"), "{}", last[18]);
376
1
    assert!(last[1].contains("Row"), "{}", last[1]);
377
1
    let range = format!("{}\u{2013}{total} of {total}", total - 17);
378
1
    assert!(last[19].contains(&range), "{}", last[19]);
379
1
}
380

            
381
#[test]
382
1
fn the_bar_sits_on_the_right_border_and_a_short_report_has_none() {
383
1
    let tab = tall_category(40);
384
1
    let long = screen(&tab);
385
1
    let bar: String = long[1..19]
386
1
        .iter()
387
18
        .filter_map(|row| row.chars().last())
388
        .collect();
389
1
    assert!(bar.starts_with('▲') && bar.ends_with('▼'), "{bar}");
390
1
    let short = screen(&tall_category(3));
391
1
    assert!(
392
1
        short
393
1
            .iter()
394
20
            .all(|row| !row.contains('▲') && !row.contains(" of "))
395
    );
396
1
}