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_BALANCE};
11use server::command::ReportData;
12use server::command::report::view::{AmountView, ReportRowView, flatten_report_data};
13use sqlx::types::Uuid;
14
15use crate::form_render::render_form;
16use crate::pages::forms::unprocessable_fields;
17use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate, response::WebError};
18
19use super::balance_query::ask;
20use super::bookmark::content_url;
21use super::invalid::report_invalid;
22use super::query::Asked;
23use super::{
24 SummaryCard, chart_svg_response, commodity_symbols_in_rows, parse_sort_order_shared,
25 sort_top_level_rows, sum_top_level_amounts, wants_json,
26};
27use rpc::chart::{ChartOpts, chart_spec, kind_or_default};
28use rpc::forms::ReportOutcome;
29
30const ACTION: &str = "/api/report/balance";
31
32#[derive(Template)]
33#[template(path = "pages/report/balance.html")]
34struct BalanceReportPage {
35 content_url: String,
36}
37
38pub async fn balance_report_page(RawQuery(query): RawQuery) -> impl IntoResponse {
39 HtmlTemplate(BalanceReportPage {
40 content_url: content_url(ACTION, query.as_deref()),
41 })
42}
43
44#[derive(Template)]
45#[template(path = "components/report/balance_table.html")]
46struct BalanceTableTemplate {
47 form: String,
48 summary: Vec<SummaryCard>,
49 rows: Vec<ReportRowView>,
50 commodity_symbols: Vec<String>,
51 commodity_columns: bool,
52 sortable: bool,
53 collapsible: bool,
54 collapsed_depth: Option<String>,
55 sort_order: String,
56 chart_kind: String,
57 chart_query: String,
58 renderer: String,
59}
60
61fn balance_summary(rows: &[ReportRowView]) -> Vec<SummaryCard> {
62 sum_top_level_amounts(rows)
63 .into_iter()
64 .map(|a| SummaryCard {
65 label: format!("Total ({})", a.commodity_symbol),
66 amounts: vec![AmountView {
67 commodity_symbol: a.commodity_symbol,
68 amount: a.amount,
69 }],
70 is_net: false,
71 highlight: false,
72 })
73 .collect()
74}
75
76fn render(asked: &Asked<ReportData>, errors: &[FieldError]) -> Result<String, WebError> {
77 render_form(
78 &REPORT_BALANCE,
79 &asked.values,
80 errors,
81 ACTION,
82 &asked.references,
83 )
84 .map_err(|e| WebError::internal("Balance form render failed", e))
85}
86
87pub async fn balance_report_table(
88 Query(pairs): Query<Vec<(String, String)>>,
89 State(_data): State<Arc<AppState>>,
90 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
91 headers: HeaderMap,
92) -> Result<Response, WebError> {
93 let asked = ask(jwt_auth.user.id, pairs).await?;
94 let report_data = match &asked.report {
95 Ok(data) => data,
96 Err(errors) if wants_json(&headers) => {
97 return Err(unprocessable_fields(errors.clone()));
98 }
99 Err(errors) => {
100 return report_invalid(
101 &headers,
102 &REPORT_BALANCE,
103 render(&asked, errors)?,
104 &asked.presentation.shown,
105 None,
106 );
107 }
108 };
109 if wants_json(&headers) {
110 return Ok(Json(report_data).into_response());
111 }
112
113 let mut rows = flatten_report_data(report_data);
114 let presentation = &asked.presentation;
115 let sort_order = parse_sort_order_shared(presentation.sort_order.as_deref());
116 sort_top_level_rows(&mut rows, sort_order);
117 let summary = balance_summary(&rows);
118 let commodity_symbols = commodity_symbols_in_rows(&rows);
119 let chart_kind = presentation.chart.chart_kind_str();
120 let renderer = presentation.chart.renderer_str();
121 let sort_order_str = sort_order.to_str().to_string();
122
123 Ok(HtmlTemplate(BalanceTableTemplate {
124 form: render(&asked, &[])?,
125 summary,
126 rows,
127 commodity_symbols,
128 commodity_columns: presentation.table.commodity_columns_enabled(),
129 sortable: true,
130 collapsible: true,
131 collapsed_depth: presentation.table.collapsed_depth.clone(),
132 chart_query: asked.chart_query(
133 &REPORT_BALANCE,
134 &[
135 ("chart_kind", &chart_kind),
136 ("renderer", &renderer),
137 ("sort_order", &sort_order_str),
138 ],
139 ),
140 sort_order: sort_order_str,
141 chart_kind,
142 renderer,
143 })
144 .into_response())
145}
146
147async fn balance_chart_spec(
150 user_id: Uuid,
151 pairs: Vec<(String, String)>,
152) -> Result<plotting::ChartSpec, WebError> {
153 let asked = ask(user_id, pairs).await?;
154 let report_data = asked.report.map_err(unprocessable_fields)?;
155 let sort_order = parse_sort_order_shared(asked.presentation.sort_order.as_deref());
156 chart_spec(
157 &ReportOutcome::Balance(report_data),
158 &ChartOpts {
159 kind: kind_or_default(asked.presentation.chart.chart_kind.as_deref()),
160 sort: sort_order.into_plotting_balance(),
161 ..ChartOpts::default()
162 },
163 )
164 .map_err(|err| WebError::from(FinanceError::Report(err)))
165}
166
167pub async fn balance_report_chart_svg(
168 Query(pairs): Query<Vec<(String, String)>>,
169 State(_data): State<Arc<AppState>>,
170 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
171) -> Result<impl IntoResponse, WebError> {
172 let spec = balance_chart_spec(jwt_auth.user.id, pairs).await?;
173 Ok(chart_svg_response(&spec))
174}
175
176pub async fn balance_report_chart_json(
177 Query(pairs): Query<Vec<(String, String)>>,
178 State(_data): State<Arc<AppState>>,
179 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
180) -> Result<impl IntoResponse, WebError> {
181 let spec = balance_chart_spec(jwt_auth.user.id, pairs).await?;
182 Ok(Json(spec))
183}