1
use axum::http::{HeaderMap, StatusCode, header::CONTENT_TYPE};
2
use axum::response::{IntoResponse, Response};
3
use num_rational::Rational64;
4
use rpc::chart::{
5
    DEFAULT_HEIGHT, DEFAULT_WIDTH, SortOrder, kind_name, kind_or_default, render_svg_chart,
6
};
7

            
8
pub mod activity;
9
pub mod activity_groups;
10
pub mod activity_query;
11
pub mod balance;
12
pub mod balance_query;
13
pub mod bookmark;
14
pub mod category_breakdown;
15
pub mod category_breakdown_csv;
16
pub mod category_breakdown_query;
17
pub mod invalid;
18
pub mod query;
19
pub mod retired;
20

            
21
use server::command::report::view;
22
use view::AmountView;
23

            
24
/// A single card in the top-of-report summary strip. `is_net` flags cards
25
/// that show a signed net (e.g. Income − Expense) so templates can
26
/// style them distinctly; `highlight` is a generic accent slot.
27
pub struct SummaryCard {
28
    pub label: String,
29
    pub amounts: Vec<AmountView>,
30
    pub is_net: bool,
31
    pub highlight: bool,
32
}
33

            
34
/// Query-string fields shared by every report page to drive client-side
35
/// table controls. The server only needs to read `commodity_columns` (which
36
/// drives a template pivot) and forward `collapsed_depth` into the template
37
/// for initial fold state; `sort_by` is consumed purely by the frontend
38
/// WASM reorder logic, so the Rust handler does not parse it.
39
#[derive(Default)]
40
pub struct TableControlParams {
41
    pub collapsed_depth: Option<String>,
42
    pub commodity_columns: Option<String>,
43
}
44

            
45
impl TableControlParams {
46
    #[must_use]
47
31
    pub fn commodity_columns_enabled(&self) -> bool {
48
31
        self.commodity_columns
49
31
            .as_deref()
50
31
            .map(str::trim)
51
            .is_some_and(|v| v.eq_ignore_ascii_case("on") || v.eq_ignore_ascii_case("true"))
52
31
    }
53
}
54

            
55
/// Chart-specific query parameters shared across report chart handlers.
56
/// `chart_kind` maps to `rpc::chart::kind_or_default`; `chart_series` is a
57
/// report-specific toggle (e.g. Activity: show Net or not) parsed in
58
/// each handler. `renderer` picks between server-side SVG (default)
59
/// and client-side canvas.
60
#[derive(Default)]
61
pub struct ChartParams {
62
    pub chart_kind: Option<String>,
63
    pub chart_series: Option<String>,
64
    pub renderer: Option<String>,
65
}
66

            
67
impl ChartParams {
68
    /// Normalise the chart kind to its canonical lowercase name so
69
    /// the template can round-trip it into URLs and `<select>`
70
    /// values.
71
    #[must_use]
72
31
    pub fn chart_kind_str(&self) -> String {
73
31
        kind_name(kind_or_default(self.chart_kind.as_deref())).to_string()
74
31
    }
75

            
76
    /// Canonicalise the renderer choice. Accepts `svg` (default) and
77
    /// `canvas`; anything else normalises to `svg`.
78
    #[must_use]
79
31
    pub fn renderer_str(&self) -> String {
80
31
        match self.renderer.as_deref().map(str::to_ascii_lowercase) {
81
            Some(ref s) if s == "canvas" => "canvas".to_string(),
82
31
            _ => "svg".to_string(),
83
        }
84
31
    }
85
}
86

            
87
/// Minimal URL-query encoder for the (key, value) pairs the chart
88
/// endpoints take. Avoids pulling in `serde_urlencoded` just to
89
/// stringify a handful of params — keeps the handler simple.
90
#[must_use]
91
31
pub fn encode_query(pairs: &[(&str, &str)]) -> String {
92
31
    let mut out = String::new();
93
31
    for (k, v) in pairs {
94
153
        if v.is_empty() {
95
1
            continue;
96
152
        }
97
152
        if !out.is_empty() {
98
121
            out.push('&');
99
31
        }
100
152
        out.push_str(&percent_encode(k));
101
152
        out.push('=');
102
152
        out.push_str(&percent_encode(v));
103
    }
104
31
    if out.is_empty() {
105
        out
106
    } else {
107
31
        format!("?{out}")
108
    }
109
31
}
110

            
111
304
fn percent_encode(s: &str) -> String {
112
304
    let mut out = String::with_capacity(s.len());
113
304
    for b in s.bytes() {
114
2151
        let keep = b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~');
115
2151
        if keep {
116
2099
            out.push(b as char);
117
        } else {
118
52
            out.push_str(&format!("%{b:02X}"));
119
        }
120
    }
121
304
    out
122
304
}
123

            
124
#[must_use]
125
74
pub fn wants_json(headers: &HeaderMap) -> bool {
126
74
    headers
127
74
        .get("accept")
128
33
        .and_then(|v| v.to_str().ok())
129
33
        .is_some_and(|v| v.contains("application/json"))
130
74
}
131

            
132
/// Sum top-level rows' amounts per commodity. Used by Balance to build its
133
/// grand-total card(s).
134
#[must_use]
135
7
pub fn sum_top_level_amounts(rows: &[view::ReportRowView]) -> Vec<AmountView> {
136
7
    let mut out: Vec<AmountView> = Vec::new();
137
7
    for row in rows.iter().filter(|r| r.depth == 0) {
138
        for a in &row.amounts {
139
            match out
140
                .iter_mut()
141
                .find(|x| x.commodity_symbol == a.commodity_symbol)
142
            {
143
                Some(existing) => existing.amount += a.amount,
144
                None => out.push(AmountView {
145
                    commodity_symbol: a.commodity_symbol.clone(),
146
                    amount: a.amount,
147
                }),
148
            }
149
        }
150
    }
151
7
    out
152
7
}
153

            
154
/// Collect the set of commodity symbols present across all rows, in the
155
/// order the row-data first mentions them. Drives the "Commodities as
156
/// columns" pivot: a stable column ordering without depending on the
157
/// user's commodity list.
158
#[must_use]
159
7
pub fn commodity_symbols_in_rows(rows: &[view::ReportRowView]) -> Vec<String> {
160
7
    let mut seen = Vec::new();
161
7
    for row in rows {
162
        for a in &row.amounts {
163
            if !seen.iter().any(|s: &String| s == &a.commodity_symbol) {
164
                seen.push(a.commodity_symbol.clone());
165
            }
166
        }
167
    }
168
7
    seen
169
7
}
170

            
171
/// Look up a row's amount for the given commodity symbol. Called from the
172
/// commodity-columns branch of the tree-table template.
173
#[must_use]
174
pub fn row_amount_by_symbol(row: &view::ReportRowView, symbol: &str) -> Option<Rational64> {
175
    row.amounts
176
        .iter()
177
        .find(|a| a.commodity_symbol == symbol)
178
        .map(|a| a.amount)
179
}
180

            
181
/// The chart endpoints answer the SVG the spec draws.
182
1
pub fn chart_svg_response(spec: &plotting::ChartSpec) -> Response {
183
1
    (
184
1
        StatusCode::OK,
185
1
        [(CONTENT_TYPE, "image/svg+xml")],
186
1
        render_svg_chart(spec, DEFAULT_WIDTH, DEFAULT_HEIGHT),
187
1
    )
188
1
        .into_response()
189
1
}
190

            
191
/// Parse the shared `sort_order` query param. Balance and Breakdown
192
/// accept the same names; this keeps the URLs consistent between
193
/// them. Unknown values fall back to `AmountDesc` so a stale URL
194
/// still renders.
195
#[must_use]
196
12
pub fn parse_sort_order_shared(raw: Option<&str>) -> SharedSort {
197
12
    match raw.map(str::to_ascii_lowercase).as_deref() {
198
        Some("amount_asc") => SharedSort::AmountAsc,
199
4
        Some("name_asc") => SharedSort::NameAsc,
200
2
        Some("name_desc") => SharedSort::NameDesc,
201
6
        _ => SharedSort::AmountDesc,
202
    }
203
12
}
204

            
205
#[derive(Debug, Clone, Copy, Default)]
206
pub enum SharedSort {
207
    #[default]
208
    AmountDesc,
209
    AmountAsc,
210
    NameAsc,
211
    NameDesc,
212
}
213

            
214
impl SharedSort {
215
    #[must_use]
216
7
    pub fn to_str(self) -> &'static str {
217
7
        match self {
218
3
            Self::AmountDesc => "amount_desc",
219
            Self::AmountAsc => "amount_asc",
220
4
            Self::NameAsc => "name_asc",
221
            Self::NameDesc => "name_desc",
222
        }
223
7
    }
224

            
225
    /// Map to the plotting crate's balance-chart sort enum.
226
    #[must_use]
227
5
    pub fn into_plotting_balance(self) -> SortOrder {
228
5
        match self {
229
3
            Self::AmountDesc => SortOrder::MagnitudeDesc,
230
            Self::AmountAsc => SortOrder::MagnitudeAsc,
231
            Self::NameAsc => SortOrder::NameAsc,
232
2
            Self::NameDesc => SortOrder::NameDesc,
233
        }
234
5
    }
235
}
236

            
237
8
fn abs_rational(r: Rational64) -> Rational64 {
238
8
    if r < Rational64::new(0, 1) { -r } else { r }
239
8
}
240

            
241
/// Sort top-level rows in place according to `order`. Children ride
242
/// with their parent — they're adjacent in the flattened view and we
243
/// preserve that adjacency by sorting on a key derived from each
244
/// top-level row alone.
245
11
pub fn sort_top_level_rows(rows: &mut Vec<view::ReportRowView>, order: SharedSort) {
246
    // Group rows by their top-level ancestor. Flat projection is DFS
247
    // order: every depth-0 row is followed by its subtree before the
248
    // next depth-0 row, so a single pass builds the groups.
249
11
    let mut groups: Vec<Vec<view::ReportRowView>> = Vec::new();
250
11
    for row in std::mem::take(rows) {
251
16
        if row.depth == 0 || groups.is_empty() {
252
12
            groups.push(vec![row]);
253
4
        } else if let Some(last) = groups.last_mut() {
254
4
            last.push(row);
255
        }
256
    }
257

            
258
17
    groups.sort_by(|a, b| {
259
10
        let (a_root, b_root) = (&a[0], &b[0]);
260
10
        match order {
261
            SharedSort::AmountDesc => {
262
4
                let ka = a_root.amounts.iter().map(|x| abs_rational(x.amount)).max();
263
4
                let kb = b_root.amounts.iter().map(|x| abs_rational(x.amount)).max();
264
4
                kb.cmp(&ka)
265
            }
266
            SharedSort::AmountAsc => {
267
                let ka = a_root.amounts.iter().map(|x| abs_rational(x.amount)).max();
268
                let kb = b_root.amounts.iter().map(|x| abs_rational(x.amount)).max();
269
                ka.cmp(&kb)
270
            }
271
6
            SharedSort::NameAsc => a_root.account_name.cmp(&b_root.account_name),
272
            SharedSort::NameDesc => b_root.account_name.cmp(&a_root.account_name),
273
        }
274
10
    });
275

            
276
11
    for group in groups {
277
12
        rows.extend(group);
278
    }
279
11
}
280

            
281
#[cfg(test)]
282
#[path = "sort_tests.rs"]
283
mod sort_tests;
284

            
285
/// Breakdown equivalent of `row_amount_by_symbol`. Category Breakdown uses
286
/// a flat row type (`BreakdownRowView`) rather than the tree `ReportRowView`.
287
#[must_use]
288
pub fn breakdown_row_amount_by_symbol(
289
    row: &view::BreakdownRowView,
290
    symbol: &str,
291
) -> Option<Rational64> {
292
    row.amounts
293
        .iter()
294
        .find(|a| a.commodity_symbol == symbol)
295
        .map(|a| a.amount)
296
}