1
//! The Transactions tab pages over `transaction-query`.
2

            
3
use rpc::{ScriptCtx, Session};
4
use server::lossless::seed;
5
use sqlx::PgPool;
6

            
7
use crate::app::App;
8
use crate::event::{Intent, apply};
9
use crate::hits::{Surface, Target};
10
use crate::route::{Route, RouteCtx};
11
use crate::tabs::fetch::Fetch;
12
use crate::tabs::nms_eval::ConsoleEval;
13
use crate::view::{Tab, ViewId};
14
use ratatui::crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
15

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

            
26
13
fn deliver(app: &mut App, wire: &str) {
27
13
    app.deliver_reply(
28
13
        Route {
29
13
            target: Some(app.window_of(ViewId::Transactions)),
30
13
            ctx: RouteCtx::None,
31
13
        },
32
13
        wire,
33
13
    );
34
13
}
35

            
36
5
fn row_ids(app: &App) -> Vec<String> {
37
5
    match &app.transactions().state {
38
52
        Fetch::Loaded(rows) => rows.iter().filter_map(|r| r.id.clone()).collect(),
39
        _ => Vec::new(),
40
    }
41
5
}
42

            
43
#[test]
44
1
fn a_delivered_page_shows_its_range_of_the_total() {
45
1
    let mut app = crate::test_support::app();
46
1
    app.switch_tab(Tab::Transactions);
47
1
    deliver(&mut app, &page_wire(1, &["a", "b", "c"], true, 45));
48
1
    assert_eq!(
49
1
        app.transactions().range_note(0..3).as_deref(),
50
1
        Some("1\u{2013}3 of 45")
51
    );
52
1
    assert_eq!(row_ids(&app), ["a", "b", "c"]);
53
1
}
54

            
55
#[test]
56
1
fn rows_keep_the_order_the_server_replied_in() {
57
1
    let mut app = crate::test_support::app();
58
1
    deliver(&mut app, &page_wire(1, &["z", "m", "a"], false, 3));
59
1
    assert_eq!(row_ids(&app), ["z", "m", "a"]);
60
1
}
61

            
62
#[tokio::test]
63
1
async fn page_down_requests_the_next_offset_and_page_up_returns() {
64
1
    let mut app = crate::test_support::app();
65
1
    let sent = app.attach_echo();
66
1
    app.switch_tab(Tab::Transactions);
67
1
    deliver(&mut app, &page_wire(1, &["a"], true, 45));
68
1
    apply(&mut app, Intent::ListPageNext);
69
1
    tokio::task::yield_now().await;
70
1
    app.drain_eval();
71
1
    let requested = |offset: u32| {
72
1
        sent.frames()
73
1
            .iter()
74
2
            .any(|line| line.contains(&format!(r#":offset \"{offset}\""#)))
75
1
    };
76
1
    assert!(requested(20), "{:?}", sent.frames());
77
1
    deliver(&mut app, &page_wire(2, &["b"], true, 45));
78
1
    apply(&mut app, Intent::ListPagePrev);
79
1
    tokio::task::yield_now().await;
80
1
    app.drain_eval();
81
1
    assert_eq!(
82
1
        sent.frames()
83
1
            .iter()
84
3
            .filter(|line| line.contains(r#":offset \"0\""#))
85
1
            .count(),
86
1
        2,
87
1
        "initial fetch and the way back"
88
1
    );
89
1
}
90

            
91
2
fn press_bar(app: &mut App, part: tvui::BarPart) {
92
2
    crate::test_support::redraw(app);
93
2
    let area = crate::test_support::area_of(app, Target::Scroll(Surface::List, part));
94
2
    let mouse = MouseEvent {
95
2
        kind: MouseEventKind::Down(MouseButton::Left),
96
2
        column: area.x,
97
2
        row: area.y,
98
2
        modifiers: KeyModifiers::NONE,
99
2
    };
100
2
    crate::mouse::handle_mouse(app, mouse, std::time::Instant::now());
101
2
}
102

            
103
#[tokio::test]
104
1
async fn the_scrollbar_page_areas_turn_the_server_page_both_ways() {
105
1
    let mut app = crate::test_support::app();
106
1
    let sent = app.attach_echo();
107
1
    app.switch_tab(Tab::Transactions);
108
1
    deliver(&mut app, &page_wire(1, &["a"], true, 45));
109
1
    press_bar(&mut app, tvui::BarPart::PageDown);
110
1
    tokio::task::yield_now().await;
111
1
    app.drain_eval();
112
2
    let requests = |offset: u32| {
113
5
        let line = |line: &&String| line.contains(&format!(r#":offset \"{offset}\""#));
114
2
        sent.frames().iter().filter(line).count()
115
2
    };
116
1
    assert_eq!(requests(20), 1, "{:?}", sent.frames());
117
1
    deliver(&mut app, &page_wire(2, &["b"], true, 45));
118
1
    press_bar(&mut app, tvui::BarPart::PageUp);
119
1
    tokio::task::yield_now().await;
120
1
    app.drain_eval();
121
1
    assert_eq!(requests(0), 2, "initial fetch and the way back");
122
1
}
123

            
124
#[tokio::test]
125
1
async fn page_up_on_the_first_page_requests_nothing() {
126
1
    let mut app = crate::test_support::app();
127
1
    app.attach_echo();
128
1
    app.switch_tab(Tab::Transactions);
129
1
    deliver(&mut app, &page_wire(1, &["a"], true, 45));
130
1
    apply(&mut app, Intent::ListPagePrev);
131
1
    assert!(matches!(app.transactions().state, Fetch::Loaded(_)));
132
1
}
133

            
134
#[tokio::test]
135
1
async fn page_down_on_the_last_page_requests_nothing() {
136
1
    let mut app = crate::test_support::app();
137
1
    app.attach_echo();
138
1
    app.switch_tab(Tab::Transactions);
139
1
    deliver(&mut app, &page_wire(1, &["a"], false, 1));
140
1
    apply(&mut app, Intent::ListPageNext);
141
1
    assert!(matches!(app.transactions().state, Fetch::Loaded(_)));
142
1
}
143

            
144
#[tokio::test]
145
1
async fn deleting_the_last_row_of_a_page_steps_back() {
146
1
    let mut app = crate::test_support::app();
147
1
    let sent = app.attach_echo();
148
1
    app.switch_tab(Tab::Transactions);
149
1
    deliver(&mut app, &page_wire(1, &["a"], true, 40));
150
1
    apply(&mut app, Intent::ListPageNext);
151
1
    deliver(&mut app, &page_wire(2, &[], false, 20));
152
1
    assert!(matches!(app.transactions().state, Fetch::Loading { .. }));
153
1
    tokio::task::yield_now().await;
154
1
    app.drain_eval();
155
2
    let offsets = |offset: u32| {
156
2
        sent.frames()
157
2
            .iter()
158
6
            .filter(|line| line.contains(&format!(r#":offset \"{offset}\""#)))
159
            .count()
160
2
    };
161
1
    assert_eq!(offsets(0), 2, "initial fetch and the step back");
162
1
    assert_eq!(offsets(20), 1);
163
1
}
164

            
165
3
async fn settle(app: &mut App) {
166
3
    for _ in 0..200 {
167
12
        app.drain_eval();
168
12
        if matches!(app.transactions().state, Fetch::Loaded(_)) {
169
3
            return;
170
9
        }
171
9
        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
172
    }
173
3
}
174

            
175
3
async fn id_of(
176
3
    user: sqlx::types::Uuid,
177
3
    source: forms::Source,
178
3
    label: &str,
179
3
) -> anyhow::Result<String> {
180
3
    rpc::forms::options(user, source)
181
3
        .await
182
        .map_err(|err| anyhow::anyhow!("{err}"))?
183
        .into_iter()
184
5
        .find(|option| option.label == label)
185
3
        .map(|option| option.id.to_string())
186
        .ok_or_else(|| anyhow::anyhow!("no option {label}"))
187
3
}
188

            
189
1
async fn create_same_day(
190
1
    user: sqlx::types::Uuid,
191
1
    session: &mut Session,
192
1
    count: usize,
193
1
) -> anyhow::Result<()> {
194
1
    let cash = id_of(user, forms::Source::Accounts, "Cash").await?;
195
1
    let food = id_of(user, forms::Source::Accounts, "Food").await?;
196
1
    let usd = id_of(user, forms::Source::Commodities, "USD").await?;
197
1
    for n in 0..count {
198
25
        let payload = format!(
199
25
            r#"(:date \"2026-10-01\" :note \"n{n}\" :splits ((:from \"{cash}\" :to \"{food}\" :from-commodity \"{usd}\" :value \"5\")))"#
200
        );
201
25
        let reply = session
202
25
            .handle_form(&format!(
203
25
                r#"(:id 1 :form (submit-form "transaction-create" "{payload}"))"#
204
25
            ))
205
25
            .await;
206
25
        assert!(reply.contains(":value"), "{reply}");
207
    }
208
1
    Ok(())
209
1
}
210

            
211
#[sqlx::test(migrator = "server::db::MIGRATOR")]
212
async fn pages_walk_equal_dates_in_a_stable_order_with_the_total(
213
    pool: PgPool,
214
) -> anyhow::Result<()> {
215
    let _guard = server::db::install_test_pool(pool.clone());
216
    let fixture = seed(&pool).await?;
217
    let mut session = Session::new(ScriptCtx::new(fixture.user))?;
218
    create_same_day(fixture.user, &mut session, 25).await?;
219
    let mut app = crate::test_support::app();
220
    app.attach_console(ConsoleEval::connect(
221
        &tokio::runtime::Handle::current(),
222
        ScriptCtx::new(fixture.user),
223
        Session::new,
224
    )?);
225

            
226
    app.switch_tab(Tab::Transactions);
227
    settle(&mut app).await;
228
    let first = row_ids(&app);
229
    assert_eq!(first.len(), 20);
230
    assert_eq!(
231
        app.transactions().range_note(0..20).as_deref(),
232
        Some("1\u{2013}20 of 26")
233
    );
234

            
235
    apply(&mut app, Intent::ListPageNext);
236
    settle(&mut app).await;
237
    let second = row_ids(&app);
238
    assert_eq!(second.len(), 6);
239
    assert_eq!(
240
        app.transactions().range_note(0..6).as_deref(),
241
        Some("21\u{2013}26 of 26")
242
    );
243

            
244
    let tied: Vec<String> = first.iter().chain(&second).skip(1).cloned().collect();
245
    let all: std::collections::HashSet<_> = first.iter().chain(&second).collect();
246
    assert_eq!(all.len(), 26, "no row repeats or is skipped");
247
    let mut descending = tied.clone();
248
24
    descending.sort_by(|a, b| b.cmp(a));
249
    assert_eq!(tied, descending, "equal dates order by id, newest first");
250

            
251
    apply(&mut app, Intent::ListPagePrev);
252
    settle(&mut app).await;
253
    assert_eq!(row_ids(&app), first);
254
    Ok(())
255
}
256

            
257
#[tokio::test]
258
1
async fn a_page_arriving_after_a_tab_switch_leaves_the_status_alone() {
259
1
    let mut app = crate::test_support::app();
260
1
    app.attach_echo();
261
1
    app.switch_tab(Tab::Transactions);
262
1
    app.switch_tab(Tab::Config);
263
1
    app.set_status("config note");
264
1
    deliver(&mut app, &page_wire(1, &["a"], true, 45));
265
1
    assert_eq!(app.status, "config note");
266
1
}
267

            
268
5
fn screen_row(app: &App, width: u16, y: u16) -> String {
269
    use ratatui::Terminal;
270
    use ratatui::backend::TestBackend;
271
5
    let mut terminal = Terminal::new(TestBackend::new(width, 24)).expect("test terminal");
272
5
    terminal
273
5
        .draw(|frame| crate::draw::draw(frame, app, &mut crate::hits::Hits::default()))
274
5
        .expect("draw");
275
5
    let buffer = terminal.backend().buffer();
276
540
    (0..width).map(|x| buffer[(x, y)].symbol()).collect()
277
5
}
278

            
279
2
fn bottom_row(app: &App, width: u16) -> String {
280
2
    screen_row(app, width, 23)
281
2
}
282

            
283
#[test]
284
1
fn the_range_is_in_the_list_border_and_the_bar_keeps_hints_and_indicator() {
285
1
    let mut app = crate::test_support::app();
286
1
    app.switch_tab(Tab::Transactions);
287
1
    deliver(&mut app, &page_wire(1, &["a", "b", "c"], true, 45));
288
1
    let row = bottom_row(&app, 160);
289
1
    assert!(row.contains("Enter Detail"), "{row:?}");
290
1
    assert!(row.contains("user="), "{row:?}");
291
1
    assert!(row.trim_end().ends_with("  [cua]"), "{row:?}");
292
1
    assert!(!row.contains("of 45"), "{row:?}");
293
1
    assert!(app.status.is_empty(), "{}", app.status);
294
1
    for width in [160, 80, 40] {
295
3
        let border = screen_row(&app, width, 22);
296
3
        assert!(border.contains(" 1\u{2013}3 of 45 "), "{width}: {border:?}");
297
    }
298
1
}
299

            
300
#[test]
301
1
fn a_real_message_still_takes_the_row_over_the_range() {
302
1
    let mut app = crate::test_support::app();
303
1
    app.switch_tab(Tab::Transactions);
304
1
    deliver(&mut app, &page_wire(1, &["a", "b", "c"], true, 45));
305
1
    app.set_status("saved");
306
1
    let row = bottom_row(&app, 100);
307
1
    assert!(row.starts_with("[cua] saved"), "{row:?}");
308
1
    assert!(!row.contains("of 45"), "{row:?}");
309
1
}