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::{FieldError, REPORT_CATEGORY};
11
use rpc::chart::{ChartOpts, chart_spec, kind_or_default};
12
use rpc::forms::ReportOutcome;
13
use server::command::BreakdownData;
14
use server::command::report::view::{AmountView, BreakdownPeriodView, flatten_breakdown_data};
15
use sqlx::types::Uuid;
16

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

            
21
use super::bookmark::content_url;
22
use super::category_breakdown_query::ask;
23
use super::invalid::report_invalid;
24
use super::query::Asked;
25
use super::{SummaryCard, chart_svg_response, wants_json};
26

            
27
const ACTION: &str = "/api/report/category-breakdown";
28

            
29
#[derive(Template)]
30
#[template(path = "pages/report/category_breakdown.html")]
31
struct CategoryBreakdownReportPage {
32
    content_url: String,
33
}
34

            
35
4
pub async fn category_breakdown_report_page(RawQuery(query): RawQuery) -> impl IntoResponse {
36
4
    HtmlTemplate(CategoryBreakdownReportPage {
37
4
        content_url: content_url(ACTION, query.as_deref()),
38
4
    })
39
4
}
40

            
41
#[derive(Template)]
42
#[template(path = "components/report/category_breakdown_table.html")]
43
struct CategoryBreakdownTableTemplate {
44
    form: String,
45
    summary: Vec<SummaryCard>,
46
    periods: Vec<BreakdownPeriodView>,
47
    commodity_symbols: Vec<String>,
48
    commodity_columns: bool,
49
    tag_name: String,
50
    chart_kind: String,
51
    chart_query: String,
52
    renderer: String,
53
}
54

            
55
39
fn push_amount(dest: &mut Vec<AmountView>, a: &AmountView) {
56
39
    match dest
57
39
        .iter_mut()
58
23
        .find(|d| d.commodity_symbol == a.commodity_symbol)
59
    {
60
23
        Some(existing) => existing.amount += a.amount,
61
16
        None => dest.push(a.clone()),
62
    }
63
39
}
64

            
65
/// Build summary cards for Category Breakdown: one grand-total card per
66
/// commodity plus cards for the first `top_n` categories in the report's
67
/// row order.
68
23
fn breakdown_summary(periods: &[BreakdownPeriodView], top_n: usize) -> Vec<SummaryCard> {
69
23
    let mut totals: Vec<AmountView> = Vec::new();
70
23
    let mut per_category: Vec<(String, bool, Vec<AmountView>)> = Vec::new();
71

            
72
23
    for period in periods {
73
25
        for row in &period.rows {
74
37
            for a in &row.amounts {
75
37
                push_amount(&mut totals, a);
76
            }
77
37
            match per_category
78
37
                .iter_mut()
79
28
                .find(|(name, _, _)| name == &row.tag_value)
80
            {
81
                Some((_, _, amts)) => {
82
2
                    for a in &row.amounts {
83
2
                        push_amount(amts, a);
84
                    }
85
                }
86
35
                None => per_category.push((
87
35
                    row.tag_value.clone(),
88
35
                    row.is_uncategorized,
89
35
                    row.amounts.clone(),
90
35
                )),
91
            }
92
        }
93
    }
94

            
95
23
    let mut cards: Vec<SummaryCard> = totals
96
23
        .into_iter()
97
        .map(|a| SummaryCard {
98
16
            label: format!("Total ({})", a.commodity_symbol),
99
16
            amounts: vec![a],
100
16
            is_net: false,
101
16
            highlight: true,
102
16
        })
103
        .collect();
104

            
105
23
    for (name, is_uncat, amounts) in per_category.into_iter().take(top_n) {
106
33
        let label = if is_uncat {
107
5
            "(uncategorized)".to_string()
108
        } else {
109
28
            name
110
        };
111
33
        cards.push(SummaryCard {
112
33
            label,
113
33
            amounts,
114
33
            is_net: false,
115
33
            highlight: false,
116
33
        });
117
    }
118
23
    cards
119
23
}
120

            
121
17
fn collect_commodity_symbols(periods: &[BreakdownPeriodView]) -> Vec<String> {
122
17
    let mut seen: Vec<String> = Vec::new();
123
17
    for period in periods {
124
17
        for row in &period.rows {
125
23
            for a in &row.amounts {
126
23
                if !seen.iter().any(|s| s == &a.commodity_symbol) {
127
10
                    seen.push(a.commodity_symbol.clone());
128
13
                }
129
            }
130
        }
131
    }
132
17
    seen
133
17
}
134

            
135
21
fn render(asked: &Asked<BreakdownData>, errors: &[FieldError]) -> Result<String, WebError> {
136
21
    render_form(
137
21
        &REPORT_CATEGORY,
138
21
        &asked.values,
139
21
        errors,
140
21
        ACTION,
141
21
        &asked.references,
142
21
    )
143
    .map_err(|e| WebError::internal("Category form render failed", e))
144
21
}
145

            
146
30
pub async fn category_breakdown_report_table(
147
30
    Query(pairs): Query<Vec<(String, String)>>,
148
30
    State(_data): State<Arc<AppState>>,
149
30
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
150
30
    headers: HeaderMap,
151
30
) -> Result<Response, WebError> {
152
30
    let asked = ask(jwt_auth.user.id, pairs).await?;
153
29
    let breakdown_data = match &asked.report {
154
24
        Ok(data) => data,
155
5
        Err(errors) if wants_json(&headers) => {
156
1
            return Err(unprocessable_fields(errors.clone()));
157
        }
158
        Err(errors) => {
159
4
            return report_invalid(
160
4
                &headers,
161
4
                &REPORT_CATEGORY,
162
4
                render(&asked, errors)?,
163
4
                &asked.presentation.shown,
164
4
                None,
165
            );
166
        }
167
    };
168
24
    if wants_json(&headers) {
169
7
        return Ok(Json(breakdown_data).into_response());
170
17
    }
171

            
172
17
    let periods = flatten_breakdown_data(breakdown_data);
173
17
    let presentation = &asked.presentation;
174
17
    let chart_kind = presentation.chart.chart_kind_str();
175
17
    let renderer = presentation.chart.renderer_str();
176

            
177
    Ok(HtmlTemplate(CategoryBreakdownTableTemplate {
178
17
        form: render(&asked, &[])?,
179
17
        summary: breakdown_summary(&periods, 5),
180
17
        commodity_symbols: collect_commodity_symbols(&periods),
181
17
        periods,
182
17
        commodity_columns: presentation.table.commodity_columns_enabled(),
183
17
        tag_name: breakdown_data.tag_name.clone(),
184
17
        chart_query: asked.chart_query(
185
17
            &REPORT_CATEGORY,
186
17
            &[("chart_kind", &chart_kind), ("renderer", &renderer)],
187
17
        ),
188
17
        chart_kind,
189
17
        renderer,
190
    })
191
    .into_response())
192
30
}
193

            
194
/// Both chart endpoints take the table endpoint's query.
195
1
async fn breakdown_chart_spec(
196
1
    user_id: Uuid,
197
1
    pairs: Vec<(String, String)>,
198
1
) -> Result<plotting::ChartSpec, WebError> {
199
1
    let asked = ask(user_id, pairs).await?;
200
1
    let data = asked.report.map_err(unprocessable_fields)?;
201
1
    chart_spec(
202
1
        &ReportOutcome::Breakdown(data),
203
1
        &ChartOpts {
204
1
            kind: kind_or_default(asked.presentation.chart.chart_kind.as_deref()),
205
1
            ..ChartOpts::default()
206
1
        },
207
1
    )
208
    .map_err(|err| WebError::from(FinanceError::Report(err)))
209
1
}
210

            
211
pub async fn category_breakdown_report_chart_svg(
212
    Query(pairs): Query<Vec<(String, String)>>,
213
    State(_data): State<Arc<AppState>>,
214
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
215
) -> Result<impl IntoResponse, WebError> {
216
    let spec = breakdown_chart_spec(jwt_auth.user.id, pairs).await?;
217
    Ok(chart_svg_response(&spec))
218
}
219

            
220
1
pub async fn category_breakdown_report_chart_json(
221
1
    Query(pairs): Query<Vec<(String, String)>>,
222
1
    State(_data): State<Arc<AppState>>,
223
1
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
224
1
) -> Result<impl IntoResponse, WebError> {
225
1
    let spec = breakdown_chart_spec(jwt_auth.user.id, pairs).await?;
226
1
    Ok(Json(spec))
227
1
}
228

            
229
#[cfg(test)]
230
#[path = "category_breakdown_tests.rs"]
231
mod category_breakdown_tests;