1
//! The category CSV pane: `x` fetches it, `y` copies it by OSC 52, `s` saves it locally.
2

            
3
use crate::tabs::nms_eval::double::Sent;
4
use crate::test_support::{key, press};
5
use cli_core::report_form::csv_call;
6
use cli_core::transaction::submit_call;
7
use forms::{FormValues, REPORT_CATEGORY, escape_str, write_payload};
8
use sqlx::types::Uuid;
9

            
10
use super::report_chart::{EMPTY, echoed, pending, rendered, text};
11
use crate::app::App;
12
use crate::event::{Intent, apply};
13
use crate::modal::{ConfirmAction, Modal};
14
use crate::route::RouteCtx;
15
use crate::tabs::reports::ReportKind;
16
use crate::view::Tab;
17
use ratatui::crossterm::event::KeyCode;
18

            
19
const CSV: &str = "name,amount\nfood,10\nrent,20\n";
20

            
21
13
fn category() -> FormValues {
22
13
    let mut values = FormValues::default();
23
13
    values.set("from", "2026-01-01");
24
13
    values.set("to", "2026-02-01");
25
13
    values
26
13
}
27

            
28
10
fn with_category() -> (App, Sent) {
29
10
    let mut app = crate::test_support::app();
30
10
    let sent = app.attach_echo();
31
10
    app.switch_tab(Tab::Reports);
32
10
    app.submit_report(
33
10
        app.window_of(crate::view::ViewId::Reports),
34
10
        ReportKind::Breakdown,
35
10
        &category(),
36
10
    );
37
10
    let [run] = pending(&app, |ctx| matches!(ctx, RouteCtx::Reports { .. }))[..] else {
38
        panic!("one report run");
39
    };
40
10
    app.route_reply(run, EMPTY);
41
10
    (app, sent)
42
10
}
43

            
44
12
fn csv_requests(app: &App) -> Vec<i64> {
45
12
    pending(app, |ctx| matches!(ctx, RouteCtx::ReportCsv { .. }))
46
12
}
47

            
48
8
fn csv_wire(id: i64, csv: &str) -> String {
49
8
    let quoted = csv.replace('\\', "\\\\").replace('"', "\\\"");
50
8
    format!("(:id {id} :value \"{quoted}\")")
51
8
}
52

            
53
/// An app showing the CSV pane for [`CSV`].
54
6
fn with_pane() -> App {
55
6
    let (mut app, _) = with_category();
56
6
    press(&mut app, key(KeyCode::Char('x')));
57
6
    let [id] = csv_requests(&app)[..] else {
58
        panic!("one csv request");
59
    };
60
6
    app.route_reply(id, &csv_wire(id, CSV));
61
6
    app
62
6
}
63

            
64
2
fn scratch_file(name: &str) -> std::path::PathBuf {
65
2
    let dir = std::env::temp_dir().join(format!("tui-csv-{}", Uuid::new_v4()));
66
2
    std::fs::create_dir_all(&dir).expect("scratch dir");
67
2
    dir.join(name)
68
2
}
69

            
70
3
fn path_values(path: &std::path::Path) -> FormValues {
71
3
    let mut values = FormValues::default();
72
3
    values.set("path", &path.display().to_string());
73
3
    values
74
3
}
75

            
76
#[tokio::test]
77
1
async fn x_without_a_report_says_so() {
78
1
    let mut app = crate::test_support::app();
79
1
    app.switch_tab(Tab::Reports);
80
1
    press(&mut app, key(KeyCode::Char('x')));
81
1
    assert_eq!(app.status, "no report run yet");
82
1
    assert!(csv_requests(&app).is_empty());
83
1
}
84

            
85
#[tokio::test]
86
1
async fn x_on_another_report_is_refused() {
87
1
    let mut app = crate::test_support::app();
88
1
    app.attach_echo();
89
1
    app.switch_tab(Tab::Reports);
90
1
    app.submit_report(
91
1
        app.window_of(crate::view::ViewId::Reports),
92
1
        ReportKind::Balance,
93
1
        &FormValues::default(),
94
1
    );
95
1
    let [run] = pending(&app, |ctx| matches!(ctx, RouteCtx::Reports { .. }))[..] else {
96
        panic!("one report run");
97
    };
98
1
    app.route_reply(run, EMPTY);
99
1
    press(&mut app, key(KeyCode::Char('x')));
100
1
    assert_eq!(app.status, "CSV is only for the category report");
101
1
    assert!(csv_requests(&app).is_empty());
102
1
}
103

            
104
#[tokio::test]
105
1
async fn the_csv_request_carries_the_payload_the_report_ran_with() {
106
1
    let (mut app, sent) = with_category();
107
1
    press(&mut app, key(KeyCode::Char('x')));
108
1
    assert_eq!(csv_requests(&app).len(), 1);
109
1
    let echoed = echoed(&mut app, &sent).await;
110
1
    let payload = escape_str(&write_payload(&REPORT_CATEGORY, &category()));
111
1
    assert!(echoed.contains(&csv_call(&REPORT_CATEGORY, &category())));
112
1
    assert!(echoed.contains(&format!("(report-csv {payload})")));
113
1
    assert!(echoed.contains(&submit_call(&REPORT_CATEGORY, &category())));
114
1
}
115

            
116
#[tokio::test]
117
1
async fn the_reply_opens_a_read_only_pane_with_the_csv() {
118
1
    let app = with_pane();
119
1
    let Some(Modal::Csv(csv)) = app.overlays.top() else {
120
        panic!("csv pane on top");
121
    };
122
1
    assert_eq!(csv.text, CSV);
123
1
    assert_eq!(csv.file_name, "category-2026-01-01-2026-02-01.csv");
124
1
    let shown = text(&rendered(&app, 100, 20));
125
1
    assert!(shown.contains("name,amount"), "{shown}");
126
1
    assert!(shown.contains("rent,20"), "{shown}");
127
1
}
128

            
129
#[tokio::test]
130
1
async fn the_pane_scrolls_and_closes() {
131
1
    let mut app = with_pane();
132
1
    crate::test_support::draw_once(&app, 80, 8);
133
1
    press(&mut app, key(KeyCode::Down));
134
1
    let Some(Modal::Csv(csv)) = app.overlays.top() else {
135
        panic!("csv pane on top");
136
    };
137
1
    assert_eq!(csv.scroll.top(), 1);
138
1
    press(&mut app, key(KeyCode::Esc));
139
1
    assert!(app.overlays.is_empty());
140
1
}
141

            
142
#[tokio::test]
143
1
async fn y_queues_the_osc52_sequence_for_the_terminal() {
144
1
    let mut app = with_pane();
145
1
    press(&mut app, key(KeyCode::Char('y')));
146
1
    assert_eq!(
147
1
        app.take_outbound(),
148
1
        vec![b"\x1b]52;c;bmFtZSxhbW91bnQKZm9vZCwxMApyZW50LDIwCg==\x07".to_vec()]
149
    );
150
1
    assert!(app.take_outbound().is_empty());
151
1
    assert_eq!(app.status, "CSV copied to the clipboard");
152
1
}
153

            
154
#[tokio::test]
155
1
async fn y_over_the_size_limit_copies_nothing() {
156
1
    let (mut app, _) = with_category();
157
1
    press(&mut app, key(KeyCode::Char('x')));
158
1
    let [id] = csv_requests(&app)[..] else {
159
        panic!("one csv request");
160
    };
161
1
    app.route_reply(id, &csv_wire(id, &"x".repeat(100_000)));
162
1
    press(&mut app, key(KeyCode::Char('y')));
163
1
    assert!(app.take_outbound().is_empty());
164
1
    assert!(app.status.contains("too large"), "{}", app.status);
165
1
}
166

            
167
#[tokio::test]
168
1
async fn saving_is_refused_over_ssh() {
169
1
    let mut app = with_pane();
170
1
    assert!(!app.local_files);
171
1
    press(&mut app, key(KeyCode::Char('s')));
172
1
    assert_eq!(app.status, "save is not available over ssh");
173
1
    assert!(matches!(app.overlays.top(), Some(Modal::Csv(_))));
174

            
175
1
    let path = scratch_file("refused.csv");
176
1
    app.save_csv(&path_values(&path));
177
1
    assert_eq!(app.status, "save is not available over ssh");
178
1
    assert!(!path.exists());
179
1
}
180

            
181
#[tokio::test]
182
1
async fn s_locally_asks_for_the_default_path() {
183
1
    let mut app = with_pane();
184
1
    app.local_files = true;
185
1
    press(&mut app, key(KeyCode::Char('s')));
186
1
    let Some(Modal::Form(form)) = app.overlays.top() else {
187
        panic!("save prompt on top");
188
    };
189
1
    assert_eq!(
190
1
        form.values().text("path"),
191
1
        Some("category-2026-01-01-2026-02-01.csv")
192
1
    );
193
1
}
194

            
195
#[tokio::test]
196
1
async fn saving_writes_the_file_and_asks_before_overwriting() {
197
1
    let mut app = with_pane();
198
1
    app.local_files = true;
199
1
    let path = scratch_file("out.csv");
200

            
201
1
    app.save_csv(&path_values(&path));
202
1
    assert_eq!(std::fs::read_to_string(&path).expect("written"), CSV);
203

            
204
1
    std::fs::write(&path, "old").expect("seed");
205
1
    app.save_csv(&path_values(&path));
206
1
    assert_eq!(std::fs::read_to_string(&path).expect("kept"), "old");
207
1
    assert!(matches!(
208
1
        app.overlays.top(),
209
        Some(Modal::Confirm {
210
            action: ConfirmAction::OverwriteCsv(_),
211
            ..
212
        })
213
    ));
214

            
215
1
    apply(&mut app, Intent::ConfirmYes);
216
1
    assert_eq!(std::fs::read_to_string(&path).expect("replaced"), CSV);
217
1
    let leftovers = std::fs::read_dir(path.parent().expect("dir"))
218
1
        .expect("list")
219
1
        .count();
220
1
    assert_eq!(leftovers, 1);
221
1
    assert!(matches!(app.overlays.top(), Some(Modal::Csv(_))));
222
1
}
223

            
224
#[tokio::test]
225
1
async fn a_server_error_goes_to_the_status_and_keeps_the_table() {
226
1
    let (mut app, _) = with_category();
227
1
    assert!(text(&rendered(&app, 100, 20)).contains("(no data)"));
228
1
    press(&mut app, key(KeyCode::Char('x')));
229
1
    let [id] = csv_requests(&app)[..] else {
230
        panic!("one csv request");
231
    };
232
1
    app.route_reply(
233
1
        id,
234
1
        &format!(r#"(:id {id} :error (:code args :message "bad"))"#),
235
1
    );
236
1
    assert!(app.overlays.is_empty());
237
1
    assert!(app.status.contains("bad"), "{}", app.status);
238
1
    let shown = text(&rendered(&app, 100, 20));
239
1
    assert!(shown.contains("(no data)"), "{shown}");
240
1
    assert!(!shown.contains("[error]"), "{shown}");
241
1
}
242

            
243
#[tokio::test]
244
1
async fn an_older_csv_reply_is_dropped() {
245
1
    let (mut app, _) = with_category();
246
1
    press(&mut app, key(KeyCode::Char('x')));
247
1
    let [first] = csv_requests(&app)[..] else {
248
        panic!("one csv request");
249
    };
250
1
    press(&mut app, key(KeyCode::Char('x')));
251
1
    app.route_reply(first, &csv_wire(first, CSV));
252
1
    assert!(app.overlays.is_empty());
253
1
}