Lines
94.74 %
Functions
19.23 %
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::{Field, FieldError, Form, REPORT_ACTIVITY};
use rpc::chart::{ChartOpts, chart_spec, kind_or_default, series_includes_net};
use rpc::forms::ReportOutcome;
use server::command::ActivityData;
use server::command::report::view::{AmountView, PeriodActivityView, flatten_activity_data};
use sqlx::types::Uuid;
use crate::form_render::{render_form, without};
use crate::pages::forms::unprocessable_fields;
use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate, response::WebError};
use super::activity_groups::{GroupRow, GroupsEditor, group_rows, is_marked};
use super::activity_query::ask;
use super::bookmark::content_url;
use super::invalid::report_invalid;
use super::query::Asked;
use super::{SummaryCard, chart_svg_response, wants_json};
const ACTION: &str = "/api/report/activity";
/// The form without its `groups` rows, which the groups editor beside it writes.
const SHOWN_FIELDS: [Field; 5] = without(&REPORT_ACTIVITY, "groups");
const SHOWN: Form = Form {
fields: &SHOWN_FIELDS,
..REPORT_ACTIVITY
};
#[derive(Template)]
#[template(path = "pages/report/activity.html")]
struct ActivityReportPage {
content_url: String,
}
pub async fn activity_report_page(RawQuery(query): RawQuery) -> impl IntoResponse {
HtmlTemplate(ActivityReportPage {
content_url: content_url(ACTION, query.as_deref()),
})
#[template(path = "components/report/activity_table.html")]
struct ActivityTableTemplate {
form: String,
summary: Vec<SummaryCard>,
periods: Vec<PeriodActivityView>,
commodity_symbols: Vec<String>,
commodity_columns: bool,
sortable: bool,
collapsible: bool,
collapsed_depth: Option<String>,
editor: String,
blank: GroupRow,
chart_kind: String,
chart_query: String,
renderer: String,
/// Collect the set of commodity symbols referenced anywhere in the
/// activity result, in insertion order. Used to drive the
/// "Commodities as columns" pivot.
fn collect_commodity_symbols(periods: &[PeriodActivityView]) -> Vec<String> {
let mut seen: Vec<String> = Vec::new();
let mut push = |sym: &str| {
if !seen.iter().any(|s| s == sym) {
seen.push(sym.to_string());
for period in periods {
for group in &period.groups {
for row in &group.rows {
for a in &row.amounts {
push(&a.commodity_symbol);
seen
fn add_amounts(dest: &mut Vec<AmountView>, src: &[AmountView]) {
for a in src {
match dest
.iter_mut()
.find(|d| d.commodity_symbol == a.commodity_symbol)
{
Some(existing) => existing.amount += a.amount,
None => dest.push(AmountView {
commodity_symbol: a.commodity_symbol.clone(),
amount: a.amount,
}),
/// Build summary cards for Activity: one card per group label summing its
/// group-total across every period, plus a final net card combining per-
/// period nets. Server values are already `flip_sign`-applied by the view
/// flattener, so this is a straightforward cross-period sum.
fn activity_summary(periods: &[PeriodActivityView]) -> Vec<SummaryCard> {
let mut labeled: Vec<(String, bool, Vec<AmountView>)> = Vec::new();
let mut net: Vec<AmountView> = Vec::new();
match labeled
.find(|(label, _, _)| label == &group.label)
Some((_, _, totals)) => add_amounts(totals, &group.total),
None => labeled.push((group.label.clone(), group.flip_sign, group.total.clone())),
add_amounts(&mut net, &period.net);
let mut cards: Vec<SummaryCard> = labeled
.into_iter()
.map(|(label, highlight, amounts)| SummaryCard {
label,
amounts,
is_net: false,
highlight,
.collect();
if !net.is_empty() {
cards.push(SummaryCard {
label: "Net".to_string(),
amounts: net,
is_net: true,
highlight: false,
});
cards
/// The editor beside the form shows the errors of the group rows, so the
/// form's banner must not repeat them under their raw addresses.
fn render(asked: &Asked<ActivityData>, errors: &[FieldError]) -> Result<String, WebError> {
let own: Vec<FieldError> = errors
.iter()
.filter(|error| !is_marked(&asked.values, error))
.cloned()
render_form(&SHOWN, &asked.values, &own, ACTION, &asked.references)
.map_err(|e| WebError::internal("Activity form render failed", e))
fn editor(
asked: &Asked<ActivityData>,
errors: &[FieldError],
oob: bool,
) -> Result<String, WebError> {
GroupsEditor {
groups: group_rows(&asked.values, errors),
oob,
.render()
.map_err(|e| WebError::internal("Groups editor render failed", e))
pub async fn activity_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 activity_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,
&SHOWN,
render(&asked, errors)?,
&asked.presentation.shown,
Some(&|oob| editor(&asked, errors, oob)),
);
if wants_json(&headers) {
return Ok(Json(activity_data).into_response());
let periods = flatten_activity_data(activity_data)
.map_err(|err| WebError::from(FinanceError::Report(err)))?;
let presentation = &asked.presentation;
let chart_kind = presentation.chart.chart_kind_str();
let renderer = presentation.chart.renderer_str();
Ok(HtmlTemplate(ActivityTableTemplate {
form: render(&asked, &[])?,
summary: activity_summary(&periods),
commodity_symbols: collect_commodity_symbols(&periods),
periods,
commodity_columns: presentation.table.commodity_columns_enabled(),
sortable: true,
collapsible: true,
collapsed_depth: presentation.table.collapsed_depth.clone(),
editor: editor(&asked, &[], false)?,
blank: GroupRow::default(),
chart_query: asked.chart_query(
&REPORT_ACTIVITY,
&[("chart_kind", &chart_kind), ("renderer", &renderer)],
),
chart_kind,
renderer,
.into_response())
/// Both chart endpoints take the table endpoint's query.
async fn activity_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)?;
let chart = &asked.presentation.chart;
chart_spec(
&ReportOutcome::Activity(data),
&ChartOpts {
kind: kind_or_default(chart.chart_kind.as_deref()),
include_net: series_includes_net(chart.chart_series.as_deref()),
..ChartOpts::default()
},
)
.map_err(|err| WebError::from(FinanceError::Report(err)))
pub async fn activity_report_chart_svg(
) -> Result<impl IntoResponse, WebError> {
let spec = activity_chart_spec(jwt_auth.user.id, pairs).await?;
Ok(chart_svg_response(&spec))
pub async fn activity_report_chart_json(
Ok(Json(spec))
#[cfg(test)]
#[path = "activity_tests.rs"]
mod tests;