1
//! Report setup forms submit through `submit-form`; their replies render as the native replies did.
2

            
3
use crate::tabs::nms_eval::double::Sent;
4
use forms::{FormValues, Row, write_payload};
5
use ratatui::Terminal;
6
use ratatui::backend::TestBackend;
7

            
8
use crate::app::App;
9
use crate::event::{Intent, apply};
10
use crate::form::Form;
11
use crate::modal::Modal;
12
use crate::route::RouteCtx;
13
use crate::tabs::fetch::Fetch;
14
use crate::tabs::reports::{ReportKind, ReportsTab};
15
use crate::widgets::Widget;
16

            
17
type Fill = fn(&mut Form);
18

            
19
const ID: &str = "00000000-0000-0000-0000-000000000000";
20
const FORM_INVALID: &str = r#"(:id 1 :error (:code form-invalid :message "2 fields invalid" :detail ((:FIELD "groups.0.name" :MESSAGE "is required") (:FIELD "filter" :MESSAGE "unbalanced"))))"#;
21

            
22
5
fn envelope(body: &str) -> String {
23
5
    let escaped = body.replace('\\', "\\\\").replace('"', "\\\"");
24
5
    format!("(:id 1 :value \"{escaped}\")")
25
5
}
26

            
27
5
fn node() -> String {
28
5
    format!(
29
5
        "(:account-id \"{ID}\" :account-name \"Assets\" :account-path \"Assets\" :depth 0 \
30
         :account-type \"asset\" :amounts ((:commodity-id \"{ID}\" :symbol \"USD\" :amount 1000)) \
31
         :own-amounts ((:commodity-id \"{ID}\" :symbol \"USD\" :amount 1000)) :children ())"
32
    )
33
5
}
34

            
35
/// The natives' wire for a report, which `submit-form` returns unchanged.
36
5
fn reply(kind: ReportKind) -> String {
37
5
    let node = node();
38
5
    envelope(&match kind {
39
        ReportKind::Balance => {
40
2
            format!("(:balance-report :periods ((:label nil :roots ({node}))))")
41
        }
42
2
        ReportKind::Activity => format!(
43
2
            "(:activity-report :meta nil :periods ((:label \"Q1\" :groups ((:label \"Income\" :flip-sign t :roots ({node}) :total ())) :net ())))"
44
        ),
45
1
        ReportKind::Breakdown => format!(
46
1
            "(:category-breakdown :meta nil :tag-name \"category\" :periods ((:label nil :rows ((:tag-value \"Food\" :uncategorized nil :amounts ((:commodity-id \"{ID}\" :symbol \"USD\" :amount 200)))))))"
47
        ),
48
    })
49
5
}
50

            
51
6
fn render(tab: &ReportsTab) -> String {
52
6
    let mut terminal = Terminal::new(TestBackend::new(100, 30)).expect("test terminal");
53
6
    terminal
54
6
        .draw(|frame| {
55
6
            let area = frame.area();
56
6
            tab.draw(
57
6
                frame.buffer_mut(),
58
6
                area,
59
6
                &mut crate::test_support::draw_ctx(
60
6
                    &crate::test_support::dn_theme(),
61
6
                    &mut crate::hits::Hits::default(),
62
6
                ),
63
6
            )
64
6
        })
65
6
        .expect("draw");
66
6
    terminal
67
6
        .backend()
68
6
        .buffer()
69
6
        .content()
70
6
        .iter()
71
18000
        .map(|cell| cell.symbol())
72
        .collect()
73
6
}
74

            
75
19
fn set(form: &mut Form, key: &str, text: &str) {
76
19
    let field = form
77
19
        .fields
78
19
        .iter_mut()
79
65
        .find(|f| f.key == Some(key))
80
19
        .expect("descriptor field");
81
19
    field.widget.set_text(text);
82
19
}
83

            
84
1
fn group(name: &str, filter: &str, flip: &str) -> Row {
85
1
    [("name", name), ("filter", filter), ("flip", flip)]
86
1
        .into_iter()
87
3
        .map(|(k, v)| (k.to_string(), v.to_string()))
88
        .collect()
89
1
}
90

            
91
8
async fn submitted(kind: ReportKind, fill: impl FnOnce(&mut Form)) -> (App, Sent) {
92
8
    let mut app = crate::test_support::app();
93
8
    let sent = app.attach_echo();
94
8
    let mut form = Form::report(kind, &FormValues::default());
95
8
    fill(&mut form);
96
8
    app.open_dialog_for(crate::view::ViewId::Reports, Modal::Form(form));
97
8
    apply(&mut app, Intent::Submit);
98
8
    (app, sent)
99
8
}
100

            
101
4
fn payload(app: &App, kind: ReportKind) -> String {
102
4
    let pending = app.pending_form.as_ref().expect("form is pending");
103
4
    write_payload(kind.descriptor(), &pending.form.values())
104
4
}
105

            
106
6
fn fill_dates(form: &mut Form) {
107
6
    set(form, "from", "2024-01-01");
108
6
    set(form, "to", "2024-03-31");
109
6
}
110

            
111
#[tokio::test]
112
1
async fn each_report_defaults_render_as_the_native_reply_does() {
113
    let fills: [(ReportKind, Fill); 3] = [
114
1
        (ReportKind::Balance, |_| {}),
115
1
        (ReportKind::Activity, fill_dates),
116
1
        (ReportKind::Breakdown, fill_dates),
117
    ];
118
1
    for (kind, fill) in fills {
119
3
        let (mut app, _) = submitted(kind, fill).await;
120
3
        assert_eq!(app.pending_routes.len(), 1, "{kind:?} dispatched");
121
3
        let wire = reply(kind);
122
3
        app.route_reply(1, &wire);
123
3
        assert!(matches!(app.reports().state, Fetch::Loaded(_)), "{kind:?}");
124
3
        let mut expected = ReportsTab::new();
125
3
        let (_, values) = app.reports().last().cloned().expect("last report");
126
3
        expected.on_reply(&wire, kind, values);
127
3
        assert!(app.pending_form.is_none());
128
3
        assert_eq!(app.reports().state, expected.state, "{kind:?}");
129
3
        assert_eq!(render(app.reports()), render(&expected), "{kind:?}");
130
1
    }
131
1
}
132

            
133
#[tokio::test]
134
1
async fn the_balance_form_sends_target_dates_and_filter() {
135
1
    let (app, _) = submitted(ReportKind::Balance, |form| {
136
1
        set(form, "as-of", "2024-06-30");
137
1
        set(form, "filter", "(account \"Assets\")");
138
1
    })
139
1
    .await;
140
1
    assert_eq!(
141
1
        payload(&app, ReportKind::Balance),
142
1
        r#"(:target "" :from "" :as-of "2024-06-30" :filter "(account \"Assets\")")"#
143
1
    );
144
1
}
145

            
146
#[tokio::test]
147
1
async fn the_activity_form_sends_grouping_and_group_rows() {
148
1
    let (app, _) = submitted(ReportKind::Activity, |form| {
149
1
        fill_dates(form);
150
1
        set(form, "grouping", "month");
151
1
        set(form, "filter", "(tag \"x\")");
152
1
        for field in &mut form.fields {
153
6
            if let Widget::Rows(rows) = &mut field.widget {
154
1
                rows.load_rows(Some(&[group("Income", "(tag \"i\")", "yes")]));
155
5
            }
156
        }
157
1
    })
158
1
    .await;
159
1
    assert_eq!(
160
1
        payload(&app, ReportKind::Activity),
161
1
        r#"(:target "" :from "2024-01-01" :to "2024-03-31" :grouping "month" :groups ((:name "Income" :filter "(tag \"i\")" :flip "yes")) :filter "(tag \"x\")")"#
162
1
    );
163
1
}
164

            
165
#[tokio::test]
166
1
async fn the_category_form_sends_tag_sort_and_uncategorized() {
167
1
    let (app, _) = submitted(ReportKind::Breakdown, |form| {
168
1
        fill_dates(form);
169
1
        set(form, "tag", "category");
170
1
        set(form, "sort", "name_asc");
171
1
        set(form, "include-uncategorized", "no");
172
1
    })
173
1
    .await;
174
1
    assert_eq!(
175
1
        payload(&app, ReportKind::Breakdown),
176
1
        r#"(:target "" :from "2024-01-01" :to "2024-03-31" :grouping "none" :tag "category" :sort "name_asc" :include-uncategorized "no" :filter "")"#
177
1
    );
178
1
}
179

            
180
#[tokio::test]
181
1
async fn a_rejected_report_marks_the_group_cell_and_the_filter() {
182
1
    let (mut app, _) = submitted(ReportKind::Activity, fill_dates).await;
183
1
    app.route_reply(1, FORM_INVALID);
184
1
    let Some(Modal::Form(form)) = app.overlays.top() else {
185
        panic!("form must be restored");
186
    };
187
1
    assert_eq!(
188
1
        form.errors,
189
1
        ["Row 1 \u{b7} Name: is required", "Filter: unbalanced"]
190
    );
191
1
    assert!(matches!(app.reports().state, Fetch::Idle));
192
1
}
193

            
194
#[tokio::test]
195
1
async fn the_palette_balance_command_runs_the_same_form_and_shows_loading() {
196
1
    let mut app = crate::test_support::app();
197
1
    app.attach_echo();
198
1
    apply(&mut app, Intent::OpenCommandLine);
199
1
    "reports balance from=2025-01-01"
200
1
        .chars()
201
31
        .for_each(|c| apply(&mut app, Intent::InsertChar(c)));
202
1
    apply(&mut app, Intent::Submit);
203
1
    assert!(matches!(app.reports().state, Fetch::Loading { id: 1 }));
204
1
    app.route_reply(1, &reply(ReportKind::Balance));
205
1
    assert!(matches!(app.reports().state, Fetch::Loaded(_)));
206
1
}
207

            
208
#[tokio::test]
209
1
async fn the_palette_activity_command_with_only_from_prefills_the_form_and_submits_it() {
210
1
    let mut app = crate::test_support::app();
211
1
    app.attach_echo();
212
1
    apply(&mut app, Intent::OpenCommandLine);
213
1
    "reports activity from=2025-01-01"
214
1
        .chars()
215
32
        .for_each(|c| apply(&mut app, Intent::InsertChar(c)));
216
1
    apply(&mut app, Intent::Submit);
217
1
    let Some(Modal::Form(form)) = app.overlays.top() else {
218
        panic!("the activity form must open");
219
    };
220
1
    assert_eq!(form.values().text("from"), Some("2025-01-01"));
221
1
    assert_eq!(form.values().text("to"), Some(""));
222
1
    apply(&mut app, Intent::Submit);
223
1
    assert!(payload(&app, ReportKind::Activity).contains("2025-01-01"));
224
1
}
225

            
226
#[test]
227
1
fn commodity_options_reach_only_the_target_select() {
228
1
    let mut app = crate::test_support::app();
229
1
    app.overlays.push(Modal::Form(Form::report(
230
1
        ReportKind::Activity,
231
1
        &FormValues::default(),
232
1
    )));
233
1
    app.form_options_seq.advance();
234
1
    let wire = format!(r#"(:id 9 :value "((:id \"{ID}\" :label \"USD\"))")"#);
235
1
    app.deliver_reply(
236
1
        crate::route::Route {
237
1
            target: Some(app.window_of(crate::view::ViewId::Commodities)),
238
1
            ctx: RouteCtx::FormOptions {
239
1
                seq: 1,
240
1
                source: crate::route::FormOptionsSource::FormCommodities,
241
1
            },
242
1
        },
243
1
        &wire,
244
1
    );
245
1
    let Some(Modal::Form(form)) = app.overlays.top() else {
246
        panic!("form must stay open");
247
    };
248
5
    let count = |key: &str| match &form.fields.iter().find(|f| f.key == Some(key)) {
249
        Some(crate::form::Field {
250
            widget: Widget::Select(select),
251
            ..
252
2
        }) => select.options().len(),
253
        _ => 0,
254
2
    };
255
1
    assert_eq!(count("target"), 2);
256
1
    assert_eq!(count("grouping"), 4);
257
1
}
258

            
259
#[tokio::test]
260
1
async fn scroll_intents_scroll_the_reports_tab() {
261
1
    let (mut app, _) = submitted(ReportKind::Activity, fill_dates).await;
262
1
    app.route_reply(1, &reply(ReportKind::Activity));
263
1
    app.switch_tab(crate::view::Tab::Reports);
264
1
    crate::test_support::draw_once(&app, 80, 5);
265
1
    apply(&mut app, Intent::ScrollLineDown);
266
1
    assert_eq!(app.reports().scroll.top(), 1);
267
1
    apply(&mut app, Intent::ScrollLineUp);
268
1
    assert_eq!(app.reports().scroll.top(), 0);
269
1
}