1
use finance::error::FinanceError;
2
use std::sync::Arc;
3

            
4
use askama::Template;
5
use axum::Json;
6
use axum::extract::{Query, RawQuery};
7
use axum::http::HeaderMap;
8
use axum::response::Response;
9
use axum::{Extension, extract::State, response::IntoResponse};
10
use forms::{Field, FieldError, Form, REPORT_ACTIVITY};
11
use rpc::chart::{ChartOpts, chart_spec, kind_or_default, series_includes_net};
12
use rpc::forms::ReportOutcome;
13
use server::command::ActivityData;
14
use server::command::report::view::{AmountView, PeriodActivityView, flatten_activity_data};
15
use sqlx::types::Uuid;
16

            
17
use crate::form_render::{render_form, without};
18
use crate::pages::forms::unprocessable_fields;
19
use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate, response::WebError};
20

            
21
use super::activity_groups::{GroupRow, GroupsEditor, group_rows, is_marked};
22
use super::activity_query::ask;
23
use super::bookmark::content_url;
24
use super::invalid::report_invalid;
25
use super::query::Asked;
26
use super::{SummaryCard, chart_svg_response, wants_json};
27

            
28
const ACTION: &str = "/api/report/activity";
29

            
30
/// The form without its `groups` rows, which the groups editor beside it writes.
31
const SHOWN_FIELDS: [Field; 5] = without(&REPORT_ACTIVITY, "groups");
32
const SHOWN: Form = Form {
33
    fields: &SHOWN_FIELDS,
34
    ..REPORT_ACTIVITY
35
};
36

            
37
#[derive(Template)]
38
#[template(path = "pages/report/activity.html")]
39
struct ActivityReportPage {
40
    content_url: String,
41
}
42

            
43
4
pub async fn activity_report_page(RawQuery(query): RawQuery) -> impl IntoResponse {
44
4
    HtmlTemplate(ActivityReportPage {
45
4
        content_url: content_url(ACTION, query.as_deref()),
46
4
    })
47
4
}
48

            
49
#[derive(Template)]
50
#[template(path = "components/report/activity_table.html")]
51
struct 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.
70
7
fn collect_commodity_symbols(periods: &[PeriodActivityView]) -> Vec<String> {
71
7
    let mut seen: Vec<String> = Vec::new();
72
1
    let mut push = |sym: &str| {
73
1
        if !seen.iter().any(|s| s == sym) {
74
1
            seen.push(sym.to_string());
75
        }
76
1
    };
77
7
    for period in periods {
78
7
        for group in &period.groups {
79
13
            for row in &group.rows {
80
1
                for a in &row.amounts {
81
1
                    push(&a.commodity_symbol);
82
                }
83
            }
84
        }
85
    }
86
7
    seen
87
7
}
88

            
89
7
fn add_amounts(dest: &mut Vec<AmountView>, src: &[AmountView]) {
90
7
    for a in src {
91
1
        match dest
92
1
            .iter_mut()
93
            .find(|d| d.commodity_symbol == a.commodity_symbol)
94
        {
95
            Some(existing) => existing.amount += a.amount,
96
1
            None => dest.push(AmountView {
97
1
                commodity_symbol: a.commodity_symbol.clone(),
98
1
                amount: a.amount,
99
1
            }),
100
        }
101
    }
102
7
}
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.
108
7
fn activity_summary(periods: &[PeriodActivityView]) -> Vec<SummaryCard> {
109
7
    let mut labeled: Vec<(String, bool, Vec<AmountView>)> = Vec::new();
110
7
    let mut net: Vec<AmountView> = Vec::new();
111

            
112
7
    for period in periods {
113
7
        for group in &period.groups {
114
13
            match labeled
115
13
                .iter_mut()
116
6
                .find(|(label, _, _)| label == &group.label)
117
            {
118
                Some((_, _, totals)) => add_amounts(totals, &group.total),
119
13
                None => labeled.push((group.label.clone(), group.flip_sign, group.total.clone())),
120
            }
121
        }
122
7
        add_amounts(&mut net, &period.net);
123
    }
124

            
125
7
    let mut cards: Vec<SummaryCard> = labeled
126
7
        .into_iter()
127
        .map(|(label, highlight, amounts)| SummaryCard {
128
13
            label,
129
13
            amounts,
130
13
            is_net: false,
131
13
            highlight,
132
13
        })
133
        .collect();
134

            
135
7
    if !net.is_empty() {
136
1
        cards.push(SummaryCard {
137
1
            label: "Net".to_string(),
138
1
            amounts: net,
139
1
            is_net: true,
140
1
            highlight: false,
141
1
        });
142
6
    }
143
7
    cards
144
7
}
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.
148
12
fn render(asked: &Asked<ActivityData>, errors: &[FieldError]) -> Result<String, WebError> {
149
12
    let own: Vec<FieldError> = errors
150
12
        .iter()
151
5
        .filter(|error| !is_marked(&asked.values, error))
152
        .cloned()
153
        .collect();
154
12
    render_form(&SHOWN, &asked.values, &own, ACTION, &asked.references)
155
        .map_err(|e| WebError::internal("Activity form render failed", e))
156
12
}
157

            
158
12
fn editor(
159
12
    asked: &Asked<ActivityData>,
160
12
    errors: &[FieldError],
161
12
    oob: bool,
162
12
) -> Result<String, WebError> {
163
12
    GroupsEditor {
164
12
        groups: group_rows(&asked.values, errors),
165
12
        oob,
166
12
    }
167
12
    .render()
168
    .map_err(|e| WebError::internal("Groups editor render failed", e))
169
12
}
170

            
171
27
pub async fn activity_report_table(
172
27
    Query(pairs): Query<Vec<(String, String)>>,
173
27
    State(_data): State<Arc<AppState>>,
174
27
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
175
27
    headers: HeaderMap,
176
27
) -> Result<Response, WebError> {
177
27
    let asked = ask(jwt_auth.user.id, pairs).await?;
178
25
    let activity_data = match &asked.report {
179
15
        Ok(data) => data,
180
10
        Err(errors) if wants_json(&headers) => {
181
5
            return Err(unprocessable_fields(errors.clone()));
182
        }
183
        Err(errors) => {
184
5
            return report_invalid(
185
5
                &headers,
186
5
                &SHOWN,
187
5
                render(&asked, errors)?,
188
5
                &asked.presentation.shown,
189
5
                Some(&|oob| editor(&asked, errors, oob)),
190
            );
191
        }
192
    };
193
15
    if wants_json(&headers) {
194
8
        return Ok(Json(activity_data).into_response());
195
7
    }
196

            
197
7
    let periods = flatten_activity_data(activity_data)
198
        .map_err(|err| WebError::from(FinanceError::Report(err)))?;
199
7
    let presentation = &asked.presentation;
200
7
    let chart_kind = presentation.chart.chart_kind_str();
201
7
    let renderer = presentation.chart.renderer_str();
202

            
203
    Ok(HtmlTemplate(ActivityTableTemplate {
204
7
        form: render(&asked, &[])?,
205
7
        summary: activity_summary(&periods),
206
7
        commodity_symbols: collect_commodity_symbols(&periods),
207
7
        periods,
208
7
        commodity_columns: presentation.table.commodity_columns_enabled(),
209
7
        sortable: true,
210
7
        collapsible: true,
211
7
        collapsed_depth: presentation.table.collapsed_depth.clone(),
212
7
        editor: editor(&asked, &[], false)?,
213
7
        blank: GroupRow::default(),
214
7
        chart_query: asked.chart_query(
215
7
            &REPORT_ACTIVITY,
216
7
            &[("chart_kind", &chart_kind), ("renderer", &renderer)],
217
7
        ),
218
7
        chart_kind,
219
7
        renderer,
220
    })
221
    .into_response())
222
27
}
223

            
224
/// Both chart endpoints take the table endpoint's query.
225
13
async fn activity_chart_spec(
226
13
    user_id: Uuid,
227
13
    pairs: Vec<(String, String)>,
228
13
) -> Result<plotting::ChartSpec, WebError> {
229
13
    let asked = ask(user_id, pairs).await?;
230
12
    let data = asked.report.map_err(unprocessable_fields)?;
231
6
    let chart = &asked.presentation.chart;
232
6
    chart_spec(
233
6
        &ReportOutcome::Activity(data),
234
6
        &ChartOpts {
235
6
            kind: kind_or_default(chart.chart_kind.as_deref()),
236
6
            include_net: series_includes_net(chart.chart_series.as_deref()),
237
6
            ..ChartOpts::default()
238
6
        },
239
6
    )
240
    .map_err(|err| WebError::from(FinanceError::Report(err)))
241
13
}
242

            
243
4
pub async fn activity_report_chart_svg(
244
4
    Query(pairs): Query<Vec<(String, String)>>,
245
4
    State(_data): State<Arc<AppState>>,
246
4
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
247
4
) -> Result<impl IntoResponse, WebError> {
248
4
    let spec = activity_chart_spec(jwt_auth.user.id, pairs).await?;
249
1
    Ok(chart_svg_response(&spec))
250
4
}
251

            
252
9
pub async fn activity_report_chart_json(
253
9
    Query(pairs): Query<Vec<(String, String)>>,
254
9
    State(_data): State<Arc<AppState>>,
255
9
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
256
9
) -> Result<impl IntoResponse, WebError> {
257
9
    let spec = activity_chart_spec(jwt_auth.user.id, pairs).await?;
258
5
    Ok(Json(spec))
259
9
}
260

            
261
#[cfg(test)]
262
#[path = "activity_tests.rs"]
263
mod tests;