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
24pub struct SummaryCard {
28 pub label: String,
29 pub amounts: Vec<AmountView>,
30 pub is_net: bool,
31 pub highlight: bool,
32}
33
34#[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#[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 #[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 #[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#[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#[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#[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#[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
181pub 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#[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 #[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
241pub fn sort_top_level_rows(rows: &mut Vec<view::ReportRowView>, order: SharedSort) {
246 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#[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}