1
//! Marking transactions and deleting the marked ones together.
2

            
3
use crate::app::App;
4
use crate::event::{Intent, apply};
5
use crate::modal::Modal;
6
use crate::route::{Route, RouteCtx};
7
use crate::tabs::fetch::Fetch;
8
use crate::tabs::nms_eval::double::Sent;
9
use crate::test_support::{key, press};
10
use crate::view::{Tab, ViewId};
11
use forms::FormValues;
12
use ratatui::crossterm::event::KeyCode;
13

            
14
19
fn page_wire(ids: &[&str], has_more: bool) -> String {
15
19
    let rows: String = ids
16
19
        .iter()
17
37
        .map(|i| format!(r#"(:ID "{i}" :DATE "2026-10-01T00:00:00Z" :DATE-TEXT "2026-10-01 00:00" :NOTE "n" :AMOUNT "5")"#))
18
        .collect::<Vec<_>>()
19
19
        .join(" ");
20
19
    let more = if has_more { "t" } else { "nil" };
21
19
    format!(r#"(:id 1 :value (:ROWS ({rows}) :HAS-MORE {more} :TOTAL 9))"#)
22
19
}
23

            
24
17
fn deliver(app: &mut App, ids: &[&str], has_more: bool) {
25
17
    app.deliver_reply(
26
17
        Route {
27
17
            target: Some(app.window_of(ViewId::Transactions)),
28
17
            ctx: RouteCtx::None,
29
17
        },
30
17
        &page_wire(ids, has_more),
31
17
    );
32
17
}
33

            
34
15
fn loaded_app(ids: &[&str]) -> (App, Sent) {
35
15
    let mut app = crate::test_support::app();
36
15
    let sent = app.attach_echo();
37
15
    app.switch_tab(Tab::Transactions);
38
15
    deliver(&mut app, ids, true);
39
15
    (app, sent)
40
15
}
41

            
42
7
fn mark_all(app: &mut App, count: usize) {
43
14
    (0..count).for_each(|_| press(app, key(KeyCode::Char('m'))));
44
7
}
45

            
46
9
fn bulk_routes(app: &App) -> Vec<(i64, String)> {
47
9
    let mut routes: Vec<_> = app
48
9
        .pending_routes
49
9
        .iter()
50
25
        .filter_map(|(request, route)| match &route.ctx {
51
12
            RouteCtx::BulkDelete { id, .. } => Some((*request, id.clone())),
52
13
            _ => None,
53
25
        })
54
        .collect();
55
9
    routes.sort();
56
9
    routes
57
9
}
58

            
59
8
fn confirm_bulk(app: &mut App) {
60
8
    press(app, key(KeyCode::Char('x')));
61
8
    apply(app, Intent::ConfirmYes);
62
8
}
63

            
64
5
fn ok_reply(app: &mut App, request: i64) {
65
5
    app.route_reply(request, &format!("(:id {request} :value t)"));
66
5
}
67

            
68
#[tokio::test]
69
1
async fn m_marks_the_row_and_moves_down_and_unmark_all_clears() {
70
1
    let (mut app, _) = loaded_app(&["a", "b", "c"]);
71
1
    press(&mut app, key(KeyCode::Char('m')));
72
1
    assert_eq!(app.transactions().marked_ids(), ["a"]);
73
1
    assert_eq!(app.transactions().selected_id(), Some("b"));
74
1
    press(&mut app, key(KeyCode::Char('k')));
75
1
    press(&mut app, key(KeyCode::Char('m')));
76
1
    assert!(app.transactions().marked_ids().is_empty(), "m toggles");
77
1
    press(&mut app, key(KeyCode::Char('m')));
78
1
    press(&mut app, key(KeyCode::Char('m')));
79
1
    assert_eq!(app.transactions().marked_ids(), ["b", "c"]);
80
1
    press(&mut app, key(KeyCode::Char('U')));
81
1
    assert!(app.transactions().marked_ids().is_empty());
82
1
}
83

            
84
#[tokio::test]
85
1
async fn marks_survive_paging_and_refresh() {
86
1
    let (mut app, _) = loaded_app(&["a", "b"]);
87
1
    press(&mut app, key(KeyCode::Char('m')));
88
1
    apply(&mut app, Intent::ListPageNext);
89
1
    deliver(&mut app, &["c", "d"], false);
90
1
    press(&mut app, key(KeyCode::Char('m')));
91
1
    assert_eq!(app.transactions().marked_ids(), ["a", "c"]);
92
1
    apply(&mut app, Intent::RefreshTab);
93
1
    deliver(&mut app, &["c", "d"], false);
94
1
    assert_eq!(app.transactions().marked_ids(), ["a", "c"]);
95
1
}
96

            
97
#[tokio::test]
98
1
async fn a_filter_change_clears_the_marks() {
99
1
    let (mut app, _) = loaded_app(&["a", "b"]);
100
1
    mark_all(&mut app, 2);
101
1
    let mut filter = FormValues::default();
102
1
    filter.set("from", "2026-01-01");
103
1
    let window = app.window_of(crate::view::ViewId::Transactions);
104
1
    let request = app
105
1
        .submit_transaction_filter(window, &filter, "from".to_string())
106
1
        .expect("dispatched");
107
1
    assert_eq!(
108
1
        app.transactions().marked_ids().len(),
109
1
        2,
110
        "not before the reply"
111
    );
112
1
    app.route_reply(request, &page_wire(&["a"], false));
113
1
    assert!(app.transactions().marked_ids().is_empty());
114
1
}
115

            
116
#[tokio::test]
117
1
async fn clearing_the_filter_clears_the_marks() {
118
1
    let (mut app, _) = loaded_app(&["a", "b"]);
119
1
    press(&mut app, key(KeyCode::Char('m')));
120
1
    press(&mut app, key(KeyCode::Char('F')));
121
1
    assert!(app.transactions().marked_ids().is_empty());
122
1
}
123

            
124
#[tokio::test]
125
1
async fn x_asks_one_confirmation_with_the_count() {
126
1
    let (mut app, _) = loaded_app(&["a", "b", "c"]);
127
1
    mark_all(&mut app, 2);
128
1
    press(&mut app, key(KeyCode::Char('x')));
129
1
    match app.overlays.top() {
130
1
        Some(Modal::Confirm { prompt, .. }) => {
131
1
            assert!(prompt.contains("Delete 2 marked"), "{prompt}");
132
1
        }
133
1
        other => panic!("confirm expected, got {other:?}"),
134
1
    }
135
1
    assert!(
136
1
        bulk_routes(&app).is_empty(),
137
1
        "nothing sent before the answer"
138
1
    );
139
1
}
140

            
141
#[tokio::test]
142
1
async fn x_without_marks_says_so_and_opens_nothing() {
143
1
    let (mut app, _) = loaded_app(&["a"]);
144
1
    press(&mut app, key(KeyCode::Char('x')));
145
1
    assert!(app.overlays.is_empty());
146
1
    assert_eq!(app.status, "no marked transactions");
147
1
}
148

            
149
#[tokio::test]
150
1
async fn confirm_sends_one_delete_per_marked_id() {
151
1
    let (mut app, sent) = loaded_app(&["a", "b", "c"]);
152
1
    mark_all(&mut app, 2);
153
1
    confirm_bulk(&mut app);
154
1
    tokio::task::yield_now().await;
155
1
    app.drain_eval();
156
1
    let echoed = sent.frames().join("\n");
157
1
    assert!(echoed.contains(r#"(delete-transaction "a")"#), "{echoed}");
158
1
    assert!(echoed.contains(r#"(delete-transaction "b")"#), "{echoed}");
159
1
    assert!(!echoed.contains(r#"(delete-transaction "c")"#), "{echoed}");
160
1
    assert_eq!(bulk_routes(&app).len(), 2);
161
1
}
162

            
163
#[tokio::test]
164
1
async fn all_replies_in_report_the_count_and_reload_the_page() {
165
1
    let (mut app, _) = loaded_app(&["a", "b", "c"]);
166
1
    mark_all(&mut app, 2);
167
1
    confirm_bulk(&mut app);
168
1
    for (request, _) in bulk_routes(&app) {
169
2
        ok_reply(&mut app, request);
170
    }
171
1
    assert_eq!(app.status, "deleted 2 of 2 transactions");
172
1
    assert!(matches!(app.transactions().state, Fetch::Loading { .. }));
173
1
    assert!(app.transactions().marked_ids().is_empty());
174
1
    let reload = *app.pending_routes.keys().max().expect("reload route");
175
1
    app.route_reply(reload, &page_wire(&["c"], false));
176
1
    assert_eq!(
177
1
        app.status, "deleted 2 of 2 transactions",
178
1
        "the reload keeps it"
179
1
    );
180
1
}
181

            
182
#[tokio::test]
183
1
async fn a_partial_failure_names_the_id_and_reason_and_keeps_its_mark() {
184
1
    let (mut app, _) = loaded_app(&["a", "b"]);
185
1
    mark_all(&mut app, 2);
186
1
    confirm_bulk(&mut app);
187
1
    let routes = bulk_routes(&app);
188
1
    let (bad, bad_id) = routes[0].clone();
189
1
    let message = r#"(:code busy :message "Transaction busy")"#;
190
1
    app.route_reply(bad, &format!("(:id {bad} :error {message})"));
191
1
    ok_reply(&mut app, routes[1].0);
192
1
    let status = app.status.clone();
193
1
    assert!(
194
1
        status.starts_with("deleted 1 of 2 transactions; failed: "),
195
        "{status}"
196
    );
197
1
    assert!(status.contains(&bad_id), "{status}");
198
1
    assert!(status.contains("Transaction busy"), "{status}");
199
1
    assert_eq!(app.transactions().marked_ids(), [bad_id]);
200
1
}
201

            
202
#[tokio::test]
203
1
async fn a_nil_reply_counts_as_not_deleted() {
204
1
    let (mut app, _) = loaded_app(&["a"]);
205
1
    press(&mut app, key(KeyCode::Char('m')));
206
1
    confirm_bulk(&mut app);
207
1
    let (request, _) = bulk_routes(&app)[0].clone();
208
1
    app.route_reply(request, &format!("(:id {request} :value nil)"));
209
1
    assert!(app.status.contains("a: not deleted"), "{}", app.status);
210
1
}
211

            
212
#[tokio::test]
213
1
async fn a_late_reply_of_an_older_bulk_delete_is_dropped() {
214
1
    let (mut app, _) = loaded_app(&["a", "b"]);
215
1
    press(&mut app, key(KeyCode::Char('m')));
216
1
    confirm_bulk(&mut app);
217
1
    let old_seq = app
218
1
        .pending_routes
219
1
        .values()
220
2
        .find_map(|route| match route.ctx {
221
1
            RouteCtx::BulkDelete { seq, .. } => Some(seq),
222
1
            _ => None,
223
2
        })
224
1
        .expect("bulk route");
225
1
    app.bulk.abandon();
226
1
    app.pending_routes.clear();
227
1
    app.attach_echo();
228
1
    press(&mut app, key(KeyCode::Char('m')));
229
1
    confirm_bulk(&mut app);
230
1
    let ok = "(:id 9 :value t)";
231
1
    app.deliver_bulk_delete_reply(old_seq, "a", ok);
232
1
    assert!(
233
1
        !app.status.starts_with("deleted"),
234
        "the old reply settles nothing: {}",
235
        app.status
236
    );
237
1
    for (request, _) in bulk_routes(&app) {
238
2
        ok_reply(&mut app, request);
239
1
    }
240
1
    assert_eq!(app.status, "deleted 2 of 2 transactions");
241
1
}
242

            
243
#[tokio::test]
244
1
async fn x_while_a_bulk_delete_is_pending_is_refused_and_sends_nothing() {
245
1
    let (mut app, sent) = loaded_app(&["a", "b"]);
246
1
    press(&mut app, key(KeyCode::Char('m')));
247
1
    confirm_bulk(&mut app);
248
1
    tokio::task::yield_now().await;
249
1
    app.drain_eval();
250
1
    let before = sent.frames().len();
251
1
    press(&mut app, key(KeyCode::Char('x')));
252
1
    assert!(app.overlays.is_empty(), "no second confirm");
253
1
    assert_eq!(app.status, "a bulk delete is still running");
254
1
    tokio::task::yield_now().await;
255
1
    app.drain_eval();
256
1
    assert_eq!(sent.frames().len(), before, "no further evals");
257
1
    assert_eq!(bulk_routes(&app).len(), 1);
258
1
}
259

            
260
#[tokio::test]
261
1
async fn a_row_that_no_longer_exists_is_named_and_loses_its_mark() {
262
1
    let (mut app, _) = loaded_app(&["a", "b"]);
263
1
    mark_all(&mut app, 2);
264
1
    confirm_bulk(&mut app);
265
1
    let routes = bulk_routes(&app);
266
1
    let (gone, gone_id) = routes[0].clone();
267
1
    let (failing, failing_id) = routes[1].clone();
268
1
    let missing = r#"(:code not-found :message "delete-transaction: not found")"#;
269
1
    app.route_reply(gone, &format!("(:id {gone} :error {missing})"));
270
1
    let busy = r#"(:code busy :message "try later")"#;
271
1
    app.route_reply(failing, &format!("(:id {failing} :error {busy})"));
272
1
    assert!(
273
1
        app.status.contains(&format!("{gone_id}: not found")),
274
        "{}",
275
        app.status
276
    );
277
1
    assert_eq!(app.transactions().marked_ids(), [failing_id]);
278
1
}
279

            
280
#[tokio::test]
281
1
async fn cancel_deletes_nothing() {
282
1
    let (mut app, _) = loaded_app(&["a", "b"]);
283
1
    mark_all(&mut app, 2);
284
1
    press(&mut app, key(KeyCode::Char('x')));
285
1
    apply(&mut app, Intent::CloseTopmost);
286
1
    assert!(app.overlays.is_empty());
287
1
    assert!(bulk_routes(&app).is_empty());
288
1
    assert_eq!(app.transactions().marked_ids(), ["a", "b"]);
289
1
}
290

            
291
#[tokio::test]
292
1
async fn x_is_ignored_off_the_transactions_tab() {
293
1
    let (mut app, _) = loaded_app(&["a"]);
294
1
    press(&mut app, key(KeyCode::Char('m')));
295
1
    app.switch_tab(Tab::Accounts);
296
1
    press(&mut app, key(KeyCode::Char('x')));
297
1
    assert!(app.overlays.is_empty());
298
1
}