1
//! The balance page on its descriptor form: its data against the command
2
//! it replaced, the chart endpoints on the same values, and the refusals.
3

            
4
use axum::{
5
    Router,
6
    body::Body,
7
    http::{Request, StatusCode},
8
    routing::get,
9
};
10
use forms::parse_date;
11
use plotting::adapters::{BalanceChartOpts, balance_chart};
12
use rpc::chart::{ChartOpts, chart_spec};
13
use rpc::forms::ReportOutcome;
14
use serde_json::Value;
15
use server::command::report::BalanceReport;
16
use server::command::report::view::flatten_report_data;
17
use server::command::{CmdResult, ReportFilter};
18
use tower::ServiceExt;
19
use web::model::User;
20
use web::pages::report::{balance, parse_sort_order_shared};
21
use web::route::create_api_router;
22

            
23
use crate::common::controls::unescape;
24
use crate::common::new_page::{Reply, input_value, seeded_ids, seeded_user, send_to};
25
use crate::common::report_seed::{spend, spend_at, today_string};
26
use crate::common::{create_test_app_state, test_limiter};
27

            
28
const FILTER: &str = r#"(split-tag= "category" "Rent")"#;
29

            
30
1
fn encode(raw: &str) -> String {
31
1
    serde_urlencoded::to_string([("q", raw)])
32
1
        .unwrap_or_default()
33
1
        .trim_start_matches("q=")
34
1
        .to_string()
35
1
}
36

            
37
15
async fn fetch(user: &User, path: &str, query: &str, json: bool) -> Reply {
38
15
    let router = Router::new()
39
15
        .route("/balance", get(balance::balance_report_table))
40
15
        .route(
41
15
            "/balance/chart.json",
42
15
            get(balance::balance_report_chart_json),
43
15
        );
44
15
    let mut request = Request::builder().uri(format!("{path}?{query}"));
45
15
    if json {
46
8
        request = request.header("accept", "application/json");
47
7
    }
48
15
    send_to(router, user, request.body(Body::empty()).expect("request")).await
49
15
}
50

            
51
8
fn json(reply: &Reply) -> Value {
52
8
    assert_eq!(reply.status, StatusCode::OK, "{}", reply.body);
53
8
    serde_json::from_str(&reply.body).expect("json body")
54
8
}
55

            
56
/// What the command the page used to call answers for these bounds.
57
struct Bounds<'a> {
58
    target: Option<&'a str>,
59
    from: Option<&'a str>,
60
    as_of: &'a str,
61
    filter: Option<&'a str>,
62
}
63

            
64
5
async fn command_data(user: &User, bounds: Bounds<'_>) -> Value {
65
5
    let mut cmd = BalanceReport::new()
66
5
        .user_id(user.id)
67
5
        .as_of(end_of(bounds.as_of));
68
5
    if let Some(target) = bounds.target {
69
1
        cmd = cmd.target_commodity_id(target.parse().expect("id"));
70
4
    }
71
5
    if let Some(from) = bounds.from {
72
1
        cmd = cmd.date_from(parse_date(from, false).expect("date"));
73
4
    }
74
5
    if let Some(filter) = bounds.filter {
75
1
        cmd = cmd.report_filter(ReportFilter::from_sexpr(filter).expect("filter"));
76
4
    }
77
5
    match cmd.run().await {
78
5
        Ok(Some(CmdResult::Report(data))) => serde_json::to_value(data).expect("report json"),
79
        other => panic!("report: {other:?}"),
80
    }
81
5
}
82

            
83
7
fn end_of(day: &str) -> chrono::DateTime<chrono::Utc> {
84
7
    parse_date(day, true).expect("date")
85
7
}
86

            
87
#[supp_macro::shared_runtime_test]
88
1
async fn the_page_data_equals_the_command_it_replaced() {
89
1
    let user = seeded_user().await;
90
1
    spend(&user, "Rent", "300").await;
91
1
    spend(&user, "Fun", "20").await;
92
1
    let usd = seeded_ids(&user).await.usd;
93
1
    let today = today_string();
94
1
    let cases = [
95
1
        (
96
1
            String::new(),
97
1
            Bounds {
98
1
                target: None,
99
1
                from: None,
100
1
                as_of: &today,
101
1
                filter: None,
102
1
            },
103
1
        ),
104
1
        (
105
1
            format!("target={usd}"),
106
1
            Bounds {
107
1
                target: Some(&usd),
108
1
                from: None,
109
1
                as_of: &today,
110
1
                filter: None,
111
1
            },
112
1
        ),
113
1
        (
114
1
            "from=2026-03-01&as-of=2026-03-31".to_string(),
115
1
            Bounds {
116
1
                target: None,
117
1
                from: Some("2026-03-01"),
118
1
                as_of: "2026-03-31",
119
1
                filter: None,
120
1
            },
121
1
        ),
122
1
        (
123
1
            "as-of=2026-03-09".to_string(),
124
1
            Bounds {
125
1
                target: None,
126
1
                from: None,
127
1
                as_of: "2026-03-09",
128
1
                filter: None,
129
1
            },
130
1
        ),
131
1
        (
132
1
            format!("filter={}", encode(FILTER)),
133
1
            Bounds {
134
1
                target: None,
135
1
                from: None,
136
1
                as_of: &today,
137
1
                filter: Some(FILTER),
138
1
            },
139
1
        ),
140
1
    ];
141
1
    for (query, bounds) in cases {
142
5
        let page = json(&fetch(&user, "/balance", &query, true).await);
143
5
        assert_eq!(page, command_data(&user, bounds).await, "{query}");
144
    }
145
}
146

            
147
#[supp_macro::shared_runtime_test]
148
1
async fn the_chart_endpoint_draws_the_page_data() {
149
1
    let user = seeded_user().await;
150
1
    spend(&user, "Rent", "300").await;
151
1
    let query = "from=2026-03-01&as-of=2026-03-31&chart_kind=line";
152
1
    let chart = json(&fetch(&user, "/balance/chart.json", query, false).await);
153
1
    let data = BalanceReport::new()
154
1
        .user_id(user.id)
155
1
        .date_from(parse_date("2026-03-01", false).expect("date"))
156
1
        .as_of(end_of("2026-03-31"))
157
1
        .run()
158
1
        .await;
159

            
160
1
    let Ok(Some(CmdResult::Report(data))) = data else {
161
        panic!("report: {data:?}");
162
    };
163
1
    let spec = balance_chart(
164
1
        &flatten_report_data(&data),
165
1
        BalanceChartOpts {
166
1
            kind: plotting::ChartKind::Line,
167
1
            top_n: 10,
168
1
            sort_order: parse_sort_order_shared(None).into_plotting_balance(),
169
1
        },
170
1
    );
171
1
    assert_eq!(chart, serde_json::to_value(spec).expect("spec json"));
172
}
173

            
174
#[supp_macro::shared_runtime_test]
175
1
async fn the_sort_order_option_reorders_the_chart() {
176
1
    let user = seeded_user().await;
177
1
    spend(&user, "Rent", "300").await;
178
1
    spend(&user, "Fun", "20").await;
179
1
    let query = "from=2026-03-01&as-of=2026-03-31";
180
1
    let by_amount = json(&fetch(&user, "/balance/chart.json", query, false).await);
181
1
    let by_name_desc = json(
182
1
        &fetch(
183
1
            &user,
184
1
            "/balance/chart.json",
185
1
            &format!("{query}&sort_order=name_desc"),
186
1
            false,
187
1
        )
188
1
        .await,
189
    );
190
1
    let data = BalanceReport::new()
191
1
        .user_id(user.id)
192
1
        .date_from(parse_date("2026-03-01", false).expect("date"))
193
1
        .as_of(end_of("2026-03-31"))
194
1
        .run()
195
1
        .await;
196
1
    let Ok(Some(CmdResult::Report(data))) = data else {
197
        panic!("report: {data:?}");
198
    };
199

            
200
1
    let spec = chart_spec(
201
1
        &ReportOutcome::Balance(data),
202
1
        &ChartOpts {
203
1
            sort: parse_sort_order_shared(Some("name_desc")).into_plotting_balance(),
204
1
            ..ChartOpts::default()
205
1
        },
206
1
    )
207
1
    .expect("chart");
208

            
209
1
    assert_eq!(by_name_desc, serde_json::to_value(spec).expect("spec json"));
210
1
    assert_eq!(labels(&by_amount), ["Assets:Checking", "Expenses:Food"]);
211
1
    assert_eq!(labels(&by_name_desc), ["Expenses:Food", "Assets:Checking"]);
212
}
213

            
214
2
fn labels(chart: &Value) -> Vec<&str> {
215
2
    chart["series"]
216
2
        .as_array()
217
2
        .into_iter()
218
2
        .flatten()
219
4
        .filter_map(|series| series["label"].as_str())
220
        .collect()
221
2
}
222

            
223
#[supp_macro::shared_runtime_test]
224
1
async fn the_default_page_shows_today_in_the_form() {
225
1
    let user = seeded_user().await;
226
1
    let page = fetch(&user, "/balance", "", false).await;
227

            
228
1
    assert_eq!(page.status, StatusCode::OK, "{}", page.body);
229
1
    assert_eq!(
230
1
        input_value(&page.body, "as-of"),
231
1
        Some(today_string().as_str())
232
    );
233
}
234

            
235
#[supp_macro::shared_runtime_test]
236
1
async fn a_bad_date_or_filter_rerenders_the_form_with_its_values() {
237
1
    let user = seeded_user().await;
238
1
    let date = fetch(&user, "/balance", "as-of=nope&from=2026-01-01", false).await;
239
1
    let filter = fetch(&user, "/balance", "filter=%28and", false).await;
240
1
    let as_json = fetch(&user, "/balance", "as-of=nope", true).await;
241

            
242
1
    for reply in [&date, &filter] {
243
2
        assert_eq!(
244
2
            reply.status,
245
2
            StatusCode::UNPROCESSABLE_ENTITY,
246
            "{}",
247
            reply.body
248
        );
249
2
        assert_eq!(
250
2
            reply.headers.get("hx-retarget").map(|v| v.as_bytes()),
251
2
            Some(b"#nf-report-balance".as_slice())
252
        );
253
2
        assert!(reply.body.contains("field-error"), "{}", reply.body);
254
    }
255
1
    assert_eq!(input_value(&date.body, "as-of"), Some("nope"));
256
1
    assert_eq!(input_value(&date.body, "from"), Some("2026-01-01"));
257
1
    assert!(unescape(&filter.body).contains(">\n(and</textarea>"));
258
1
    assert_eq!(as_json.status, StatusCode::UNPROCESSABLE_ENTITY);
259
}
260

            
261
#[supp_macro::shared_runtime_test]
262
1
async fn the_old_names_are_refused_naming_the_new_key() {
263
1
    let state = create_test_app_state().await;
264
1
    let app = create_api_router(state.clone(), test_limiter()).with_state(state);
265
1
    for (query, message) in [
266
1
        (
267
1
            "target_commodity_id=x",
268
1
            "target_commodity_id is no longer supported; use target",
269
1
        ),
270
1
        (
271
1
            "date_from=2026-01-01",
272
1
            "date_from is no longer supported; use from",
273
1
        ),
274
1
        (
275
1
            "as_of=2026-01-01",
276
1
            "as_of is no longer supported; use as-of",
277
1
        ),
278
1
    ] {
279
3
        for path in [
280
3
            "/report/balance",
281
3
            "/report/balance/chart.svg",
282
3
            "/report/balance/chart.json",
283
3
        ] {
284
9
            let request = Request::builder()
285
9
                .uri(format!("{path}?{query}"))
286
9
                .body(Body::empty())
287
9
                .expect("request");
288
9
            let response = app.clone().oneshot(request).await.expect("response");
289
9
            assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{path}?{query}");
290
9
            let body = axum::body::to_bytes(response.into_body(), usize::MAX)
291
9
                .await
292
9
                .expect("body");
293
9
            let text = String::from_utf8_lossy(&body);
294
9
            assert!(text.contains(message), "{path}?{query}: {text}");
295
        }
296
    }
297
}
298

            
299
#[supp_macro::shared_runtime_test]
300
1
async fn a_whole_day_as_of_includes_a_late_transaction_of_that_day() {
301
1
    let user = seeded_user().await;
302
1
    spend_at(&user, "Rent", "300", "2026-03-10T23:30:00Z").await;
303
1
    let same_day = fetch(&user, "/balance", "as-of=2026-03-10", true).await;
304
1
    let day_before = fetch(&user, "/balance", "as-of=2026-03-09", true).await;
305

            
306
1
    assert!(same_day.body.contains("Food"), "{}", same_day.body);
307
1
    assert!(!day_before.body.contains("Food"), "{}", day_before.body);
308
}
309

            
310
#[supp_macro::shared_runtime_test]
311
1
async fn the_report_dates_are_whole_day_inputs() {
312
1
    let user = seeded_user().await;
313
1
    let page = fetch(&user, "/balance", "from=2026-03-01", false).await;
314

            
315
1
    for name in ["from", "as-of"] {
316
2
        let tag = format!("type=\"date\" name=\"{name}\"");
317
2
        assert!(page.body.contains(&tag), "{name}: {}", page.body);
318
    }
319
1
    assert!(!page.body.contains("datetime-local"), "{}", page.body);
320
}