Lines
70.29 %
Functions
20.16 %
Branches
100 %
use axum::http::{HeaderMap, StatusCode, header::CONTENT_TYPE};
use axum::response::{IntoResponse, Response};
use num_rational::Rational64;
use rpc::chart::{
DEFAULT_HEIGHT, DEFAULT_WIDTH, SortOrder, kind_name, kind_or_default, render_svg_chart,
};
pub mod activity;
pub mod activity_groups;
pub mod activity_query;
pub mod balance;
pub mod balance_query;
pub mod bookmark;
pub mod category_breakdown;
pub mod category_breakdown_csv;
pub mod category_breakdown_query;
pub mod invalid;
pub mod query;
pub mod retired;
use server::command::report::view;
use view::AmountView;
/// A single card in the top-of-report summary strip. `is_net` flags cards
/// that show a signed net (e.g. Income − Expense) so templates can
/// style them distinctly; `highlight` is a generic accent slot.
pub struct SummaryCard {
pub label: String,
pub amounts: Vec<AmountView>,
pub is_net: bool,
pub highlight: bool,
}
/// Query-string fields shared by every report page to drive client-side
/// table controls. The server only needs to read `commodity_columns` (which
/// drives a template pivot) and forward `collapsed_depth` into the template
/// for initial fold state; `sort_by` is consumed purely by the frontend
/// WASM reorder logic, so the Rust handler does not parse it.
#[derive(Default)]
pub struct TableControlParams {
pub collapsed_depth: Option<String>,
pub commodity_columns: Option<String>,
impl TableControlParams {
#[must_use]
pub fn commodity_columns_enabled(&self) -> bool {
self.commodity_columns
.as_deref()
.map(str::trim)
.is_some_and(|v| v.eq_ignore_ascii_case("on") || v.eq_ignore_ascii_case("true"))
/// Chart-specific query parameters shared across report chart handlers.
/// `chart_kind` maps to `rpc::chart::kind_or_default`; `chart_series` is a
/// report-specific toggle (e.g. Activity: show Net or not) parsed in
/// each handler. `renderer` picks between server-side SVG (default)
/// and client-side canvas.
pub struct ChartParams {
pub chart_kind: Option<String>,
pub chart_series: Option<String>,
pub renderer: Option<String>,
impl ChartParams {
/// Normalise the chart kind to its canonical lowercase name so
/// the template can round-trip it into URLs and `<select>`
/// values.
pub fn chart_kind_str(&self) -> String {
kind_name(kind_or_default(self.chart_kind.as_deref())).to_string()
/// Canonicalise the renderer choice. Accepts `svg` (default) and
/// `canvas`; anything else normalises to `svg`.
pub fn renderer_str(&self) -> String {
match self.renderer.as_deref().map(str::to_ascii_lowercase) {
Some(ref s) if s == "canvas" => "canvas".to_string(),
_ => "svg".to_string(),
/// Minimal URL-query encoder for the (key, value) pairs the chart
/// endpoints take. Avoids pulling in `serde_urlencoded` just to
/// stringify a handful of params — keeps the handler simple.
pub fn encode_query(pairs: &[(&str, &str)]) -> String {
let mut out = String::new();
for (k, v) in pairs {
if v.is_empty() {
continue;
if !out.is_empty() {
out.push('&');
out.push_str(&percent_encode(k));
out.push('=');
out.push_str(&percent_encode(v));
if out.is_empty() {
out
} else {
format!("?{out}")
fn percent_encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
let keep = b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~');
if keep {
out.push(b as char);
out.push_str(&format!("%{b:02X}"));
pub fn wants_json(headers: &HeaderMap) -> bool {
headers
.get("accept")
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.contains("application/json"))
/// Sum top-level rows' amounts per commodity. Used by Balance to build its
/// grand-total card(s).
pub fn sum_top_level_amounts(rows: &[view::ReportRowView]) -> Vec<AmountView> {
let mut out: Vec<AmountView> = Vec::new();
for row in rows.iter().filter(|r| r.depth == 0) {
for a in &row.amounts {
match out
.iter_mut()
.find(|x| x.commodity_symbol == a.commodity_symbol)
{
Some(existing) => existing.amount += a.amount,
None => out.push(AmountView {
commodity_symbol: a.commodity_symbol.clone(),
amount: a.amount,
}),
/// Collect the set of commodity symbols present across all rows, in the
/// order the row-data first mentions them. Drives the "Commodities as
/// columns" pivot: a stable column ordering without depending on the
/// user's commodity list.
pub fn commodity_symbols_in_rows(rows: &[view::ReportRowView]) -> Vec<String> {
let mut seen = Vec::new();
for row in rows {
if !seen.iter().any(|s: &String| s == &a.commodity_symbol) {
seen.push(a.commodity_symbol.clone());
seen
/// Look up a row's amount for the given commodity symbol. Called from the
/// commodity-columns branch of the tree-table template.
pub fn row_amount_by_symbol(row: &view::ReportRowView, symbol: &str) -> Option<Rational64> {
row.amounts
.iter()
.find(|a| a.commodity_symbol == symbol)
.map(|a| a.amount)
/// The chart endpoints answer the SVG the spec draws.
pub fn chart_svg_response(spec: &plotting::ChartSpec) -> Response {
(
StatusCode::OK,
[(CONTENT_TYPE, "image/svg+xml")],
render_svg_chart(spec, DEFAULT_WIDTH, DEFAULT_HEIGHT),
)
.into_response()
/// Parse the shared `sort_order` query param. Balance and Breakdown
/// accept the same names; this keeps the URLs consistent between
/// them. Unknown values fall back to `AmountDesc` so a stale URL
/// still renders.
pub fn parse_sort_order_shared(raw: Option<&str>) -> SharedSort {
match raw.map(str::to_ascii_lowercase).as_deref() {
Some("amount_asc") => SharedSort::AmountAsc,
Some("name_asc") => SharedSort::NameAsc,
Some("name_desc") => SharedSort::NameDesc,
_ => SharedSort::AmountDesc,
#[derive(Debug, Clone, Copy, Default)]
pub enum SharedSort {
#[default]
AmountDesc,
AmountAsc,
NameAsc,
NameDesc,
impl SharedSort {
pub fn to_str(self) -> &'static str {
match self {
Self::AmountDesc => "amount_desc",
Self::AmountAsc => "amount_asc",
Self::NameAsc => "name_asc",
Self::NameDesc => "name_desc",
/// Map to the plotting crate's balance-chart sort enum.
pub fn into_plotting_balance(self) -> SortOrder {
Self::AmountDesc => SortOrder::MagnitudeDesc,
Self::AmountAsc => SortOrder::MagnitudeAsc,
Self::NameAsc => SortOrder::NameAsc,
Self::NameDesc => SortOrder::NameDesc,
fn abs_rational(r: Rational64) -> Rational64 {
if r < Rational64::new(0, 1) { -r } else { r }
/// Sort top-level rows in place according to `order`. Children ride
/// with their parent — they're adjacent in the flattened view and we
/// preserve that adjacency by sorting on a key derived from each
/// top-level row alone.
pub fn sort_top_level_rows(rows: &mut Vec<view::ReportRowView>, order: SharedSort) {
// Group rows by their top-level ancestor. Flat projection is DFS
// order: every depth-0 row is followed by its subtree before the
// next depth-0 row, so a single pass builds the groups.
let mut groups: Vec<Vec<view::ReportRowView>> = Vec::new();
for row in std::mem::take(rows) {
if row.depth == 0 || groups.is_empty() {
groups.push(vec![row]);
} else if let Some(last) = groups.last_mut() {
last.push(row);
groups.sort_by(|a, b| {
let (a_root, b_root) = (&a[0], &b[0]);
match order {
SharedSort::AmountDesc => {
let ka = a_root.amounts.iter().map(|x| abs_rational(x.amount)).max();
let kb = b_root.amounts.iter().map(|x| abs_rational(x.amount)).max();
kb.cmp(&ka)
SharedSort::AmountAsc => {
ka.cmp(&kb)
SharedSort::NameAsc => a_root.account_name.cmp(&b_root.account_name),
SharedSort::NameDesc => b_root.account_name.cmp(&a_root.account_name),
});
for group in groups {
rows.extend(group);
#[cfg(test)]
#[path = "sort_tests.rs"]
mod sort_tests;
/// Breakdown equivalent of `row_amount_by_symbol`. Category Breakdown uses
/// a flat row type (`BreakdownRowView`) rather than the tree `ReportRowView`.
pub fn breakdown_row_amount_by_symbol(
row: &view::BreakdownRowView,
symbol: &str,
) -> Option<Rational64> {