1
//! An open detail follows its transaction: it refills in place, never raises, and goes with it.
2

            
3
use super::edit::{PAYLOAD, deliver_options, options_wire, wire_of};
4
use super::report_chart::env;
5
use super::transaction_detail::{
6
    TX, detail_lines, detail_text, open_detail, reply_of, request_of, started,
7
};
8
use crate::app::App;
9
use crate::event::{Intent, apply};
10
use crate::modal::Modal;
11
use crate::route::{FormOptionsSource, RouteCtx};
12
use crate::test_support::{draw_frame, flat, key, press};
13
use crate::view::ViewId;
14
use crate::viewer::{Source, Viewer};
15
use crate::window::WindowId;
16
use ratatui::crossterm::event::KeyCode;
17
use rpc::chart::ChartBackend;
18

            
19
const OTHER: &str = "other";
20

            
21
20
fn detail_of(id: &str) -> Source {
22
20
    Source::Detail { id: id.to_string() }
23
20
}
24

            
25
8
fn detail_window(app: &App, id: &str) -> WindowId {
26
8
    match app.viewer_of(&detail_of(id)) {
27
8
        Some(window) => window,
28
        None => panic!("no detail of {id}"),
29
    }
30
8
}
31

            
32
2
fn mutation_request(app: &App) -> Option<i64> {
33
2
    app.pending_routes
34
2
        .iter()
35
4
        .find_map(|(id, route)| matches!(route.ctx, RouteCtx::Mutation { .. }).then_some(*id))
36
2
}
37

            
38
2
fn open_edit_from_detail(app: &mut App) {
39
2
    press(app, key(KeyCode::Char('e')));
40
2
    let id = app
41
2
        .pending_routes
42
2
        .iter()
43
2
        .find_map(|(id, route)| matches!(route.ctx, RouteCtx::TransactionEdit).then_some(*id))
44
2
        .expect("the edit request");
45
2
    app.route_reply(id, &wire_of(PAYLOAD));
46
2
    let accounts = options_wire(&[("a", "Assets:Cash")]);
47
2
    deliver_options(app, FormOptionsSource::FormAccounts, &accounts);
48
2
}
49

            
50
#[tokio::test]
51
1
async fn a_saved_edit_refreshes_the_detail_in_place_without_raising_it() {
52
1
    let (mut app, _) = started();
53
1
    open_detail(&mut app, &detail_text("", 1));
54
1
    let detail = detail_window(&app, TX);
55
1
    open_edit_from_detail(&mut app);
56
1
    assert_eq!(
57
1
        app.overlays.origin().map(|origin| origin.window),
58
1
        Some(detail)
59
    );
60
1
    apply(&mut app, Intent::Submit);
61
1
    let save = mutation_request(&app).expect("the save request");
62
1
    let accounts = app.open_extra(ViewId::Accounts);
63
1
    app.route_reply(save, &format!(r#"(:id {save} :value "ok")"#));
64
1
    let lists = app.window_ids(ViewId::Transactions);
65
1
    assert!(
66
1
        lists
67
1
            .iter()
68
1
            .all(|list| app.win_by(*list).is_some_and(|win| win.view.loading()))
69
    );
70
1
    let refresh = request_of(&app, 1);
71
1
    let before = detail_lines(&app, TX);
72
1
    app.route_reply(refresh, &reply_of(refresh, &detail_text("", 3)));
73
1
    assert_ne!(detail_lines(&app, TX), before);
74
1
    assert_eq!(
75
1
        app.front_window(),
76
1
        Some(accounts),
77
1
        "the refill raised the detail"
78
1
    );
79
1
}
80

            
81
#[tokio::test]
82
1
async fn a_detail_above_the_origin_of_a_form_leaves_the_dialog_working() {
83
1
    let (mut app, _) = started();
84
1
    let list = app.window_of(ViewId::Transactions);
85
1
    app.deliver_transaction_edit_reply(Some(list), &wire_of(PAYLOAD));
86
1
    let accounts = options_wire(&[("a", "Assets:Cash")]);
87
1
    deliver_options(&mut app, FormOptionsSource::FormAccounts, &accounts);
88
1
    app.show_viewer(detail_of(TX), vec!["a".into()]);
89
1
    assert_eq!(app.dialog_window(), Some(list));
90
1
    assert!(matches!(app.overlays.top(), Some(Modal::Form(_))));
91
1
    apply(&mut app, Intent::Submit);
92
1
    assert!(mutation_request(&app).is_some(), "{}", app.status);
93
1
}
94

            
95
#[tokio::test]
96
1
async fn a_form_of_a_closed_detail_names_no_viewer() {
97
1
    let (mut app, _) = started();
98
1
    open_detail(&mut app, &detail_text("", 1));
99
1
    open_edit_from_detail(&mut app);
100
1
    app.close_window(detail_window(&app, TX));
101
1
    assert_eq!(app.dialog_window(), None);
102
1
    assert_eq!(app.status, "the window was closed");
103
1
}
104

            
105
#[test]
106
1
fn a_pty_shrunk_below_a_fixed_viewer_still_draws_and_scrolls_to_the_end() {
107
1
    let (mut app, _) = started();
108
1
    app.sync_terminal(env(80, 24, ChartBackend::Halfblocks));
109
30
    let text: Vec<String> = (0..30).map(|n| format!("line{n:02}")).collect();
110
1
    app.show_viewer(detail_of(TX), text);
111
1
    app.sync_terminal(env(40, 10, ChartBackend::Halfblocks));
112
1
    let window = detail_window(&app, TX);
113
1
    let rect = flat(
114
1
        app.desktop
115
1
            .place_of(window, app.desktop_rect())
116
1
            .expect("open"),
117
1
    );
118
1
    draw_frame(&app, 40, 10);
119
1
    press(&mut app, key(KeyCode::End));
120
1
    let buffer = draw_frame(&app, 40, 10).0;
121
1
    let row: String = (rect.x..rect.right())
122
16
        .map(|x| buffer[(x, rect.bottom() - 2)].symbol())
123
        .collect();
124
1
    assert!(row.contains("line29"), "{row:?}");
125
1
}
126

            
127
#[tokio::test]
128
1
async fn each_detail_awaits_only_its_own_requests() {
129
1
    let (mut app, _) = started();
130
1
    app.show_viewer(detail_of(TX), vec!["a".into()]);
131
1
    app.show_viewer(detail_of(OTHER), vec!["a".into()]);
132
1
    app.refresh_details();
133
2
    let [tx_request, other_request] = [TX, OTHER].map(|id| {
134
2
        let found = app
135
2
            .pending_routes
136
2
            .iter()
137
3
            .find_map(|(request, route)| match &route.ctx {
138
                RouteCtx::TransactionDetail {
139
                    id: asked, seq: 1, ..
140
3
                } if asked == id => Some(*request),
141
1
                _ => None,
142
3
            });
143
2
        found.expect("a refresh of the detail")
144
2
    });
145
1
    app.route_reply(other_request, &reply_of(other_request, &detail_text("", 2)));
146
1
    app.route_reply(tx_request, &reply_of(tx_request, &detail_text("", 3)));
147
2
    let sizes = [TX, OTHER].map(|id| detail_lines(&app, id).len());
148
1
    assert!(sizes[0] > sizes[1] && sizes[1] > 1, "{sizes:?}");
149
1
}
150

            
151
#[tokio::test]
152
1
async fn a_refill_refits_the_fixed_window_to_its_lines() {
153
1
    let (mut app, _) = started();
154
1
    app.sync_terminal(env(80, 24, ChartBackend::Halfblocks));
155
1
    app.show_viewer(detail_of(TX), vec!["a".into()]);
156
1
    let window = detail_window(&app, TX);
157
12
    let lines: Vec<String> = (0..12).map(|n| format!("line {n}")).collect();
158
1
    let wanted = tvui::viewer_size(&lines);
159
1
    app.fill_viewer(window, lines);
160
1
    let place = app.desktop.window(window).map(|slot| slot.place);
161
1
    assert_eq!(place.map(|place| (place.width, place.height)), Some(wanted));
162
1
}
163

            
164
const MISSING: &str = r#"(nil "()" "()")"#;
165

            
166
#[tokio::test]
167
1
async fn a_transaction_that_is_gone_closes_its_window_and_says_so() {
168
1
    let (mut app, _) = started();
169
1
    open_detail(&mut app, &detail_text("", 1));
170
1
    app.refresh_details();
171
1
    let refresh = request_of(&app, 1);
172
1
    app.route_reply(refresh, &format!("(:id {refresh} :value {MISSING})"));
173
1
    assert_eq!(app.windows_of(ViewId::Viewer), 0);
174
1
    assert_eq!(app.status, format!("Transaction {TX} no longer exists"));
175
1
}
176

            
177
#[tokio::test]
178
1
async fn enter_on_a_row_that_is_gone_opens_nothing_and_says_so() {
179
1
    let (mut app, _) = started();
180
1
    press(&mut app, key(KeyCode::Enter));
181
1
    let request = request_of(&app, 0);
182
1
    app.route_reply(request, &format!("(:id {request} :value {MISSING})"));
183
1
    assert_eq!(app.windows_of(ViewId::Viewer), 0);
184
1
    assert_eq!(app.status, format!("Transaction {TX} no longer exists"));
185
1
}
186

            
187
#[tokio::test]
188
1
async fn enter_on_an_open_detail_raises_it_and_a_refresh_in_flight_keeps_it_there() {
189
1
    let (mut app, _) = started();
190
1
    open_detail(&mut app, &detail_text("", 1));
191
1
    let detail = detail_window(&app, TX);
192
1
    app.activate_window(app.window_of(ViewId::Transactions));
193
1
    press(&mut app, key(KeyCode::Enter));
194
1
    assert_eq!(app.front_window(), Some(detail), "raised at once");
195
1
    app.refresh_details();
196
1
    let refresh = request_of(&app, 2);
197
1
    app.route_reply(refresh, &reply_of(refresh, &detail_text("", 3)));
198
1
    assert_eq!(app.front_window(), Some(detail));
199
1
}
200

            
201
#[tokio::test]
202
1
async fn a_refresh_reply_for_a_closed_detail_opens_nothing() {
203
1
    let (mut app, _) = started();
204
1
    open_detail(&mut app, &detail_text("", 1));
205
1
    app.refresh_details();
206
1
    let refresh = request_of(&app, 1);
207
1
    app.close_window(detail_window(&app, TX));
208
1
    app.route_reply(refresh, &reply_of(refresh, &detail_text("", 1)));
209
1
    assert!(app.front::<Viewer>().is_none());
210
1
}
211

            
212
1
fn two_rows(app: &mut App) {
213
    let row = |id: &str| cli_core::render::ListRow {
214
2
        id: Some(id.to_string()),
215
2
        cells: vec!["2024-06-01".to_string()],
216
2
    };
217
1
    app.transactions_mut().state = crate::tabs::fetch::Fetch::Loaded(vec![row(TX), row(OTHER)]);
218
1
}
219

            
220
2
fn detail_requests_of(app: &App, wanted: &str) -> usize {
221
2
    let asked = app.pending_routes.values();
222
2
    asked
223
        .filter(
224
3
            |route| matches!(&route.ctx, RouteCtx::TransactionDetail { id, .. } if id == wanted),
225
        )
226
        .count()
227
2
}
228

            
229
#[tokio::test]
230
1
async fn a_bulk_delete_closes_the_deleted_details_and_keeps_its_summary() {
231
1
    let (mut app, _) = started();
232
1
    two_rows(&mut app);
233
1
    app.show_viewer(detail_of(TX), vec!["a".into()]);
234
1
    app.show_viewer(detail_of(OTHER), vec!["a".into()]);
235
1
    app.activate_window(app.window_of(ViewId::Transactions));
236
1
    press(&mut app, key(KeyCode::Char('m')));
237
1
    press(&mut app, key(KeyCode::Char('m')));
238
1
    press(&mut app, key(KeyCode::Char('x')));
239
1
    apply(&mut app, Intent::ConfirmYes);
240
1
    let mut routes: Vec<(i64, String)> = app
241
1
        .pending_routes
242
1
        .iter()
243
2
        .filter_map(|(request, route)| match &route.ctx {
244
2
            RouteCtx::BulkDelete { id, .. } => Some((*request, id.clone())),
245
            _ => None,
246
2
        })
247
        .collect();
248
1
    routes.sort_by(|a, b| a.1.cmp(&b.1));
249
1
    for (request, id) in routes {
250
2
        let reply = match id == TX {
251
1
            true => format!("(:id {request} :value t)"),
252
1
            false => format!(r#"(:id {request} :error (:code busy :message "busy"))"#),
253
        };
254
2
        app.route_reply(request, &reply);
255
    }
256
1
    assert!(
257
1
        app.viewer_of(&detail_of(TX)).is_none(),
258
        "the deleted detail stays"
259
    );
260
1
    assert!(app.viewer_of(&detail_of(OTHER)).is_some());
261
1
    assert!(
262
1
        app.status
263
1
            .starts_with("deleted 1 of 2 transactions; failed: "),
264
        "{}",
265
        app.status
266
    );
267
1
    assert_eq!(detail_requests_of(&app, TX), 0);
268
1
}
269

            
270
#[tokio::test]
271
1
async fn a_single_delete_closes_its_detail_and_keeps_the_notice() {
272
1
    let (mut app, _) = started();
273
1
    app.show_viewer(detail_of(TX), vec!["a".into()]);
274
1
    let list = app.window_of(ViewId::Transactions);
275
1
    app.pending_routes.insert(
276
1
        7,
277
1
        crate::route::Route {
278
1
            target: Some(list),
279
1
            ctx: RouteCtx::DeleteTransaction { id: TX.to_string() },
280
1
        },
281
1
    );
282
1
    app.route_reply(7, r#"(:id 7 :value t :notices ("balance moved"))"#);
283
1
    assert_eq!(app.windows_of(ViewId::Viewer), 0);
284
1
    assert_eq!(app.status, "balance moved");
285
1
    assert_eq!(detail_requests_of(&app, TX), 0);
286
1
}
287

            
288
#[tokio::test]
289
1
async fn an_error_reply_to_a_refresh_keeps_the_window_and_its_lines() {
290
1
    let (mut app, _) = started();
291
1
    open_detail(&mut app, &detail_text("", 1));
292
1
    let before = detail_lines(&app, TX);
293
1
    app.refresh_details();
294
1
    let refresh = request_of(&app, 1);
295
1
    app.route_reply(
296
1
        refresh,
297
1
        &format!(r#"(:id {refresh} :error (:code db :message "boom"))"#),
298
1
    );
299
1
    assert_eq!(detail_lines(&app, TX), before);
300
1
    assert!(app.status.starts_with("command error:"), "{}", app.status);
301
1
}
302

            
303
#[tokio::test]
304
1
async fn two_enters_before_the_first_reply_leave_one_window() {
305
1
    let (mut app, _) = started();
306
1
    press(&mut app, key(KeyCode::Enter));
307
1
    press(&mut app, key(KeyCode::Enter));
308
1
    let requests: Vec<i64> = app.pending_routes.keys().copied().collect();
309
1
    for request in requests {
310
2
        app.route_reply(request, &reply_of(request, &detail_text("", 1)));
311
1
    }
312
1
    assert_eq!(app.windows_of(ViewId::Viewer), 1);
313
1
}
314

            
315
2
fn place_detail(app: &mut App, window: WindowId, rect: ratatui::layout::Rect) {
316
2
    let slot = app.desktop.window(window).expect("it is open");
317
2
    app.desktop.restore(tvui::Window {
318
2
        place: tvui::Place::from(rect),
319
2
        ..slot
320
2
    });
321
2
}
322

            
323
2
fn drawn(app: &App, window: WindowId) -> tvui::Place {
324
2
    let place = app.desktop.window(window).map(|slot| slot.place);
325
2
    place.expect("it is open")
326
2
}
327

            
328
#[tokio::test]
329
1
async fn a_refill_of_the_same_size_keeps_the_position_the_user_gave() {
330
1
    let (mut app, _) = started();
331
1
    app.sync_terminal(env(80, 24, ChartBackend::Halfblocks));
332
1
    app.show_viewer(detail_of(TX), vec!["a".into()]);
333
1
    let window = detail_window(&app, TX);
334
1
    let area = app.desktop_rect();
335
1
    let size = tvui::viewer_size(&["a"]);
336
1
    let off = ratatui::layout::Rect::new(area.right() - 3, area.y + 1, size.0, size.1);
337
1
    place_detail(&mut app, window, off);
338
1
    app.fill_viewer(window, vec!["b".into()]);
339
1
    assert_eq!(drawn(&app, window), tvui::Place::from(off));
340
1
}
341

            
342
#[tokio::test]
343
1
async fn a_refill_that_grows_at_the_desktop_edge_stays_inside() {
344
1
    let (mut app, _) = started();
345
1
    app.sync_terminal(env(80, 24, ChartBackend::Halfblocks));
346
1
    app.show_viewer(detail_of(TX), vec!["a".into()]);
347
1
    let window = detail_window(&app, TX);
348
1
    let area = app.desktop_rect();
349
1
    let small = tvui::viewer_size(&["a"]);
350
1
    let edge = ratatui::layout::Rect::new(
351
1
        area.right() - small.0,
352
1
        area.bottom() - small.1,
353
1
        small.0,
354
1
        small.1,
355
1
    );
356
1
    place_detail(&mut app, window, edge);
357
1
    app.fill_viewer(
358
1
        window,
359
8
        (0..8).map(|n| format!("{n}{}", "x".repeat(30))).collect(),
360
    );
361
1
    let place = drawn(&app, window);
362
1
    assert!(
363
1
        place.x + i32::from(place.width) <= i32::from(area.right()),
364
        "{place:?}"
365
    );
366
1
    assert!(
367
1
        place.y + i32::from(place.height) <= i32::from(area.bottom()),
368
1
        "{place:?}"
369
1
    );
370
1
}