Lines
92.65 %
Functions
32.5 %
Branches
100 %
use finance::error::FinanceError;
use std::sync::Arc;
use askama::Template;
use axum::Json;
use axum::extract::{Query, RawQuery};
use axum::http::HeaderMap;
use axum::response::Response;
use axum::{Extension, extract::State, response::IntoResponse};
use forms::{FieldError, REPORT_CATEGORY};
use rpc::chart::{ChartOpts, chart_spec, kind_or_default};
use rpc::forms::ReportOutcome;
use server::command::BreakdownData;
use server::command::report::view::{AmountView, BreakdownPeriodView, flatten_breakdown_data};
use sqlx::types::Uuid;
use crate::form_render::render_form;
use crate::pages::forms::unprocessable_fields;
use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate, response::WebError};
use super::bookmark::content_url;
use super::category_breakdown_query::ask;
use super::invalid::report_invalid;
use super::query::Asked;
use super::{SummaryCard, chart_svg_response, wants_json};
const ACTION: &str = "/api/report/category-breakdown";
#[derive(Template)]
#[template(path = "pages/report/category_breakdown.html")]
struct CategoryBreakdownReportPage {
content_url: String,
}
pub async fn category_breakdown_report_page(RawQuery(query): RawQuery) -> impl IntoResponse {
HtmlTemplate(CategoryBreakdownReportPage {
content_url: content_url(ACTION, query.as_deref()),
})
#[template(path = "components/report/category_breakdown_table.html")]
struct CategoryBreakdownTableTemplate {
form: String,
summary: Vec<SummaryCard>,
periods: Vec<BreakdownPeriodView>,
commodity_symbols: Vec<String>,
commodity_columns: bool,
tag_name: String,
chart_kind: String,
chart_query: String,
renderer: String,
fn push_amount(dest: &mut Vec<AmountView>, a: &AmountView) {
match dest
.iter_mut()
.find(|d| d.commodity_symbol == a.commodity_symbol)
{
Some(existing) => existing.amount += a.amount,
None => dest.push(a.clone()),
/// Build summary cards for Category Breakdown: one grand-total card per
/// commodity plus cards for the first `top_n` categories in the report's
/// row order.
fn breakdown_summary(periods: &[BreakdownPeriodView], top_n: usize) -> Vec<SummaryCard> {
let mut totals: Vec<AmountView> = Vec::new();
let mut per_category: Vec<(String, bool, Vec<AmountView>)> = Vec::new();
for period in periods {
for row in &period.rows {
for a in &row.amounts {
push_amount(&mut totals, a);
match per_category
.find(|(name, _, _)| name == &row.tag_value)
Some((_, _, amts)) => {
push_amount(amts, a);
None => per_category.push((
row.tag_value.clone(),
row.is_uncategorized,
row.amounts.clone(),
)),
let mut cards: Vec<SummaryCard> = totals
.into_iter()
.map(|a| SummaryCard {
label: format!("Total ({})", a.commodity_symbol),
amounts: vec![a],
is_net: false,
highlight: true,
.collect();
for (name, is_uncat, amounts) in per_category.into_iter().take(top_n) {
let label = if is_uncat {
"(uncategorized)".to_string()
} else {
name
};
cards.push(SummaryCard {
label,
amounts,
highlight: false,
});
cards
fn collect_commodity_symbols(periods: &[BreakdownPeriodView]) -> Vec<String> {
let mut seen: Vec<String> = Vec::new();
if !seen.iter().any(|s| s == &a.commodity_symbol) {
seen.push(a.commodity_symbol.clone());
seen
fn render(asked: &Asked<BreakdownData>, errors: &[FieldError]) -> Result<String, WebError> {
render_form(
&REPORT_CATEGORY,
&asked.values,
errors,
ACTION,
&asked.references,
)
.map_err(|e| WebError::internal("Category form render failed", e))
pub async fn category_breakdown_report_table(
Query(pairs): Query<Vec<(String, String)>>,
State(_data): State<Arc<AppState>>,
Extension(jwt_auth): Extension<JWTAuthMiddleware>,
headers: HeaderMap,
) -> Result<Response, WebError> {
let asked = ask(jwt_auth.user.id, pairs).await?;
let breakdown_data = match &asked.report {
Ok(data) => data,
Err(errors) if wants_json(&headers) => {
return Err(unprocessable_fields(errors.clone()));
Err(errors) => {
return report_invalid(
&headers,
render(&asked, errors)?,
&asked.presentation.shown,
None,
);
if wants_json(&headers) {
return Ok(Json(breakdown_data).into_response());
let periods = flatten_breakdown_data(breakdown_data);
let presentation = &asked.presentation;
let chart_kind = presentation.chart.chart_kind_str();
let renderer = presentation.chart.renderer_str();
Ok(HtmlTemplate(CategoryBreakdownTableTemplate {
form: render(&asked, &[])?,
summary: breakdown_summary(&periods, 5),
commodity_symbols: collect_commodity_symbols(&periods),
periods,
commodity_columns: presentation.table.commodity_columns_enabled(),
tag_name: breakdown_data.tag_name.clone(),
chart_query: asked.chart_query(
&[("chart_kind", &chart_kind), ("renderer", &renderer)],
),
chart_kind,
renderer,
.into_response())
/// Both chart endpoints take the table endpoint's query.
async fn breakdown_chart_spec(
user_id: Uuid,
pairs: Vec<(String, String)>,
) -> Result<plotting::ChartSpec, WebError> {
let asked = ask(user_id, pairs).await?;
let data = asked.report.map_err(unprocessable_fields)?;
chart_spec(
&ReportOutcome::Breakdown(data),
&ChartOpts {
kind: kind_or_default(asked.presentation.chart.chart_kind.as_deref()),
..ChartOpts::default()
},
.map_err(|err| WebError::from(FinanceError::Report(err)))
pub async fn category_breakdown_report_chart_svg(
) -> Result<impl IntoResponse, WebError> {
let spec = breakdown_chart_spec(jwt_auth.user.id, pairs).await?;
Ok(chart_svg_response(&spec))
pub async fn category_breakdown_report_chart_json(
Ok(Json(spec))
#[cfg(test)]
#[path = "category_breakdown_tests.rs"]
mod category_breakdown_tests;