1
//! `:reports <kind> key=value` through the palette: prefill, lookup and run rules.
2

            
3
use crate::app::App;
4
use crate::event::{Intent, apply};
5
use crate::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;
11
use cli_core::transaction::submit_call;
12
use forms::FormValues;
13

            
14
const USD: &str = "550e8400-e29b-41d4-a716-446655440001";
15

            
16
18
fn connected() -> (App, Sent) {
17
18
    let mut app = crate::test_support::app();
18
18
    let sent = app.attach_echo();
19
18
    (app, sent)
20
18
}
21

            
22
23
pub(super) fn run(app: &mut App, command: &str) {
23
23
    apply(app, Intent::OpenCommandLine);
24
23
    command
25
23
        .chars()
26
768
        .for_each(|c| apply(app, Intent::InsertChar(c)));
27
23
    apply(app, Intent::Submit);
28
23
}
29

            
30
11
pub(super) fn options(labels: &[&str]) -> String {
31
11
    let rows: String = labels
32
11
        .iter()
33
12
        .map(|label| format!(r#"(:id \"{USD}\" :label \"{label}\")"#))
34
        .collect();
35
11
    format!(r#"(:id 1 :value "({rows})")"#)
36
11
}
37

            
38
7
fn open_form(app: &App) -> &crate::form::Form {
39
7
    match app.overlays.top() {
40
7
        Some(Modal::Form(form)) => form,
41
        other => panic!("report form expected, got {other:?}"),
42
    }
43
7
}
44

            
45
/// The ids of the report lookups awaiting a reply, oldest first.
46
2
pub(super) fn lookup_ids(app: &App) -> Vec<i64> {
47
2
    let mut ids: Vec<i64> = app
48
2
        .pending_routes
49
2
        .iter()
50
3
        .filter(|(_, route)| matches!(route.ctx, RouteCtx::Lookup { .. }))
51
3
        .map(|(id, _)| *id)
52
        .collect();
53
2
    ids.sort_unstable();
54
2
    ids
55
2
}
56

            
57
1
fn lookup_pending(app: &App) -> bool {
58
1
    app.pending_routes
59
1
        .values()
60
1
        .any(|route| matches!(route.ctx, RouteCtx::Lookup { .. }))
61
1
}
62

            
63
#[tokio::test]
64
1
async fn a_non_date_arg_prefills_the_form_it_opens() {
65
1
    let (mut app, _) = connected();
66
1
    run(
67
1
        &mut app,
68
1
        "reports breakdown from=2026-01-01 tag=category grouping=Month sort=name_asc",
69
1
    );
70
1
    let form = open_form(&app);
71
1
    assert_eq!(form.kind, FormKind::Report(ReportKind::Breakdown));
72
1
    let values = form.values();
73
1
    assert_eq!(values.text("tag"), Some("category"));
74
1
    assert_eq!(values.text("grouping"), Some("month"));
75
1
    assert_eq!(values.text("sort"), Some("name_asc"));
76
1
    assert_eq!(values.text("from"), Some("2026-01-01"));
77
1
    assert_eq!(values.text("to"), Some(""));
78
1
}
79

            
80
#[tokio::test]
81
1
async fn an_unknown_key_errors_and_opens_nothing() {
82
1
    let (mut app, _) = connected();
83
1
    run(
84
1
        &mut app,
85
1
        "reports activity from=2026-01-01 to=2026-02-01 chart=bar",
86
1
    );
87
1
    assert!(
88
1
        app.status.starts_with("command error: ") && app.status.ends_with("unknown arg: chart")
89
    );
90
1
    assert!(app.overlays.is_empty());
91
1
    assert!(matches!(app.reports().state, Fetch::Idle));
92
1
}
93

            
94
2
async fn echoed(app: &mut App, sent: &Sent) -> String {
95
2
    tokio::task::yield_now().await;
96
2
    app.drain_eval();
97
2
    sent.frames().join("\n")
98
2
}
99

            
100
2
fn expected_call(kind: ReportKind, pairs: &[(&str, &str)]) -> String {
101
2
    let mut values = FormValues::default();
102
5
    pairs.iter().for_each(|(key, value)| values.set(key, value));
103
2
    submit_call(kind.descriptor(), &values)
104
2
}
105

            
106
#[tokio::test]
107
1
async fn all_required_fields_run_the_report_with_every_arg() {
108
1
    let (mut app, sent) = connected();
109
1
    run(
110
1
        &mut app,
111
1
        "reports breakdown from=2026-01-01 to=2026-02-01 tag=category grouping=Year",
112
1
    );
113
1
    assert!(app.overlays.is_empty());
114
1
    assert!(matches!(app.reports().state, Fetch::Loading { .. }));
115
1
    let call = expected_call(
116
1
        ReportKind::Breakdown,
117
1
        &[
118
1
            ("from", "2026-01-01"),
119
1
            ("to", "2026-02-01"),
120
1
            ("grouping", "year"),
121
1
            ("tag", "category"),
122
1
        ],
123
1
    );
124
1
    assert!(echoed(&mut app, &sent).await.contains(&call));
125
1
}
126

            
127
#[tokio::test]
128
1
async fn a_bare_command_opens_the_form_with_defaults() {
129
1
    for (kind, name) in [
130
1
        (ReportKind::Balance, "balance"),
131
1
        (ReportKind::Activity, "activity"),
132
1
        (ReportKind::Breakdown, "breakdown"),
133
1
    ] {
134
3
        let (mut app, _) = connected();
135
3
        run(&mut app, &format!("reports {name}"));
136
3
        assert_eq!(open_form(&app).kind, FormKind::Report(kind));
137
3
        assert!(matches!(app.reports().state, Fetch::Idle));
138
1
    }
139
1
}
140

            
141
#[tokio::test]
142
1
async fn balance_with_args_and_no_required_field_runs() {
143
1
    let (mut app, _) = connected();
144
1
    run(&mut app, "reports balance filter=x");
145
1
    assert!(app.overlays.is_empty());
146
1
    assert!(matches!(app.reports().state, Fetch::Loading { .. }));
147
1
}
148

            
149
#[tokio::test]
150
1
async fn a_duplicate_key_errors_and_opens_nothing() {
151
1
    let (mut app, _) = connected();
152
1
    run(&mut app, "reports balance from=2026-01-01 from=2026-02-01");
153
1
    assert!(
154
1
        app.status.ends_with("duplicate arg: from"),
155
        "{}",
156
        app.status
157
    );
158
1
    assert!(app.overlays.is_empty());
159
1
}
160

            
161
#[tokio::test]
162
1
async fn a_missing_required_field_opens_the_form_prefilled() {
163
1
    let (mut app, _) = connected();
164
1
    run(&mut app, "reports activity from=2026-01-01 grouping=year");
165
1
    let values = open_form(&app).values();
166
1
    assert_eq!(values.text("grouping"), Some("year"));
167
1
    assert_eq!(values.text("from"), Some("2026-01-01"));
168
1
    assert!(matches!(app.reports().state, Fetch::Idle));
169
1
}
170

            
171
#[tokio::test]
172
1
async fn a_bad_choice_errors_and_opens_nothing() {
173
1
    let (mut app, _) = connected();
174
1
    run(&mut app, "reports activity grouping=decade");
175
1
    assert!(app.status.contains("grouping"), "{}", app.status);
176
1
    assert!(app.overlays.is_empty());
177
1
}
178

            
179
#[tokio::test]
180
1
async fn a_target_label_is_looked_up_before_the_report_runs() {
181
1
    let (mut app, sent) = connected();
182
1
    run(&mut app, "reports balance target=usd");
183
1
    assert!(lookup_pending(&app));
184
1
    assert!(matches!(app.reports().state, Fetch::Idle));
185
1
    let id = *app.pending_routes.keys().next().expect("lookup request");
186
1
    app.route_reply(id, &options(&["USD"]));
187
1
    assert!(matches!(app.reports().state, Fetch::Loading { .. }));
188
1
    let call = expected_call(ReportKind::Balance, &[("target", USD)]);
189
1
    assert!(echoed(&mut app, &sent).await.contains(&call));
190
1
}
191

            
192
#[tokio::test]
193
1
async fn another_options_fetch_does_not_drop_the_report_lookup() {
194
1
    let (mut app, _) = connected();
195
1
    run(&mut app, "reports balance target=usd");
196
1
    let id = *app.pending_routes.keys().next().expect("lookup request");
197
1
    app.fetch_commodity_form_options();
198
1
    app.route_reply(id, &options(&["USD"]));
199
1
    assert!(matches!(app.reports().state, Fetch::Loading { .. }));
200
1
}
201

            
202
#[tokio::test]
203
1
async fn a_target_label_prefills_the_form_by_id() {
204
1
    let (mut app, _) = connected();
205
1
    run(&mut app, "reports activity target=USD from=2026-01-01");
206
1
    let id = *app.pending_routes.keys().next().expect("lookup request");
207
1
    app.route_reply(id, &options(&["USD"]));
208
1
    assert_eq!(open_form(&app).values().text("target"), Some(USD));
209
1
}
210

            
211
#[tokio::test]
212
1
async fn an_ambiguous_target_is_a_command_error() {
213
1
    let (mut app, _) = connected();
214
1
    run(&mut app, "reports balance target=USD");
215
1
    let id = *app.pending_routes.keys().next().expect("lookup request");
216
1
    app.route_reply(id, &options(&["USD", "USD"]));
217
1
    assert!(app.status.contains("ambiguous"), "{}", app.status);
218
1
    assert!(app.overlays.is_empty());
219
1
    assert!(matches!(app.reports().state, Fetch::Idle));
220
1
}
221

            
222
#[tokio::test]
223
1
async fn an_unknown_target_is_a_command_error() {
224
1
    let (mut app, _) = connected();
225
1
    run(&mut app, "reports balance target=XYZ");
226
1
    let id = *app.pending_routes.keys().next().expect("lookup request");
227
1
    app.route_reply(id, &options(&["USD"]));
228
1
    assert!(app.status.contains("matches no entry"), "{}", app.status);
229
1
    assert!(matches!(app.reports().state, Fetch::Idle));
230
1
}
231

            
232
#[tokio::test]
233
1
async fn a_newer_direct_run_supersedes_a_pending_lookup() {
234
1
    let (mut app, _) = connected();
235
1
    run(&mut app, "reports balance target=usd");
236
1
    let id = *app.pending_routes.keys().next().expect("lookup request");
237
1
    run(&mut app, "reports breakdown from=2026-01-01 to=2026-02-01");
238
1
    app.route_reply(id, &options(&["USD"]));
239
1
    let expected = FormKind::Report(ReportKind::Breakdown);
240
1
    assert!(matches!(app.reports().state, Fetch::Loading { .. }));
241
1
    assert_eq!(app.reports().kind, ReportKind::Breakdown, "{expected:?}");
242
1
}
243

            
244
#[tokio::test]
245
1
async fn a_newer_bare_form_supersedes_a_pending_lookup() {
246
1
    let (mut app, _) = connected();
247
1
    run(&mut app, "reports balance target=usd");
248
1
    let id = *app.pending_routes.keys().next().expect("lookup request");
249
1
    run(&mut app, "reports activity");
250
1
    app.route_reply(id, &options(&["USD"]));
251
1
    assert!(matches!(app.reports().state, Fetch::Idle));
252
1
    assert_eq!(open_form(&app).kind, FormKind::Report(ReportKind::Activity));
253
1
}
254

            
255
#[tokio::test]
256
1
async fn the_tui_error_names_the_key_without_dashes() {
257
1
    let (mut app, _) = connected();
258
1
    run(&mut app, "reports balance target=XYZ");
259
1
    let id = *app.pending_routes.keys().next().expect("lookup request");
260
1
    app.route_reply(id, &options(&["USD"]));
261
1
    assert!(app.status.contains("target: 'XYZ'"), "{}", app.status);
262
1
    assert!(!app.status.contains("--target"), "{}", app.status);
263
1
}