Skip to main content

web/pages/report/
activity.rs

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::{Field, FieldError, Form, REPORT_ACTIVITY};
11use rpc::chart::{ChartOpts, chart_spec, kind_or_default, series_includes_net};
12use rpc::forms::ReportOutcome;
13use server::command::ActivityData;
14use server::command::report::view::{AmountView, PeriodActivityView, flatten_activity_data};
15use sqlx::types::Uuid;
16
17use crate::form_render::{render_form, without};
18use crate::pages::forms::unprocessable_fields;
19use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate, response::WebError};
20
21use super::activity_groups::{GroupRow, GroupsEditor, group_rows, is_marked};
22use super::activity_query::ask;
23use super::bookmark::content_url;
24use super::invalid::report_invalid;
25use super::query::Asked;
26use super::{SummaryCard, chart_svg_response, wants_json};
27
28const ACTION: &str = "/api/report/activity";
29
30/// The form without its `groups` rows, which the groups editor beside it writes.
31const SHOWN_FIELDS: [Field; 5] = without(&REPORT_ACTIVITY, "groups");
32const SHOWN: Form = Form {
33    fields: &SHOWN_FIELDS,
34    ..REPORT_ACTIVITY
35};
36
37#[derive(Template)]
38#[template(path = "pages/report/activity.html")]
39struct ActivityReportPage {
40    content_url: String,
41}
42
43pub async fn activity_report_page(RawQuery(query): RawQuery) -> impl IntoResponse {
44    HtmlTemplate(ActivityReportPage {
45        content_url: content_url(ACTION, query.as_deref()),
46    })
47}
48
49#[derive(Template)]
50#[template(path = "components/report/activity_table.html")]
51struct ActivityTableTemplate {
52    form: String,
53    summary: Vec<SummaryCard>,
54    periods: Vec<PeriodActivityView>,
55    commodity_symbols: Vec<String>,
56    commodity_columns: bool,
57    sortable: bool,
58    collapsible: bool,
59    collapsed_depth: Option<String>,
60    editor: String,
61    blank: GroupRow,
62    chart_kind: String,
63    chart_query: String,
64    renderer: String,
65}
66
67/// Collect the set of commodity symbols referenced anywhere in the
68/// activity result, in insertion order. Used to drive the
69/// "Commodities as columns" pivot.
70fn collect_commodity_symbols(periods: &[PeriodActivityView]) -> Vec<String> {
71    let mut seen: Vec<String> = Vec::new();
72    let mut push = |sym: &str| {
73        if !seen.iter().any(|s| s == sym) {
74            seen.push(sym.to_string());
75        }
76    };
77    for period in periods {
78        for group in &period.groups {
79            for row in &group.rows {
80                for a in &row.amounts {
81                    push(&a.commodity_symbol);
82                }
83            }
84        }
85    }
86    seen
87}
88
89fn add_amounts(dest: &mut Vec<AmountView>, src: &[AmountView]) {
90    for a in src {
91        match dest
92            .iter_mut()
93            .find(|d| d.commodity_symbol == a.commodity_symbol)
94        {
95            Some(existing) => existing.amount += a.amount,
96            None => dest.push(AmountView {
97                commodity_symbol: a.commodity_symbol.clone(),
98                amount: a.amount,
99            }),
100        }
101    }
102}
103
104/// Build summary cards for Activity: one card per group label summing its
105/// group-total across every period, plus a final net card combining per-
106/// period nets. Server values are already `flip_sign`-applied by the view
107/// flattener, so this is a straightforward cross-period sum.
108fn activity_summary(periods: &[PeriodActivityView]) -> Vec<SummaryCard> {
109    let mut labeled: Vec<(String, bool, Vec<AmountView>)> = Vec::new();
110    let mut net: Vec<AmountView> = Vec::new();
111
112    for period in periods {
113        for group in &period.groups {
114            match labeled
115                .iter_mut()
116                .find(|(label, _, _)| label == &group.label)
117            {
118                Some((_, _, totals)) => add_amounts(totals, &group.total),
119                None => labeled.push((group.label.clone(), group.flip_sign, group.total.clone())),
120            }
121        }
122        add_amounts(&mut net, &period.net);
123    }
124
125    let mut cards: Vec<SummaryCard> = labeled
126        .into_iter()
127        .map(|(label, highlight, amounts)| SummaryCard {
128            label,
129            amounts,
130            is_net: false,
131            highlight,
132        })
133        .collect();
134
135    if !net.is_empty() {
136        cards.push(SummaryCard {
137            label: "Net".to_string(),
138            amounts: net,
139            is_net: true,
140            highlight: false,
141        });
142    }
143    cards
144}
145
146/// The editor beside the form shows the errors of the group rows, so the
147/// form's banner must not repeat them under their raw addresses.
148fn render(asked: &Asked<ActivityData>, errors: &[FieldError]) -> Result<String, WebError> {
149    let own: Vec<FieldError> = errors
150        .iter()
151        .filter(|error| !is_marked(&asked.values, error))
152        .cloned()
153        .collect();
154    render_form(&SHOWN, &asked.values, &own, ACTION, &asked.references)
155        .map_err(|e| WebError::internal("Activity form render failed", e))
156}
157
158fn editor(
159    asked: &Asked<ActivityData>,
160    errors: &[FieldError],
161    oob: bool,
162) -> Result<String, WebError> {
163    GroupsEditor {
164        groups: group_rows(&asked.values, errors),
165        oob,
166    }
167    .render()
168    .map_err(|e| WebError::internal("Groups editor render failed", e))
169}
170
171pub async fn activity_report_table(
172    Query(pairs): Query<Vec<(String, String)>>,
173    State(_data): State<Arc<AppState>>,
174    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
175    headers: HeaderMap,
176) -> Result<Response, WebError> {
177    let asked = ask(jwt_auth.user.id, pairs).await?;
178    let activity_data = match &asked.report {
179        Ok(data) => data,
180        Err(errors) if wants_json(&headers) => {
181            return Err(unprocessable_fields(errors.clone()));
182        }
183        Err(errors) => {
184            return report_invalid(
185                &headers,
186                &SHOWN,
187                render(&asked, errors)?,
188                &asked.presentation.shown,
189                Some(&|oob| editor(&asked, errors, oob)),
190            );
191        }
192    };
193    if wants_json(&headers) {
194        return Ok(Json(activity_data).into_response());
195    }
196
197    let periods = flatten_activity_data(activity_data)
198        .map_err(|err| WebError::from(FinanceError::Report(err)))?;
199    let presentation = &asked.presentation;
200    let chart_kind = presentation.chart.chart_kind_str();
201    let renderer = presentation.chart.renderer_str();
202
203    Ok(HtmlTemplate(ActivityTableTemplate {
204        form: render(&asked, &[])?,
205        summary: activity_summary(&periods),
206        commodity_symbols: collect_commodity_symbols(&periods),
207        periods,
208        commodity_columns: presentation.table.commodity_columns_enabled(),
209        sortable: true,
210        collapsible: true,
211        collapsed_depth: presentation.table.collapsed_depth.clone(),
212        editor: editor(&asked, &[], false)?,
213        blank: GroupRow::default(),
214        chart_query: asked.chart_query(
215            &REPORT_ACTIVITY,
216            &[("chart_kind", &chart_kind), ("renderer", &renderer)],
217        ),
218        chart_kind,
219        renderer,
220    })
221    .into_response())
222}
223
224/// Both chart endpoints take the table endpoint's query.
225async fn activity_chart_spec(
226    user_id: Uuid,
227    pairs: Vec<(String, String)>,
228) -> Result<plotting::ChartSpec, WebError> {
229    let asked = ask(user_id, pairs).await?;
230    let data = asked.report.map_err(unprocessable_fields)?;
231    let chart = &asked.presentation.chart;
232    chart_spec(
233        &ReportOutcome::Activity(data),
234        &ChartOpts {
235            kind: kind_or_default(chart.chart_kind.as_deref()),
236            include_net: series_includes_net(chart.chart_series.as_deref()),
237            ..ChartOpts::default()
238        },
239    )
240    .map_err(|err| WebError::from(FinanceError::Report(err)))
241}
242
243pub async fn activity_report_chart_svg(
244    Query(pairs): Query<Vec<(String, String)>>,
245    State(_data): State<Arc<AppState>>,
246    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
247) -> Result<impl IntoResponse, WebError> {
248    let spec = activity_chart_spec(jwt_auth.user.id, pairs).await?;
249    Ok(chart_svg_response(&spec))
250}
251
252pub async fn activity_report_chart_json(
253    Query(pairs): Query<Vec<(String, String)>>,
254    State(_data): State<Arc<AppState>>,
255    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
256) -> Result<impl IntoResponse, WebError> {
257    let spec = activity_chart_spec(jwt_auth.user.id, pairs).await?;
258    Ok(Json(spec))
259}
260
261#[cfg(test)]
262#[path = "activity_tests.rs"]
263mod tests;