1
//! `Enter` on the Transactions tab opens a read-only detail window.
2

            
3
use super::edit::options_wire;
4
use crate::app::App;
5
use crate::route::RouteCtx;
6
use crate::tabs::fetch::Fetch;
7
use crate::tabs::list::ListTab;
8
use crate::tabs::nms_eval::double::Sent;
9
use crate::test_support::{key, press};
10
use crate::view::{Tab, ViewId};
11
use crate::viewer::{Source, Viewer};
12
use cli_core::render::ListRow;
13
use ratatui::crossterm::event::KeyCode;
14

            
15
pub(super) const TX: &str = "550e8400-e29b-41d4-a716-446655440071";
16
const CASH: &str = "550e8400-e29b-41d4-a716-446655440072";
17
const USD: &str = "550e8400-e29b-41d4-a716-446655440073";
18

            
19
36
pub(super) fn started() -> (App, Sent) {
20
36
    let mut app = crate::test_support::app();
21
36
    let sent = app.attach_echo();
22
36
    app.transactions_mut().state = Fetch::Loaded(vec![ListRow {
23
36
        id: Some(TX.to_string()),
24
36
        cells: vec!["2024-06-01".to_string()],
25
36
    }]);
26
36
    app.switch_tab(Tab::Transactions);
27
36
    (app, sent)
28
36
}
29

            
30
19
fn detail_request(app: &App) -> Option<(i64, u64)> {
31
19
    app.pending_routes
32
19
        .iter()
33
18
        .find_map(|(id, route)| match route.ctx {
34
18
            RouteCtx::TransactionDetail { seq, .. } => Some((*id, seq)),
35
            _ => None,
36
18
        })
37
19
}
38

            
39
28
pub(super) fn detail_text(tags: &str, splits: usize) -> String {
40
    let split =
41
28
        format!(r#"(:id "s" :account-id "{CASH}" :commodity-id "{USD}" :value 5 :tags ())"#);
42
28
    let splits = vec![split; splits].join(" ");
43
28
    format!(
44
28
        r#"(:id "{TX}" :post-date "2024-06-01" :post-date-text "2024-06-01 00:00" :enter-date "x" :note "lunch" :splits ({splits}) :prices () :tags ({tags}))"#
45
    )
46
28
}
47

            
48
28
fn quoted(text: &str) -> String {
49
28
    format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
50
28
}
51

            
52
/// The combined reply: the options wires carry their list as a quoted string.
53
28
pub(super) fn reply_of(id: i64, detail: &str) -> String {
54
56
    let value_of = |wire: String| {
55
56
        wire.split_once(":value ")
56
56
            .map(|(_, value)| value.trim_end_matches(')').to_string())
57
            .unwrap_or_default()
58
56
    };
59
28
    let accounts = value_of(options_wire(&[(CASH, "Assets:Cash")]));
60
28
    let commodities = value_of(options_wire(&[(USD, "USD")]));
61
28
    format!(
62
28
        "(:id {id} :value ({} {accounts} {commodities}))",
63
28
        quoted(detail)
64
    )
65
28
}
66

            
67
16
pub(super) fn open_detail(app: &mut App, detail: &str) {
68
16
    press(app, key(KeyCode::Enter));
69
16
    let (id, _) = detail_request(app).expect("a detail request");
70
16
    app.route_reply(id, &reply_of(id, detail));
71
16
}
72

            
73
5
pub(super) fn front_viewer(app: &App) -> &Viewer {
74
5
    match app.front::<Viewer>() {
75
5
        Some(viewer) => viewer,
76
        None => panic!("the front window is not a viewer"),
77
    }
78
5
}
79

            
80
14
pub(super) fn detail_lines(app: &App, id: &str) -> Vec<String> {
81
14
    let source = Source::Detail { id: id.to_string() };
82
14
    let viewer = app
83
14
        .viewer_of(&source)
84
14
        .and_then(|window| app.win::<Viewer>(window));
85
14
    viewer
86
14
        .map(|viewer| viewer.lines.clone())
87
        .unwrap_or_default()
88
14
}
89

            
90
/// The request id of the detail request that carried `seq`; the test fails when there is none.
91
10
pub(super) fn request_of(app: &App, seq: u64) -> i64 {
92
14
    let found = app.pending_routes.iter().find_map(|(id, route)| {
93
14
        matches!(route.ctx, RouteCtx::TransactionDetail { seq: s, .. } if s == seq).then_some(*id)
94
14
    });
95
10
    match found {
96
10
        Some(id) => id,
97
        None => panic!("no detail request with seq {seq}"),
98
    }
99
10
}
100

            
101
1
fn view_of(app: &App) -> usize {
102
1
    front_viewer(app).scroll.rows()
103
1
}
104

            
105
3
fn scroll_of(app: &App) -> usize {
106
3
    front_viewer(app).scroll.top()
107
3
}
108

            
109
#[tokio::test]
110
1
async fn enter_dispatches_the_detail_request_for_the_selected_id() {
111
1
    let (mut app, sent) = started();
112
1
    press(&mut app, key(KeyCode::Enter));
113
1
    let (_, seq) = detail_request(&app).expect("a detail request");
114
1
    assert_eq!(seq, 0, "a first open has no viewer to count it");
115
1
    tokio::task::yield_now().await;
116
1
    app.drain_eval();
117
1
    let echoed = sent.frames().join("\n");
118
1
    assert!(
119
1
        echoed.contains(&format!(r#"(get-transaction-detail "{TX}")"#)),
120
1
        "frame: {echoed}"
121
1
    );
122
1
}
123

            
124
#[tokio::test]
125
1
async fn the_reply_opens_the_window_with_labelled_splits_and_tags() {
126
1
    let (mut app, _) = started();
127
1
    open_detail(&mut app, &detail_text(r#"(:name "trip" :value "rome")"#, 1));
128
1
    let text = detail_lines(&app, TX).join("\n");
129
1
    for needle in [
130
1
        "Date: 2024-06-01 00:00",
131
1
        "Note: lunch",
132
1
        "trip=rome",
133
1
        "Assets:Cash  5.00 USD",
134
1
    ] {
135
4
        assert!(text.contains(needle), "{needle} missing in\n{text}");
136
1
    }
137
1
    assert!(app.pending_routes.is_empty());
138
1
}
139

            
140
#[test]
141
1
fn enter_without_a_selection_reports_it() {
142
1
    let mut app = crate::test_support::app();
143
1
    app.switch_tab(Tab::Transactions);
144
1
    press(&mut app, key(KeyCode::Enter));
145
1
    assert_eq!(app.status, "no transaction selected");
146
1
    assert!(detail_request(&app).is_none());
147
1
}
148

            
149
#[tokio::test]
150
1
async fn an_error_reply_shows_in_the_status_line() {
151
1
    let (mut app, _) = started();
152
1
    press(&mut app, key(KeyCode::Enter));
153
1
    let (id, _) = detail_request(&app).expect("a detail request");
154
1
    app.route_reply(
155
1
        id,
156
1
        &format!(r#"(:id {id} :error (:code command-failed :message "no such transaction"))"#),
157
1
    );
158
1
    assert!(app.status.starts_with("command error:"), "{}", app.status);
159
1
    assert!(app.front::<Viewer>().is_none());
160
1
}
161

            
162
#[tokio::test]
163
1
async fn a_stale_reply_is_dropped() {
164
1
    let (mut app, _) = started();
165
1
    open_detail(&mut app, &detail_text("", 1));
166
1
    app.activate_window(app.window_of(ViewId::Transactions));
167
1
    press(&mut app, key(KeyCode::Enter));
168
1
    let first = request_of(&app, 1);
169
1
    app.activate_window(app.window_of(ViewId::Transactions));
170
1
    press(&mut app, key(KeyCode::Enter));
171
1
    let second = request_of(&app, 2);
172
1
    let before = detail_lines(&app, TX);
173
1
    app.route_reply(first, &reply_of(first, &detail_text("", 3)));
174
1
    assert_eq!(
175
1
        detail_lines(&app, TX),
176
1
        before,
177
        "the superseded reply is dropped"
178
    );
179
1
    app.route_reply(second, &reply_of(second, &detail_text("", 3)));
180
1
    assert_ne!(detail_lines(&app, TX), before);
181
1
}
182

            
183
#[test]
184
1
fn enter_without_a_console_reports_it() {
185
1
    let mut app = crate::test_support::app();
186
1
    app.switch_tab(Tab::Transactions);
187
1
    app.transactions_mut().state = Fetch::Loaded(vec![ListRow {
188
1
        id: Some(TX.to_string()),
189
1
        cells: vec!["2024-06-01".to_string()],
190
1
    }]);
191
1
    press(&mut app, key(KeyCode::Enter));
192
1
    assert_eq!(app.status, "console not connected");
193
1
    assert!(app.pending_routes.is_empty());
194
1
}
195

            
196
#[tokio::test]
197
1
async fn escape_and_q_close_the_window_and_enter_does_not() {
198
1
    for (code, closes) in [
199
1
        (KeyCode::Esc, true),
200
1
        (KeyCode::Char('q'), true),
201
1
        (KeyCode::Enter, false),
202
1
    ] {
203
3
        let (mut app, _) = started();
204
3
        open_detail(&mut app, &detail_text("", 1));
205
3
        press(&mut app, key(code));
206
3
        assert_eq!(app.front::<Viewer>().is_none(), closes, "{code:?}");
207
1
    }
208
1
}
209

            
210
#[tokio::test]
211
1
async fn the_window_scrolls_within_its_lines() {
212
1
    let (mut app, _) = started();
213
1
    open_detail(&mut app, &detail_text("", 70));
214
1
    crate::test_support::draw_once(&app, 80, 24);
215
1
    let view = view_of(&app);
216
1
    assert!(view > 0);
217
1
    press(&mut app, key(KeyCode::Down));
218
1
    press(&mut app, key(KeyCode::PageDown));
219
1
    assert_eq!(scroll_of(&app), 1 + view);
220
4
    (0..4).for_each(|_| press(&mut app, key(KeyCode::PageDown)));
221
1
    let last = scroll_of(&app);
222
1
    let rows = detail_lines(&app, TX).len();
223
1
    assert!(
224
1
        (rows - 1..=rows).contains(&(last + view)),
225
        "{last} {view} {rows}"
226
    );
227
1
    press(&mut app, key(KeyCode::PageUp));
228
1
    press(&mut app, key(KeyCode::Up));
229
1
    assert_eq!(scroll_of(&app), last - view - 1);
230
1
}
231

            
232
#[tokio::test]
233
1
async fn edit_inside_the_window_opens_the_edit_form_request_and_keeps_it() {
234
1
    let (mut app, sent) = started();
235
1
    open_detail(&mut app, &detail_text("", 1));
236
1
    let detail = app.front_window();
237
1
    press(&mut app, key(KeyCode::Char('e')));
238
1
    assert_eq!(app.front_window(), detail, "the detail stays");
239
1
    assert!(
240
1
        app.pending_routes
241
1
            .values()
242
1
            .any(|route| matches!(route.ctx, RouteCtx::TransactionEdit))
243
    );
244
1
    tokio::task::yield_now().await;
245
1
    app.drain_eval();
246
1
    let echoed = sent.frames().join("\n");
247
1
    assert!(
248
1
        echoed.contains(&format!(r#"(load-form "transaction-edit" "{TX}")"#)),
249
1
        "frame: {echoed}"
250
1
    );
251
1
}
252

            
253
#[tokio::test]
254
1
async fn the_latest_detail_request_wins_across_windows() {
255
1
    let (mut app, _) = started();
256
1
    open_detail(&mut app, &detail_text("", 1));
257
1
    let first = app.window_of(ViewId::Transactions);
258
1
    let second = app.open_extra(ViewId::Transactions);
259
1
    if let Some(list) = app.win_mut::<ListTab>(second) {
260
1
        list.state = Fetch::Loaded(vec![ListRow {
261
1
            id: Some(TX.to_string()),
262
1
            cells: vec!["2024-06-01".to_string()],
263
1
        }]);
264
    }
265
1
    app.activate_window(first);
266
1
    press(&mut app, key(KeyCode::Enter));
267
1
    let older = request_of(&app, 1);
268
1
    app.activate_window(second);
269
1
    press(&mut app, key(KeyCode::Enter));
270
1
    let newer = request_of(&app, 2);
271
1
    let before = detail_lines(&app, TX);
272
1
    app.route_reply(older, &reply_of(older, &detail_text("", 3)));
273
1
    assert_eq!(
274
1
        detail_lines(&app, TX),
275
1
        before,
276
        "the superseded detail applied"
277
    );
278
1
    app.route_reply(newer, &reply_of(newer, &detail_text("", 3)));
279
1
    assert_ne!(detail_lines(&app, TX), before);
280
1
}