1
//! Reports tab keys: re-run, re-edit and open forms for the last report.
2

            
3
use crate::app::App;
4
use crate::event::{Intent, apply};
5
use crate::form::{Form, FormKind};
6
use crate::modal::Modal;
7
use crate::route::RouteCtx;
8
use crate::tabs::fetch::Fetch;
9
use crate::tabs::nms_eval::double::Sent;
10
use crate::tabs::reports::{ReportKind, ReportsTab};
11
use crate::test_support::{ctrl, key, press};
12
use crate::view::Tab;
13
use crate::view::ViewId;
14
use cli_core::transaction::submit_call;
15
use forms::FormValues;
16
use ratatui::crossterm::event::KeyCode;
17

            
18
22
fn connected() -> (App, Sent) {
19
22
    let mut app = crate::test_support::app();
20
22
    let sent = app.attach_echo();
21
22
    app.switch_tab(Tab::Reports);
22
22
    (app, sent)
23
22
}
24

            
25
15
fn values(pairs: &[(&str, &str)]) -> FormValues {
26
15
    let mut values = FormValues::default();
27
27
    pairs.iter().for_each(|(key, value)| values.set(key, value));
28
15
    values
29
15
}
30

            
31
6
fn activity() -> FormValues {
32
6
    values(&[
33
6
        ("from", "2026-01-01"),
34
6
        ("to", "2026-02-01"),
35
6
        ("grouping", "year"),
36
6
    ])
37
6
}
38

            
39
17
fn report_run(app: &App) -> i64 {
40
17
    app.pending_routes
41
17
        .iter()
42
19
        .find_map(|(id, route)| matches!(route.ctx, RouteCtx::Reports { .. }).then_some(*id))
43
17
        .expect("report request")
44
17
}
45

            
46
12
fn accepted_run(app: &mut App, kind: ReportKind, values: &FormValues) {
47
12
    app.submit_report(app.window_of(crate::view::ViewId::Reports), kind, values);
48
12
    let id = report_run(app);
49
12
    app.route_reply(id, EMPTY);
50
12
}
51

            
52
3
async fn echoed(app: &mut App, sent: &Sent) -> String {
53
3
    tokio::task::yield_now().await;
54
3
    app.drain_eval();
55
3
    sent.frames().join("\n")
56
3
}
57

            
58
6
fn top_form(app: &App) -> &Form {
59
6
    match app.overlays.top() {
60
6
        Some(Modal::Form(form)) => form,
61
        other => panic!("form expected, got {other:?}"),
62
    }
63
6
}
64

            
65
#[tokio::test]
66
1
async fn r_reruns_the_last_report_with_its_values() {
67
1
    let (mut app, sent) = connected();
68
1
    accepted_run(&mut app, ReportKind::Activity, &activity());
69
1
    echoed(&mut app, &sent).await;
70
1
    app.console_mut().scrollback.clear();
71
1
    press(&mut app, ctrl(KeyCode::Char('r')));
72
1
    assert!(matches!(app.reports().state, Fetch::Loading { .. }));
73
1
    let call = submit_call(ReportKind::Activity.descriptor(), &activity());
74
1
    assert!(echoed(&mut app, &sent).await.contains(&call));
75
1
}
76

            
77
#[tokio::test]
78
1
async fn r_with_nothing_run_says_so() {
79
1
    let (mut app, _) = connected();
80
1
    press(&mut app, ctrl(KeyCode::Char('r')));
81
1
    assert_eq!(app.status, "no report run yet");
82
1
    assert!(matches!(app.reports().state, Fetch::Idle));
83
1
}
84

            
85
#[tokio::test]
86
1
async fn e_with_nothing_run_says_so() {
87
1
    let (mut app, _) = connected();
88
1
    press(&mut app, key(KeyCode::Char('e')));
89
1
    assert_eq!(app.status, "no report run yet");
90
1
    assert!(app.overlays.is_empty());
91
1
}
92

            
93
#[tokio::test]
94
1
async fn e_reopens_the_form_prefilled_with_the_last_values() {
95
1
    let (mut app, _) = connected();
96
1
    accepted_run(&mut app, ReportKind::Activity, &activity());
97
1
    press(&mut app, key(KeyCode::Char('e')));
98
1
    let form = top_form(&app);
99
1
    assert_eq!(form.kind, FormKind::Report(ReportKind::Activity));
100
1
    let shown = form.values();
101
1
    assert_eq!(shown.text("from"), Some("2026-01-01"));
102
1
    assert_eq!(shown.text("to"), Some("2026-02-01"));
103
1
    assert_eq!(shown.text("grouping"), Some("year"));
104
1
}
105

            
106
#[tokio::test]
107
1
async fn a_form_submit_replaces_the_last_report() {
108
1
    let (mut app, _) = connected();
109
1
    accepted_run(&mut app, ReportKind::Activity, &activity());
110
1
    press(&mut app, key(KeyCode::Char('b')));
111
1
    apply(&mut app, Intent::Submit);
112
1
    let form = report_run(&app);
113
1
    app.route_reply(form, EMPTY);
114
1
    let (kind, _) = app.reports().last().cloned().expect("last report");
115
1
    assert_eq!(kind, ReportKind::Balance);
116
1
}
117

            
118
#[tokio::test]
119
1
async fn b_a_c_open_the_forms_with_defaults() {
120
1
    for (letter, kind) in [
121
1
        ('b', ReportKind::Balance),
122
1
        ('a', ReportKind::Activity),
123
1
        ('c', ReportKind::Breakdown),
124
1
    ] {
125
3
        let (mut app, _) = connected();
126
3
        press(&mut app, key(KeyCode::Char(letter)));
127
3
        assert_eq!(top_form(&app).kind, FormKind::Report(kind));
128
3
        assert!(app.reports().last().is_none());
129
1
    }
130
1
}
131

            
132
#[tokio::test]
133
1
async fn a_reply_older_than_the_latest_run_is_dropped() {
134
1
    let (mut app, _) = connected();
135
1
    app.submit_report(
136
1
        app.window_of(crate::view::ViewId::Reports),
137
1
        ReportKind::Balance,
138
1
        &values(&[("filter", "x")]),
139
1
    );
140
1
    let old = *app.pending_routes.keys().next().expect("first run");
141
1
    app.submit_report(
142
1
        app.window_of(crate::view::ViewId::Reports),
143
1
        ReportKind::Balance,
144
1
        &values(&[("filter", "y")]),
145
1
    );
146
1
    app.route_reply(old, r#"(:id 1 :error (:code boom :message "stale"))"#);
147
1
    assert!(matches!(app.reports().state, Fetch::Idle));
148
1
}
149

            
150
#[tokio::test]
151
1
async fn the_title_names_the_last_report_and_its_dates() {
152
1
    let (mut app, _) = connected();
153
1
    accepted_run(&mut app, ReportKind::Activity, &activity());
154
1
    assert_eq!(
155
1
        app.reports().title(),
156
1
        "Activity from=2026-01-01 to=2026-02-01"
157
1
    );
158
1
}
159

            
160
const EMPTY: &str = r#"(:id 1 :value "()")"#;
161
const REJECTED: &str = r#"(:id 1 :error (:code form-invalid :message "1 field invalid" :detail ((:FIELD "from" :MESSAGE "not a date"))))"#;
162

            
163
5
fn usd_options() -> String {
164
5
    let row = r#"(:id \"550e8400-e29b-41d4-a716-446655440001\" :label \"USD\")"#;
165
5
    format!(r#"(:id 1 :value "({row})")"#)
166
5
}
167

            
168
3
fn loading_id(app: &App) -> i64 {
169
3
    match app.reports().state {
170
3
        Fetch::Loading { id } => id,
171
        ref other => panic!("loading expected, got {other:?}"),
172
    }
173
3
}
174

            
175
10
fn run(app: &mut App, command: &str) {
176
10
    apply(app, Intent::OpenCommandLine);
177
10
    command
178
10
        .chars()
179
242
        .for_each(|c| apply(app, Intent::InsertChar(c)));
180
10
    apply(app, Intent::Submit);
181
10
}
182

            
183
#[tokio::test]
184
1
async fn an_opened_form_does_not_drop_the_pending_reply() {
185
1
    let (mut app, _) = connected();
186
1
    run(&mut app, "reports balance filter=x");
187
1
    let id = loading_id(&app);
188
1
    run(&mut app, "reports activity");
189
1
    apply(&mut app, Intent::CloseTopmost);
190
1
    app.route_reply(id, EMPTY);
191
1
    assert!(!matches!(app.reports().state, Fetch::Loading { .. }));
192
1
}
193

            
194
#[tokio::test]
195
1
async fn a_failed_lookup_does_not_drop_the_pending_reply() {
196
1
    let (mut app, _) = connected();
197
1
    run(&mut app, "reports balance filter=x");
198
1
    let id = loading_id(&app);
199
1
    run(&mut app, "reports balance target=XYZ");
200
1
    let lookup = *app
201
1
        .pending_routes
202
1
        .keys()
203
1
        .find(|key| **key != id)
204
1
        .expect("lookup request");
205
1
    app.route_reply(lookup, &usd_options());
206
1
    app.route_reply(id, EMPTY);
207
1
    assert!(!matches!(app.reports().state, Fetch::Loading { .. }));
208
1
}
209

            
210
#[tokio::test]
211
1
async fn a_rejected_form_over_a_loading_report_does_not_stick() {
212
1
    let (mut app, _) = connected();
213
1
    run(&mut app, "reports balance filter=x");
214
1
    let id = loading_id(&app);
215
1
    press(&mut app, key(KeyCode::Char('a')));
216
1
    apply(&mut app, Intent::Submit);
217
1
    app.route_reply(id, EMPTY);
218
1
    let form = report_run(&app);
219
1
    app.route_reply(form, REJECTED);
220
1
    assert!(matches!(app.reports().state, Fetch::Idle));
221
1
}
222

            
223
#[tokio::test]
224
1
async fn the_title_follows_the_shown_report_not_a_rejected_one() {
225
1
    let (mut app, _) = connected();
226
1
    accepted_run(&mut app, ReportKind::Balance, &values(&[("filter", "x")]));
227
1
    press(&mut app, key(KeyCode::Char('a')));
228
1
    apply(&mut app, Intent::Submit);
229
1
    let form = report_run(&app);
230
1
    app.route_reply(form, REJECTED);
231
1
    assert_eq!(app.reports().title(), "Balance");
232
1
}
233

            
234
#[tokio::test]
235
1
async fn a_rejected_submit_leaves_the_last_report_to_rerun_and_edit() {
236
1
    let (mut app, _) = connected();
237
1
    let balance = values(&[("filter", "x")]);
238
1
    accepted_run(&mut app, ReportKind::Balance, &balance);
239
1
    press(&mut app, key(KeyCode::Char('a')));
240
1
    apply(&mut app, Intent::Submit);
241
1
    let form = report_run(&app);
242
1
    app.route_reply(form, REJECTED);
243
1
    apply(&mut app, Intent::CloseTopmost);
244
1
    assert_eq!(app.reports().last(), Some(&(ReportKind::Balance, balance)));
245
1
    press(&mut app, key(KeyCode::Char('e')));
246
1
    let form = top_form(&app);
247
1
    assert_eq!(form.kind, FormKind::Report(ReportKind::Balance));
248
1
    assert_eq!(form.values().text("filter"), Some("x"));
249
1
}
250

            
251
#[tokio::test]
252
1
async fn a_rejected_palette_run_leaves_the_last_report_to_rerun_and_edit() {
253
1
    let (mut app, sent) = connected();
254
1
    let accepted = values(&[("filter", "x")]);
255
1
    accepted_run(&mut app, ReportKind::Balance, &accepted);
256
1
    run(&mut app, "reports balance filter=y");
257
1
    let id = report_run(&app);
258
1
    app.route_reply(id, REJECTED);
259
1
    assert!(matches!(app.reports().state, Fetch::Error(_)));
260
1
    assert_eq!(
261
1
        app.reports().last(),
262
1
        Some(&(ReportKind::Balance, accepted.clone()))
263
    );
264
1
    app.console_mut().scrollback.clear();
265
1
    press(&mut app, ctrl(KeyCode::Char('r')));
266
1
    let call = submit_call(ReportKind::Balance.descriptor(), &accepted);
267
1
    assert!(echoed(&mut app, &sent).await.contains(&call));
268
1
    press(&mut app, key(KeyCode::Char('e')));
269
1
    assert_eq!(top_form(&app).values().text("filter"), Some("x"));
270
1
}
271

            
272
#[tokio::test]
273
1
async fn b_a_c_and_e_supersede_a_pending_lookup() {
274
1
    for letter in ['b', 'a', 'c', 'e'] {
275
4
        let (mut app, _) = connected();
276
4
        accepted_run(&mut app, ReportKind::Balance, &values(&[("filter", "x")]));
277
4
        run(&mut app, "reports balance target=usd");
278
4
        let lookup = *app.pending_routes.keys().next().expect("lookup request");
279
4
        press(&mut app, key(KeyCode::Char(letter)));
280
4
        app.route_reply(lookup, &usd_options());
281
4
        assert!(
282
4
            !matches!(app.reports().state, Fetch::Loading { .. }),
283
1
            "{letter}"
284
1
        );
285
1
    }
286
1
}
287

            
288
#[tokio::test]
289
1
async fn a_refresh_reruns_only_the_windows_that_have_a_report() {
290
1
    let (mut app, _) = connected();
291
1
    let ran = app.window_of(ViewId::Reports);
292
1
    accepted_run(&mut app, ReportKind::Activity, &activity());
293
1
    let fresh = app.open_extra(ViewId::Reports);
294
1
    app.set_status("");
295
1
    apply(&mut app, Intent::RefreshTab);
296
1
    assert!(matches!(
297
1
        app.win::<ReportsTab>(ran).map(|tab| tab.state.clone()),
298
        Some(Fetch::Loading { .. })
299
    ));
300
1
    assert!(matches!(
301
1
        app.win::<ReportsTab>(fresh).map(|tab| tab.state.clone()),
302
        Some(Fetch::Idle)
303
    ));
304
1
    assert_eq!(app.status, "");
305
1
}
306

            
307
#[tokio::test]
308
1
async fn a_refresh_with_no_report_anywhere_says_so_once() {
309
1
    let (mut app, _) = connected();
310
1
    app.open_extra(ViewId::Reports);
311
1
    apply(&mut app, Intent::RefreshTab);
312
1
    assert_eq!(app.status, "no report run yet");
313
1
    assert!(app.pending_routes.is_empty());
314
1
}