1use finance::error::FinanceError;
2use std::sync::Arc;
3
4use askama::Template;
5use axum::Json;
6use axum::extract::{Query, RawQuery};
7use axum::http::HeaderMap;
8use axum::response::Response;
9use axum::{Extension, extract::State, response::IntoResponse};
10use forms::{FieldError, REPORT_CATEGORY};
11use rpc::chart::{ChartOpts, chart_spec, kind_or_default};
12use rpc::forms::ReportOutcome;
13use server::command::BreakdownData;
14use server::command::report::view::{AmountView, BreakdownPeriodView, flatten_breakdown_data};
15use sqlx::types::Uuid;
16
17use crate::form_render::render_form;
18use crate::pages::forms::unprocessable_fields;
19use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate, response::WebError};
20
21use super::bookmark::content_url;
22use super::category_breakdown_query::ask;
23use super::invalid::report_invalid;
24use super::query::Asked;
25use super::{SummaryCard, chart_svg_response, wants_json};
26
27const ACTION: &str = "/api/report/category-breakdown";
28
29#[derive(Template)]
30#[template(path = "pages/report/category_breakdown.html")]
31struct CategoryBreakdownReportPage {
32 content_url: String,
33}
34
35pub async fn category_breakdown_report_page(RawQuery(query): RawQuery) -> impl IntoResponse {
36 HtmlTemplate(CategoryBreakdownReportPage {
37 content_url: content_url(ACTION, query.as_deref()),
38 })
39}
40
41#[derive(Template)]
42#[template(path = "components/report/category_breakdown_table.html")]
43struct CategoryBreakdownTableTemplate {
44 form: String,
45 summary: Vec<SummaryCard>,
46 periods: Vec<BreakdownPeriodView>,
47 commodity_symbols: Vec<String>,
48 commodity_columns: bool,
49 tag_name: String,
50 chart_kind: String,
51 chart_query: String,
52 renderer: String,
53}
54
55fn push_amount(dest: &mut Vec<AmountView>, a: &AmountView) {
56 match dest
57 .iter_mut()
58 .find(|d| d.commodity_symbol == a.commodity_symbol)
59 {
60 Some(existing) => existing.amount += a.amount,
61 None => dest.push(a.clone()),
62 }
63}
64
65fn breakdown_summary(periods: &[BreakdownPeriodView], top_n: usize) -> Vec<SummaryCard> {
69 let mut totals: Vec<AmountView> = Vec::new();
70 let mut per_category: Vec<(String, bool, Vec<AmountView>)> = Vec::new();
71
72 for period in periods {
73 for row in &period.rows {
74 for a in &row.amounts {
75 push_amount(&mut totals, a);
76 }
77 match per_category
78 .iter_mut()
79 .find(|(name, _, _)| name == &row.tag_value)
80 {
81 Some((_, _, amts)) => {
82 for a in &row.amounts {
83 push_amount(amts, a);
84 }
85 }
86 None => per_category.push((
87 row.tag_value.clone(),
88 row.is_uncategorized,
89 row.amounts.clone(),
90 )),
91 }
92 }
93 }
94
95 let mut cards: Vec<SummaryCard> = totals
96 .into_iter()
97 .map(|a| SummaryCard {
98 label: format!("Total ({})", a.commodity_symbol),
99 amounts: vec![a],
100 is_net: false,
101 highlight: true,
102 })
103 .collect();
104
105 for (name, is_uncat, amounts) in per_category.into_iter().take(top_n) {
106 let label = if is_uncat {
107 "(uncategorized)".to_string()
108 } else {
109 name
110 };
111 cards.push(SummaryCard {
112 label,
113 amounts,
114 is_net: false,
115 highlight: false,
116 });
117 }
118 cards
119}
120
121fn collect_commodity_symbols(periods: &[BreakdownPeriodView]) -> Vec<String> {
122 let mut seen: Vec<String> = Vec::new();
123 for period in periods {
124 for row in &period.rows {
125 for a in &row.amounts {
126 if !seen.iter().any(|s| s == &a.commodity_symbol) {
127 seen.push(a.commodity_symbol.clone());
128 }
129 }
130 }
131 }
132 seen
133}
134
135fn render(asked: &Asked<BreakdownData>, errors: &[FieldError]) -> Result<String, WebError> {
136 render_form(
137 &REPORT_CATEGORY,
138 &asked.values,
139 errors,
140 ACTION,
141 &asked.references,
142 )
143 .map_err(|e| WebError::internal("Category form render failed", e))
144}
145
146pub async fn category_breakdown_report_table(
147 Query(pairs): Query<Vec<(String, String)>>,
148 State(_data): State<Arc<AppState>>,
149 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
150 headers: HeaderMap,
151) -> Result<Response, WebError> {
152 let asked = ask(jwt_auth.user.id, pairs).await?;
153 let breakdown_data = match &asked.report {
154 Ok(data) => data,
155 Err(errors) if wants_json(&headers) => {
156 return Err(unprocessable_fields(errors.clone()));
157 }
158 Err(errors) => {
159 return report_invalid(
160 &headers,
161 &REPORT_CATEGORY,
162 render(&asked, errors)?,
163 &asked.presentation.shown,
164 None,
165 );
166 }
167 };
168 if wants_json(&headers) {
169 return Ok(Json(breakdown_data).into_response());
170 }
171
172 let periods = flatten_breakdown_data(breakdown_data);
173 let presentation = &asked.presentation;
174 let chart_kind = presentation.chart.chart_kind_str();
175 let renderer = presentation.chart.renderer_str();
176
177 Ok(HtmlTemplate(CategoryBreakdownTableTemplate {
178 form: render(&asked, &[])?,
179 summary: breakdown_summary(&periods, 5),
180 commodity_symbols: collect_commodity_symbols(&periods),
181 periods,
182 commodity_columns: presentation.table.commodity_columns_enabled(),
183 tag_name: breakdown_data.tag_name.clone(),
184 chart_query: asked.chart_query(
185 &REPORT_CATEGORY,
186 &[("chart_kind", &chart_kind), ("renderer", &renderer)],
187 ),
188 chart_kind,
189 renderer,
190 })
191 .into_response())
192}
193
194async fn breakdown_chart_spec(
196 user_id: Uuid,
197 pairs: Vec<(String, String)>,
198) -> Result<plotting::ChartSpec, WebError> {
199 let asked = ask(user_id, pairs).await?;
200 let data = asked.report.map_err(unprocessable_fields)?;
201 chart_spec(
202 &ReportOutcome::Breakdown(data),
203 &ChartOpts {
204 kind: kind_or_default(asked.presentation.chart.chart_kind.as_deref()),
205 ..ChartOpts::default()
206 },
207 )
208 .map_err(|err| WebError::from(FinanceError::Report(err)))
209}
210
211pub async fn category_breakdown_report_chart_svg(
212 Query(pairs): Query<Vec<(String, String)>>,
213 State(_data): State<Arc<AppState>>,
214 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
215) -> Result<impl IntoResponse, WebError> {
216 let spec = breakdown_chart_spec(jwt_auth.user.id, pairs).await?;
217 Ok(chart_svg_response(&spec))
218}
219
220pub async fn category_breakdown_report_chart_json(
221 Query(pairs): Query<Vec<(String, String)>>,
222 State(_data): State<Arc<AppState>>,
223 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
224) -> Result<impl IntoResponse, WebError> {
225 let spec = breakdown_chart_spec(jwt_auth.user.id, pairs).await?;
226 Ok(Json(spec))
227}
228
229#[cfg(test)]
230#[path = "category_breakdown_tests.rs"]
231mod category_breakdown_tests;