1
//! The Accounts tab's Balance column comes from `balance-report`, one call per list.
2

            
3
use crate::tabs::nms_eval::double::Sent;
4
use ratatui::Terminal;
5
use ratatui::backend::TestBackend;
6
use ratatui::layout::Rect;
7

            
8
use super::App;
9
use crate::route::{Route, RouteCtx};
10
use crate::tabs::fetch::Fetch;
11
use crate::view::{Tab, ViewId};
12

            
13
const A: &str = "00000000-0000-0000-0000-00000000000a";
14
const B: &str = "00000000-0000-0000-0000-00000000000b";
15
const C: &str = "00000000-0000-0000-0000-00000000000c";
16
const COMMODITY: &str = "00000000-0000-0000-0000-0000000000cc";
17

            
18
22
fn amount(symbol: &str, value: &str) -> String {
19
22
    format!(r#"(:commodity-id "{COMMODITY}" :symbol "{symbol}" :amount {value})"#)
20
22
}
21

            
22
18
fn node(id: &str, amounts: &[String], own: &[String], children: &[String]) -> String {
23
18
    format!(
24
18
        r#"(:account-id "{id}" :account-name "n" :account-path "n" :depth 0 :account-type nil :amounts ({}) :own-amounts ({}) :children ({}))"#,
25
18
        amounts.join(" "),
26
18
        own.join(" "),
27
18
        children.join(" ")
28
    )
29
18
}
30

            
31
16
fn leaf(id: &str, amounts: &[String]) -> String {
32
16
    node(id, amounts, amounts, &[])
33
16
}
34

            
35
14
fn report_wire(id: i64, nodes: &[String]) -> String {
36
14
    let body = format!(
37
        "(:balance-report :periods ((:label nil :roots ({}))))",
38
14
        nodes.join(" ")
39
    );
40
14
    let escaped = body.replace('\\', "\\\\").replace('"', "\\\"");
41
14
    format!("(:id {id} :value \"{escaped}\")")
42
14
}
43

            
44
17
fn accounts_wire() -> String {
45
17
    let rows: Vec<String> = [(A, "Cash"), (B, "Wallet"), (C, "Bank")]
46
17
        .iter()
47
51
        .map(|(id, name)| format!(r#"(:account :id "{id}" :name "{name}" :parent "")"#))
48
        .collect();
49
17
    format!("(:id 1 :value ({}))", rows.join(" "))
50
17
}
51

            
52
17
fn load_accounts(app: &mut App) {
53
17
    app.refresh_windows(Tab::Accounts);
54
17
    let Fetch::Loading { id } = app.accounts().state else {
55
        panic!("accounts not loading: {:?}", app.accounts().state);
56
    };
57
17
    app.route_reply(id, &accounts_wire());
58
17
}
59

            
60
18
fn balance_requests(app: &App) -> Vec<i64> {
61
18
    let mut ids: Vec<i64> = app
62
18
        .pending_routes
63
18
        .iter()
64
20
        .filter(|(_, route)| matches!(route.ctx, RouteCtx::AccountBalances { .. }))
65
19
        .map(|(id, _)| *id)
66
        .collect();
67
18
    ids.sort_unstable();
68
18
    ids
69
18
}
70

            
71
17
pub(super) fn the_balance_request(app: &App) -> i64 {
72
17
    let [id] = balance_requests(app)[..] else {
73
        panic!("one balance-report request expected");
74
    };
75
17
    id
76
17
}
77

            
78
15
fn connected() -> (App, Sent) {
79
15
    let mut app = crate::test_support::app();
80
15
    let sent = app.attach_echo();
81
15
    (app, sent)
82
15
}
83

            
84
28
pub(super) fn row<'a>(lines: &'a [String], name: &str) -> &'a str {
85
28
    lines
86
28
        .iter()
87
106
        .find(|line| line.contains(name))
88
28
        .map_or("", String::as_str)
89
28
}
90

            
91
21
pub(super) fn drawn(app: &App, width: u16) -> Vec<String> {
92
21
    let mut terminal = Terminal::new(TestBackend::new(width, 8)).expect("terminal");
93
21
    let theme = crate::test_support::dn_theme();
94
21
    let mut hits = crate::hits::Hits::default();
95
21
    let mut ctx = crate::test_support::draw_ctx(&theme, &mut hits);
96
21
    ctx.title = "Accounts".to_string();
97
21
    terminal
98
21
        .draw(|f| {
99
21
            app.accounts()
100
21
                .draw(f.buffer_mut(), Rect::new(0, 0, width, 8), &mut ctx);
101
21
        })
102
21
        .expect("draw");
103
21
    let buf = terminal.backend().buffer().clone();
104
21
    (0..buf.area.height)
105
168
        .map(|y| {
106
168
            (0..buf.area.width)
107
13440
                .map(|x| buf.cell((x, y)).map_or(" ", |c| c.symbol()))
108
                .collect()
109
168
        })
110
        .collect()
111
21
}
112

            
113
14
fn cash(app: &App, width: u16) -> String {
114
14
    row(&drawn(app, width), "Cash").to_string()
115
14
}
116

            
117
#[tokio::test]
118
1
async fn the_reply_fills_the_balance_of_each_visible_account() {
119
1
    let (mut app, _) = connected();
120
1
    load_accounts(&mut app);
121
1
    assert!(cash(&app, 80).contains('…'), "loading cells show …");
122
1
    let id = the_balance_request(&app);
123
1
    let nodes = [
124
1
        leaf(A, &[amount("USD", "10")]),
125
1
        leaf(C, &[amount("EUR", "1/3")]),
126
1
    ];
127
1
    app.route_reply(id, &report_wire(id, &nodes));
128

            
129
1
    let lines = drawn(&app, 80);
130
1
    assert!(row(&lines, "Name").contains("Balance"), "{lines:?}");
131
1
    assert!(row(&lines, "Cash").contains("10.00 USD"), "{lines:?}");
132
1
    assert!(row(&lines, "Bank").contains("1/3 EUR"), "{lines:?}");
133
1
    assert!(
134
1
        row(&lines, "Wallet")
135
1
            .trim_end_matches(['║', ' '])
136
1
            .ends_with('0')
137
1
    );
138
1
}
139

            
140
#[tokio::test]
141
1
async fn a_multi_commodity_account_shows_every_commodity() {
142
1
    let (mut app, _) = connected();
143
1
    load_accounts(&mut app);
144
1
    let id = the_balance_request(&app);
145
1
    let nodes = [leaf(A, &[amount("EUR", "5"), amount("USD", "10")])];
146
1
    app.route_reply(id, &report_wire(id, &nodes));
147
1
    assert!(cash(&app, 80).contains("5.00 EUR, 10.00 USD"));
148
1
}
149

            
150
#[tokio::test]
151
1
async fn a_parent_shows_only_its_own_balance() {
152
1
    let (mut app, _) = connected();
153
1
    load_accounts(&mut app);
154
1
    let id = the_balance_request(&app);
155
1
    let parent = node(
156
1
        A,
157
1
        &[amount("USD", "30")],
158
1
        &[amount("USD", "10")],
159
1
        &[leaf(C, &[amount("USD", "20")])],
160
1
    );
161
1
    app.route_reply(id, &report_wire(id, &[parent]));
162

            
163
1
    let lines = drawn(&app, 80);
164
1
    assert!(row(&lines, "Cash").contains("10.00 USD"), "{lines:?}");
165
1
    assert!(row(&lines, "Bank").contains("20.00 USD"), "{lines:?}");
166
1
}
167

            
168
#[tokio::test]
169
1
async fn commodities_sharing_a_symbol_show_as_separate_amounts() {
170
1
    let (mut app, _) = connected();
171
1
    load_accounts(&mut app);
172
1
    let id = the_balance_request(&app);
173
1
    let one = r#"(:commodity-id "00000000-0000-0000-0000-000000000001" :symbol "$" :amount 10)"#;
174
1
    let two = r#"(:commodity-id "00000000-0000-0000-0000-000000000002" :symbol "$" :amount 5)"#;
175
1
    let own = [one.to_string(), two.to_string()];
176
1
    app.route_reply(id, &report_wire(id, &[leaf(A, &own)]));
177
1
    assert!(cash(&app, 80).contains("10.00 $, 5.00 $"));
178
1
}
179

            
180
#[tokio::test]
181
1
async fn a_pure_container_parent_shows_zero() {
182
1
    let (mut app, _) = connected();
183
1
    load_accounts(&mut app);
184
1
    let id = the_balance_request(&app);
185
1
    let parent = node(
186
1
        A,
187
1
        &[amount("USD", "20")],
188
1
        &[amount("USD", "0")],
189
1
        &[leaf(C, &[amount("USD", "20")])],
190
1
    );
191
1
    app.route_reply(id, &report_wire(id, &[parent]));
192

            
193
1
    let lines = drawn(&app, 80);
194
1
    assert!(!row(&lines, "Cash").contains("USD"), "{lines:?}");
195
1
    assert!(
196
1
        row(&lines, "Cash")
197
1
            .trim_end_matches(['║', ' '])
198
1
            .ends_with('0')
199
1
    );
200
1
}
201

            
202
#[tokio::test]
203
1
async fn a_stale_reply_is_dropped() {
204
1
    let (mut app, _) = connected();
205
1
    load_accounts(&mut app);
206
1
    load_accounts(&mut app);
207
1
    let [stale, current] = balance_requests(&app)[..] else {
208
        panic!("two balance-report requests expected");
209
    };
210
1
    app.route_reply(
211
1
        stale,
212
1
        &report_wire(stale, &[leaf(A, &[amount("USD", "99")])]),
213
1
    );
214
1
    assert!(!cash(&app, 80).contains("99"));
215

            
216
1
    app.route_reply(
217
1
        current,
218
1
        &report_wire(current, &[leaf(A, &[amount("USD", "7")])]),
219
1
    );
220
1
    assert!(cash(&app, 80).contains("7.00 USD"));
221
1
}
222

            
223
#[tokio::test]
224
1
async fn an_error_leaves_no_numbers_and_says_why() {
225
1
    let (mut app, _) = connected();
226
1
    load_accounts(&mut app);
227
1
    let id = the_balance_request(&app);
228
1
    app.route_reply(
229
1
        id,
230
1
        &format!(r#"(:id {id} :error (:code server-error :message "no prices"))"#),
231
1
    );
232

            
233
1
    assert!(app.status.contains("balances failed"), "{}", app.status);
234
1
    assert!(app.status.contains("no prices"), "{}", app.status);
235
1
    let lines = drawn(&app, 80);
236
1
    let cells = row(&lines, "Cash");
237
1
    assert!(!cells.contains("USD") && !cells.contains('0') && !cells.contains('…'));
238
1
    assert!(matches!(app.accounts().state, Fetch::Loaded(_)));
239
1
}
240

            
241
#[tokio::test]
242
1
async fn a_refresh_reloads_the_balances() {
243
1
    let (mut app, _) = connected();
244
1
    load_accounts(&mut app);
245
1
    let first = the_balance_request(&app);
246
1
    app.route_reply(
247
1
        first,
248
1
        &report_wire(first, &[leaf(A, &[amount("USD", "10")])]),
249
1
    );
250
1
    load_accounts(&mut app);
251
1
    let line = cash(&app, 80);
252
1
    assert!(!line.contains("USD") && line.contains('…'), "{line}");
253
1
    assert_ne!(first, the_balance_request(&app));
254
1
}
255

            
256
#[tokio::test]
257
1
async fn a_transaction_mutation_refetches_the_balances() {
258
1
    let (mut app, _) = connected();
259
1
    load_accounts(&mut app);
260
1
    let first = the_balance_request(&app);
261
1
    app.route_reply(
262
1
        first,
263
1
        &report_wire(first, &[leaf(A, &[amount("USD", "10")])]),
264
1
    );
265
1
    assert!(cash(&app, 80).contains("10.00 USD"));
266

            
267
1
    app.deliver_reply(
268
1
        Route {
269
1
            target: Some(app.window_of(ViewId::Transactions)),
270
1
            ctx: RouteCtx::Mutation {
271
1
                refresh: ViewId::Transactions,
272
1
            },
273
1
        },
274
1
        "(:id 9 :value 1)",
275
1
    );
276
1
    let second = the_balance_request(&app);
277
1
    assert_ne!(first, second);
278
1
    assert!(!cash(&app, 80).contains("USD"));
279
1
    app.route_reply(
280
1
        second,
281
1
        &report_wire(second, &[leaf(A, &[amount("USD", "15")])]),
282
1
    );
283
1
    assert!(cash(&app, 80).contains("15.00 USD"));
284
1
}
285

            
286
2
fn with_long_balance(app: &mut App) {
287
2
    load_accounts(app);
288
2
    let id = the_balance_request(app);
289
2
    let nodes = [leaf(
290
2
        A,
291
2
        &[amount("EUR", "24691/2"), amount("USD", "22713/4")],
292
2
    )];
293
2
    app.route_reply(id, &report_wire(id, &nodes));
294
2
}
295

            
296
#[tokio::test]
297
1
async fn a_long_balance_shows_whole_amounts_at_80_columns() {
298
1
    let (mut app, _) = connected();
299
1
    with_long_balance(&mut app);
300
1
    assert!(cash(&app, 80).contains("12345.50 EUR, 5678.25 USD"));
301
1
}
302

            
303
#[tokio::test]
304
1
async fn a_balance_that_does_not_fit_counts_the_hidden_amounts_and_never_cuts_one() {
305
1
    let (mut app, _) = connected();
306
1
    with_long_balance(&mut app);
307
1
    let line = cash(&app, 60);
308
1
    assert!(line.contains("12345.50 EUR, +1"), "{line}");
309
1
    assert!(!line.contains("5678"), "{line}");
310
1
}
311

            
312
#[tokio::test]
313
1
async fn the_balance_column_stays_aligned_at_80_columns() {
314
1
    let (mut app, _) = connected();
315
1
    load_accounts(&mut app);
316
1
    let id = the_balance_request(&app);
317
1
    let nodes = [
318
1
        leaf(A, &[amount("USD", "10")]),
319
1
        leaf(B, &[amount("USD", "250")]),
320
1
    ];
321
1
    app.route_reply(id, &report_wire(id, &nodes));
322

            
323
1
    let lines = drawn(&app, 80);
324
3
    let column = |line: &str, needle: &str| line.find(needle).map(|at| line[..at].chars().count());
325
1
    let header = column(row(&lines, "Name"), "Balance");
326
1
    assert!(header.is_some(), "{lines:?}");
327
1
    let amounts = column(row(&lines, "Cash"), "10.00 USD");
328
1
    assert_eq!(column(row(&lines, "Wallet"), "250.00 USD"), amounts);
329
1
    assert!(amounts.is_some(), "{lines:?}");
330
1
    assert!(
331
1
        header > amounts,
332
1
        "the header is centred over the amounts: {lines:?}"
333
1
    );
334
1
}
335

            
336
#[tokio::test]
337
1
async fn a_report_without_own_amounts_fails_instead_of_showing_zeros() {
338
1
    let (mut app, _) = connected();
339
1
    load_accounts(&mut app);
340
1
    let id = the_balance_request(&app);
341
1
    let body = format!(
342
1
        r#"(:balance-report :periods ((:label nil :roots ((:account-id "{A}" :account-name "n" :account-path "n" :depth 0 :account-type nil :amounts () :children ())))))"#
343
    );
344
1
    let escaped = body.replace('"', "\\\"");
345
1
    app.route_reply(id, &format!("(:id {id} :value \"{escaped}\")"));
346

            
347
1
    assert!(app.status.contains("own-amounts"), "{}", app.status);
348
1
    let line = cash(&app, 80);
349
1
    assert!(!line.contains('0') && !line.contains('…'), "{line}");
350
1
}
351

            
352
#[tokio::test]
353
1
async fn a_dispatch_that_cannot_start_fails_the_balances() {
354
1
    let (mut app, _) = connected();
355
1
    load_accounts(&mut app);
356
1
    app.break_console();
357
1
    app.fetch_account_balances(app.window_of(crate::view::ViewId::Accounts));
358

            
359
1
    assert!(!app.accounts().balances_loading());
360
1
    assert!(app.status.contains("balances failed"), "{}", app.status);
361
1
    assert!(!cash(&app, 80).contains('…'));
362
1
}
363

            
364
#[tokio::test]
365
1
async fn balances_without_a_console_say_it_is_unavailable() {
366
1
    let mut app = crate::test_support::app();
367
1
    app.fetch_account_balances(app.window_of(crate::view::ViewId::Accounts));
368

            
369
1
    assert!(app.status.contains("console unavailable"), "{}", app.status);
370
1
}
371

            
372
#[tokio::test]
373
1
async fn a_single_too_wide_amount_shows_a_count_not_the_loading_mark() {
374
1
    let (mut app, _) = connected();
375
1
    load_accounts(&mut app);
376
1
    let id = the_balance_request(&app);
377
1
    let wide = [amount("USD", "9223372036854775807")];
378
1
    app.route_reply(id, &report_wire(id, &[leaf(A, &wide)]));
379
1
    let line = cash(&app, 60);
380
1
    assert!(line.contains("+1") && !line.contains('…'), "{line}");
381
1
}