Skip to main content

web/pages/report/
mod.rs

1use axum::http::{HeaderMap, StatusCode, header::CONTENT_TYPE};
2use axum::response::{IntoResponse, Response};
3use num_rational::Rational64;
4use rpc::chart::{
5    DEFAULT_HEIGHT, DEFAULT_WIDTH, SortOrder, kind_name, kind_or_default, render_svg_chart,
6};
7
8pub mod activity;
9pub mod activity_groups;
10pub mod activity_query;
11pub mod balance;
12pub mod balance_query;
13pub mod bookmark;
14pub mod category_breakdown;
15pub mod category_breakdown_csv;
16pub mod category_breakdown_query;
17pub mod invalid;
18pub mod query;
19pub mod retired;
20
21use server::command::report::view;
22use 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.
27pub 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)]
40pub struct TableControlParams {
41    pub collapsed_depth: Option<String>,
42    pub commodity_columns: Option<String>,
43}
44
45impl TableControlParams {
46    #[must_use]
47    pub fn commodity_columns_enabled(&self) -> bool {
48        self.commodity_columns
49            .as_deref()
50            .map(str::trim)
51            .is_some_and(|v| v.eq_ignore_ascii_case("on") || v.eq_ignore_ascii_case("true"))
52    }
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)]
61pub struct ChartParams {
62    pub chart_kind: Option<String>,
63    pub chart_series: Option<String>,
64    pub renderer: Option<String>,
65}
66
67impl 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    pub fn chart_kind_str(&self) -> String {
73        kind_name(kind_or_default(self.chart_kind.as_deref())).to_string()
74    }
75
76    /// Canonicalise the renderer choice. Accepts `svg` (default) and
77    /// `canvas`; anything else normalises to `svg`.
78    #[must_use]
79    pub fn renderer_str(&self) -> String {
80        match self.renderer.as_deref().map(str::to_ascii_lowercase) {
81            Some(ref s) if s == "canvas" => "canvas".to_string(),
82            _ => "svg".to_string(),
83        }
84    }
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]
91pub fn encode_query(pairs: &[(&str, &str)]) -> String {
92    let mut out = String::new();
93    for (k, v) in pairs {
94        if v.is_empty() {
95            continue;
96        }
97        if !out.is_empty() {
98            out.push('&');
99        }
100        out.push_str(&percent_encode(k));
101        out.push('=');
102        out.push_str(&percent_encode(v));
103    }
104    if out.is_empty() {
105        out
106    } else {
107        format!("?{out}")
108    }
109}
110
111fn percent_encode(s: &str) -> String {
112    let mut out = String::with_capacity(s.len());
113    for b in s.bytes() {
114        let keep = b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~');
115        if keep {
116            out.push(b as char);
117        } else {
118            out.push_str(&format!("%{b:02X}"));
119        }
120    }
121    out
122}
123
124#[must_use]
125pub fn wants_json(headers: &HeaderMap) -> bool {
126    headers
127        .get("accept")
128        .and_then(|v| v.to_str().ok())
129        .is_some_and(|v| v.contains("application/json"))
130}
131
132/// Sum top-level rows' amounts per commodity. Used by Balance to build its
133/// grand-total card(s).
134#[must_use]
135pub fn sum_top_level_amounts(rows: &[view::ReportRowView]) -> Vec<AmountView> {
136    let mut out: Vec<AmountView> = Vec::new();
137    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    out
152}
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]
159pub fn commodity_symbols_in_rows(rows: &[view::ReportRowView]) -> Vec<String> {
160    let mut seen = Vec::new();
161    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    seen
169}
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]
174pub 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.
182pub fn chart_svg_response(spec: &plotting::ChartSpec) -> Response {
183    (
184        StatusCode::OK,
185        [(CONTENT_TYPE, "image/svg+xml")],
186        render_svg_chart(spec, DEFAULT_WIDTH, DEFAULT_HEIGHT),
187    )
188        .into_response()
189}
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]
196pub fn parse_sort_order_shared(raw: Option<&str>) -> SharedSort {
197    match raw.map(str::to_ascii_lowercase).as_deref() {
198        Some("amount_asc") => SharedSort::AmountAsc,
199        Some("name_asc") => SharedSort::NameAsc,
200        Some("name_desc") => SharedSort::NameDesc,
201        _ => SharedSort::AmountDesc,
202    }
203}
204
205#[derive(Debug, Clone, Copy, Default)]
206pub enum SharedSort {
207    #[default]
208    AmountDesc,
209    AmountAsc,
210    NameAsc,
211    NameDesc,
212}
213
214impl SharedSort {
215    #[must_use]
216    pub fn to_str(self) -> &'static str {
217        match self {
218            Self::AmountDesc => "amount_desc",
219            Self::AmountAsc => "amount_asc",
220            Self::NameAsc => "name_asc",
221            Self::NameDesc => "name_desc",
222        }
223    }
224
225    /// Map to the plotting crate's balance-chart sort enum.
226    #[must_use]
227    pub fn into_plotting_balance(self) -> SortOrder {
228        match self {
229            Self::AmountDesc => SortOrder::MagnitudeDesc,
230            Self::AmountAsc => SortOrder::MagnitudeAsc,
231            Self::NameAsc => SortOrder::NameAsc,
232            Self::NameDesc => SortOrder::NameDesc,
233        }
234    }
235}
236
237fn abs_rational(r: Rational64) -> Rational64 {
238    if r < Rational64::new(0, 1) { -r } else { r }
239}
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.
245pub 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    let mut groups: Vec<Vec<view::ReportRowView>> = Vec::new();
250    for row in std::mem::take(rows) {
251        if row.depth == 0 || groups.is_empty() {
252            groups.push(vec![row]);
253        } else if let Some(last) = groups.last_mut() {
254            last.push(row);
255        }
256    }
257
258    groups.sort_by(|a, b| {
259        let (a_root, b_root) = (&a[0], &b[0]);
260        match order {
261            SharedSort::AmountDesc => {
262                let ka = a_root.amounts.iter().map(|x| abs_rational(x.amount)).max();
263                let kb = b_root.amounts.iter().map(|x| abs_rational(x.amount)).max();
264                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            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    });
275
276    for group in groups {
277        rows.extend(group);
278    }
279}
280
281#[cfg(test)]
282#[path = "sort_tests.rs"]
283mod 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]
288pub 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}