1
//! Testing a template from the tab and from its form: the draft shows read-only with labels.
2

            
3
use super::edit::{options_wire, top_form, wire_of};
4
use super::template_forms::{edit_payload, rejected};
5
use super::templates::{RENT, load, templates_app};
6
use crate::app::App;
7
use crate::form::FormKind;
8
use crate::modal::Modal;
9
use crate::route::{RouteCtx, TemplateRoute};
10
use crate::test_support::{ctrl, key, press};
11
use ratatui::crossterm::event::KeyCode;
12

            
13
const CASH: &str = "cccccccc-0000-0000-0000-000000000001";
14
const FOOD: &str = "cccccccc-0000-0000-0000-000000000002";
15
const USD: &str = "dddddddd-0000-0000-0000-000000000001";
16

            
17
const DRAFT: &str = concat!(
18
    r#"(:NOTE "Rent" :DATE "2026-06-15" :SPLITS "#,
19
    r#"((:ACCOUNT "cccccccc-0000-0000-0000-000000000001" :AMOUNT "-5" :COMMODITY "dddddddd-0000-0000-0000-000000000001" :TAGS nil) "#,
20
    r#"(:ACCOUNT "cccccccc-0000-0000-0000-000000000002" :AMOUNT "5" :COMMODITY "dddddddd-0000-0000-0000-000000000001" :TAGS ((:NAME "memo" :VALUE "june")))) "#,
21
    r#":TAGS ((:NAME "kind" :VALUE "rent")) :PREFILLABLE t :REASON nil)"#
22
);
23

            
24
19
fn pending_id(app: &App, want: impl Fn(&TemplateRoute) -> bool) -> anyhow::Result<i64> {
25
19
    app.pending_routes
26
19
        .iter()
27
21
        .find_map(|(id, route)| match &route.ctx {
28
21
            RouteCtx::Template(template) if want(template) => Some(*id),
29
3
            _ => None,
30
21
        })
31
1
        .ok_or_else(|| anyhow::anyhow!("no such request pending"))
32
19
}
33

            
34
5
fn answer(app: &mut App, id: i64, value: &str) {
35
5
    app.route_reply(id, &format!("(:id {id} :value {value})"));
36
5
}
37

            
38
3
fn answer_text(app: &mut App, id: i64, text: &str) {
39
3
    let wire = wire_of(text).replacen(":id 1", &format!(":id {id}"), 1);
40
3
    app.route_reply(id, &wire);
41
3
}
42

            
43
8
fn answer_options(app: &mut App, id: i64, items: &[(&str, &str)]) {
44
8
    let wire = options_wire(items).replacen(":id 2", &format!(":id {id}"), 1);
45
8
    app.route_reply(id, &wire);
46
8
}
47

            
48
4
fn answer_labels(app: &mut App, draft: &str) -> anyhow::Result<()> {
49
4
    let tested = pending_id(app, |r| matches!(r, TemplateRoute::Tested { .. }))?;
50
4
    answer(app, tested, draft);
51
4
    let accounts = pending_id(
52
4
        app,
53
4
        |r| matches!(r, TemplateRoute::Labels(l) if l.accounts.is_none()),
54
    )?;
55
4
    answer_options(app, accounts, &[(CASH, "Assets:Cash"), (FOOD, "Food")]);
56
4
    let commodities = pending_id(
57
4
        app,
58
4
        |r| matches!(r, TemplateRoute::Labels(l) if l.accounts.is_some()),
59
    )?;
60
4
    answer_options(app, commodities, &[(USD, "USD")]);
61
4
    Ok(())
62
4
}
63

            
64
3
fn draft_lines(app: &App) -> anyhow::Result<&[String]> {
65
3
    match app.overlays.top() {
66
3
        Some(Modal::Draft(draft)) => Ok(&draft.lines),
67
        other => anyhow::bail!("no draft pane: {other:?}"),
68
    }
69
3
}
70

            
71
const RENDERED: [&str; 6] = [
72
    "note: Rent",
73
    "date: 2026-06-15",
74
    "split: Assets:Cash  -5 USD",
75
    "split: Food  5 USD  [memo=june]",
76
    "tags: kind=rent",
77
    "prefillable: yes",
78
];
79

            
80
#[tokio::test]
81
1
async fn t_tests_the_stored_source_and_shows_the_draft_with_labels() -> anyhow::Result<()> {
82
1
    let (mut app, sent) = templates_app();
83
1
    load(&mut app, &[(RENT, "rent")])?;
84

            
85
1
    press(&mut app, key(KeyCode::Char('t')));
86
1
    tokio::task::yield_now().await;
87
1
    app.drain_eval();
88
1
    let echoed = sent.frames().join("\n");
89
1
    assert!(
90
1
        echoed.contains(&format!(r#"(load-form "template-edit" "{RENT}")"#)),
91
        "{echoed}"
92
    );
93

            
94
1
    let source = pending_id(&app, |r| matches!(r, TemplateRoute::Source { .. }))?;
95
1
    answer_text(&mut app, source, &edit_payload());
96
1
    tokio::task::yield_now().await;
97
1
    app.drain_eval();
98
1
    let echoed = sent.frames().join("\n");
99
1
    assert!(
100
1
        echoed.contains(r#"(submit-form "template-test""#),
101
        "{echoed}"
102
    );
103
1
    assert!(echoed.contains("set-draft-note"), "{echoed}");
104

            
105
1
    answer_labels(&mut app, DRAFT)?;
106
1
    assert_eq!(draft_lines(&app)?, RENDERED);
107
1
    press(&mut app, key(KeyCode::Esc));
108
1
    assert!(app.overlays.is_empty());
109
2
    Ok(())
110
1
}
111

            
112
#[tokio::test]
113
1
async fn a_refused_prefill_shows_its_reason_in_the_draft() -> anyhow::Result<()> {
114
1
    let (mut app, _) = templates_app();
115
1
    load(&mut app, &[(RENT, "rent")])?;
116
1
    press(&mut app, key(KeyCode::Char('t')));
117
1
    let source = pending_id(&app, |r| matches!(r, TemplateRoute::Source { .. }))?;
118
1
    answer_text(&mut app, source, &edit_payload());
119

            
120
1
    let refused = r#"(:NOTE nil :DATE nil :SPLITS nil :TAGS nil :PREFILLABLE nil :REASON "it has an odd number of splits")"#;
121
1
    answer_labels(&mut app, refused)?;
122

            
123
1
    assert_eq!(
124
1
        draft_lines(&app)?,
125
1
        ["prefillable: no: it has an odd number of splits"]
126
    );
127
2
    Ok(())
128
1
}
129

            
130
#[tokio::test]
131
1
async fn t_without_a_selection_says_so() {
132
1
    let (mut app, _) = templates_app();
133
1
    press(&mut app, key(KeyCode::Char('t')));
134
1
    assert_eq!(app.status, "no template selected");
135
1
}
136

            
137
#[tokio::test]
138
1
async fn a_failing_stored_template_shows_the_message_on_the_status_line() -> anyhow::Result<()> {
139
1
    let (mut app, _) = templates_app();
140
1
    load(&mut app, &[(RENT, "rent")])?;
141
1
    press(&mut app, key(KeyCode::Char('t')));
142
1
    let source = pending_id(&app, |r| matches!(r, TemplateRoute::Source { .. }))?;
143
1
    answer_text(&mut app, source, &edit_payload());
144
1
    let tested = pending_id(&app, |r| matches!(r, TemplateRoute::Tested { .. }))?;
145

            
146
1
    app.route_reply(tested, &rejected(tested, "source", "unclosed paren"));
147

            
148
1
    assert!(app.status.starts_with("test failed:"), "{}", app.status);
149
1
    assert!(app.status.contains("unclosed paren"), "{}", app.status);
150
1
    assert!(app.overlays.is_empty());
151
2
    Ok(())
152
1
}
153

            
154
#[tokio::test]
155
1
async fn ctrl_t_in_the_form_tests_the_source_being_edited() -> anyhow::Result<()> {
156
1
    let (mut app, sent) = templates_app();
157
1
    load(&mut app, &[(RENT, "rent")])?;
158
1
    app.deliver_template_edit_reply(
159
1
        Some(app.window_of(crate::view::ViewId::Templates)),
160
1
        &wire_of(&edit_payload()),
161
1
    );
162
1
    app.set_status("old");
163

            
164
1
    press(&mut app, ctrl(KeyCode::Char('t')));
165
1
    assert_ne!(app.status, "old", "testing starts an action");
166
1
    tokio::task::yield_now().await;
167
1
    app.drain_eval();
168
1
    let echoed = sent.frames().join("\n");
169
1
    assert!(
170
1
        echoed.contains(r#"(submit-form "template-test""#),
171
        "{echoed}"
172
    );
173
1
    assert!(echoed.contains("set-draft-note"), "{echoed}");
174

            
175
1
    answer_labels(&mut app, DRAFT)?;
176
1
    assert_eq!(draft_lines(&app)?, RENDERED);
177
1
    press(&mut app, key(KeyCode::Esc));
178
1
    assert_eq!(top_form(&app).values().text("name"), Some("rent"));
179
2
    Ok(())
180
1
}
181

            
182
#[tokio::test]
183
1
async fn a_compile_error_in_the_form_shows_at_the_source_field() -> anyhow::Result<()> {
184
1
    let (mut app, _) = templates_app();
185
1
    app.deliver_template_edit_reply(
186
1
        Some(app.window_of(crate::view::ViewId::Templates)),
187
1
        &wire_of(&edit_payload()),
188
1
    );
189
1
    press(&mut app, ctrl(KeyCode::Char('t')));
190
1
    let tested = pending_id(&app, |r| {
191
1
        matches!(r, TemplateRoute::Tested { in_form: true, .. })
192
1
    })?;
193

            
194
1
    app.route_reply(tested, &rejected(tested, "source", "unclosed paren"));
195

            
196
1
    assert_eq!(top_form(&app).errors, ["Source: unclosed paren"]);
197
1
    assert_eq!(top_form(&app).focus, 1);
198
1
    assert!(app.status.contains("unclosed paren"), "{}", app.status);
199
2
    Ok(())
200
1
}
201

            
202
#[tokio::test]
203
1
async fn a_superseded_test_reply_is_dropped() -> anyhow::Result<()> {
204
1
    let (mut app, _) = templates_app();
205
1
    app.deliver_template_edit_reply(
206
1
        Some(app.window_of(crate::view::ViewId::Templates)),
207
1
        &wire_of(&edit_payload()),
208
1
    );
209
1
    press(&mut app, ctrl(KeyCode::Char('t')));
210
2
    let first = pending_id(&app, |r| matches!(r, TemplateRoute::Tested { .. }))?;
211
1
    press(&mut app, ctrl(KeyCode::Char('t')));
212

            
213
1
    answer(&mut app, first, DRAFT);
214

            
215
1
    assert!(!matches!(app.overlays.top(), Some(Modal::Draft(_))));
216
2
    assert!(pending_id(&app, |r| matches!(r, TemplateRoute::Labels(_))).is_err());
217
2
    Ok(())
218
1
}
219

            
220
#[tokio::test]
221
1
async fn a_draft_for_a_closed_form_is_not_shown() -> anyhow::Result<()> {
222
1
    let (mut app, _) = templates_app();
223
1
    app.deliver_template_edit_reply(
224
1
        Some(app.window_of(crate::view::ViewId::Templates)),
225
1
        &wire_of(&edit_payload()),
226
1
    );
227
1
    press(&mut app, ctrl(KeyCode::Char('t')));
228
1
    app.overlays.pop();
229

            
230
1
    answer_labels(&mut app, DRAFT)?;
231

            
232
1
    assert!(app.overlays.is_empty());
233
2
    Ok(())
234
1
}
235

            
236
#[tokio::test]
237
1
async fn ctrl_t_means_nothing_outside_the_template_forms() {
238
1
    let (mut app, _) = templates_app();
239
1
    app.switch_tab(crate::view::Tab::Tags);
240
1
    press(&mut app, key(KeyCode::Char('c')));
241
1
    let routes = app.pending_routes.len();
242
1
    app.set_status("old");
243
1
    press(&mut app, ctrl(KeyCode::Char('t')));
244
1
    assert_eq!(app.pending_routes.len(), routes);
245
1
    assert_eq!(app.status, "old");
246
1
    assert!(matches!(
247
1
        app.overlays.top(),
248
1
        Some(Modal::Form(form)) if form.kind == FormKind::TagCreate
249
1
    ));
250
1
}
251

            
252
#[tokio::test]
253
1
async fn the_test_intent_does_nothing_on_a_form_that_is_not_a_template() {
254
    use crate::event::{Intent, TemplateKey, apply};
255
1
    let (mut app, _) = templates_app();
256
1
    app.switch_tab(crate::view::Tab::Tags);
257
1
    press(&mut app, key(KeyCode::Char('c')));
258
1
    let routes = app.pending_routes.len();
259
1
    app.set_status("old");
260
1
    apply(&mut app, Intent::Template(TemplateKey::Test));
261
1
    assert_eq!(app.pending_routes.len(), routes);
262
1
    assert!(app.status.is_empty(), "{}", app.status);
263
1
}