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_BALANCE};
11
use server::command::ReportData;
12
use server::command::report::view::{AmountView, ReportRowView, flatten_report_data};
13
use sqlx::types::Uuid;
14

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

            
19
use super::balance_query::ask;
20
use super::bookmark::content_url;
21
use super::invalid::report_invalid;
22
use super::query::Asked;
23
use super::{
24
    SummaryCard, chart_svg_response, commodity_symbols_in_rows, parse_sort_order_shared,
25
    sort_top_level_rows, sum_top_level_amounts, wants_json,
26
};
27
use rpc::chart::{ChartOpts, chart_spec, kind_or_default};
28
use rpc::forms::ReportOutcome;
29

            
30
const ACTION: &str = "/api/report/balance";
31

            
32
#[derive(Template)]
33
#[template(path = "pages/report/balance.html")]
34
struct BalanceReportPage {
35
    content_url: String,
36
}
37

            
38
4
pub async fn balance_report_page(RawQuery(query): RawQuery) -> impl IntoResponse {
39
4
    HtmlTemplate(BalanceReportPage {
40
4
        content_url: content_url(ACTION, query.as_deref()),
41
4
    })
42
4
}
43

            
44
#[derive(Template)]
45
#[template(path = "components/report/balance_table.html")]
46
struct BalanceTableTemplate {
47
    form: String,
48
    summary: Vec<SummaryCard>,
49
    rows: Vec<ReportRowView>,
50
    commodity_symbols: Vec<String>,
51
    commodity_columns: bool,
52
    sortable: bool,
53
    collapsible: bool,
54
    collapsed_depth: Option<String>,
55
    sort_order: String,
56
    chart_kind: String,
57
    chart_query: String,
58
    renderer: String,
59
}
60

            
61
7
fn balance_summary(rows: &[ReportRowView]) -> Vec<SummaryCard> {
62
7
    sum_top_level_amounts(rows)
63
7
        .into_iter()
64
        .map(|a| SummaryCard {
65
            label: format!("Total ({})", a.commodity_symbol),
66
            amounts: vec![AmountView {
67
                commodity_symbol: a.commodity_symbol,
68
                amount: a.amount,
69
            }],
70
            is_net: false,
71
            highlight: false,
72
        })
73
        .collect()
74
7
}
75

            
76
9
fn render(asked: &Asked<ReportData>, errors: &[FieldError]) -> Result<String, WebError> {
77
9
    render_form(
78
9
        &REPORT_BALANCE,
79
9
        &asked.values,
80
9
        errors,
81
9
        ACTION,
82
9
        &asked.references,
83
9
    )
84
    .map_err(|e| WebError::internal("Balance form render failed", e))
85
9
}
86

            
87
21
pub async fn balance_report_table(
88
21
    Query(pairs): Query<Vec<(String, String)>>,
89
21
    State(_data): State<Arc<AppState>>,
90
21
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
91
21
    headers: HeaderMap,
92
21
) -> Result<Response, WebError> {
93
21
    let asked = ask(jwt_auth.user.id, pairs).await?;
94
20
    let report_data = match &asked.report {
95
16
        Ok(data) => data,
96
4
        Err(errors) if wants_json(&headers) => {
97
2
            return Err(unprocessable_fields(errors.clone()));
98
        }
99
        Err(errors) => {
100
2
            return report_invalid(
101
2
                &headers,
102
2
                &REPORT_BALANCE,
103
2
                render(&asked, errors)?,
104
2
                &asked.presentation.shown,
105
2
                None,
106
            );
107
        }
108
    };
109
16
    if wants_json(&headers) {
110
9
        return Ok(Json(report_data).into_response());
111
7
    }
112

            
113
7
    let mut rows = flatten_report_data(report_data);
114
7
    let presentation = &asked.presentation;
115
7
    let sort_order = parse_sort_order_shared(presentation.sort_order.as_deref());
116
7
    sort_top_level_rows(&mut rows, sort_order);
117
7
    let summary = balance_summary(&rows);
118
7
    let commodity_symbols = commodity_symbols_in_rows(&rows);
119
7
    let chart_kind = presentation.chart.chart_kind_str();
120
7
    let renderer = presentation.chart.renderer_str();
121
7
    let sort_order_str = sort_order.to_str().to_string();
122

            
123
    Ok(HtmlTemplate(BalanceTableTemplate {
124
7
        form: render(&asked, &[])?,
125
7
        summary,
126
7
        rows,
127
7
        commodity_symbols,
128
7
        commodity_columns: presentation.table.commodity_columns_enabled(),
129
7
        sortable: true,
130
7
        collapsible: true,
131
7
        collapsed_depth: presentation.table.collapsed_depth.clone(),
132
7
        chart_query: asked.chart_query(
133
7
            &REPORT_BALANCE,
134
7
            &[
135
7
                ("chart_kind", &chart_kind),
136
7
                ("renderer", &renderer),
137
7
                ("sort_order", &sort_order_str),
138
7
            ],
139
7
        ),
140
7
        sort_order: sort_order_str,
141
7
        chart_kind,
142
7
        renderer,
143
    })
144
    .into_response())
145
21
}
146

            
147
/// The balance chart shows top-level accounts by magnitude. Both chart
148
/// endpoints take the table endpoint's query.
149
4
async fn balance_chart_spec(
150
4
    user_id: Uuid,
151
4
    pairs: Vec<(String, String)>,
152
4
) -> Result<plotting::ChartSpec, WebError> {
153
4
    let asked = ask(user_id, pairs).await?;
154
3
    let report_data = asked.report.map_err(unprocessable_fields)?;
155
3
    let sort_order = parse_sort_order_shared(asked.presentation.sort_order.as_deref());
156
3
    chart_spec(
157
3
        &ReportOutcome::Balance(report_data),
158
3
        &ChartOpts {
159
3
            kind: kind_or_default(asked.presentation.chart.chart_kind.as_deref()),
160
3
            sort: sort_order.into_plotting_balance(),
161
3
            ..ChartOpts::default()
162
3
        },
163
3
    )
164
    .map_err(|err| WebError::from(FinanceError::Report(err)))
165
4
}
166

            
167
pub async fn balance_report_chart_svg(
168
    Query(pairs): Query<Vec<(String, String)>>,
169
    State(_data): State<Arc<AppState>>,
170
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
171
) -> Result<impl IntoResponse, WebError> {
172
    let spec = balance_chart_spec(jwt_auth.user.id, pairs).await?;
173
    Ok(chart_svg_response(&spec))
174
}
175

            
176
4
pub async fn balance_report_chart_json(
177
4
    Query(pairs): Query<Vec<(String, String)>>,
178
4
    State(_data): State<Arc<AppState>>,
179
4
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
180
4
) -> Result<impl IntoResponse, WebError> {
181
4
    let spec = balance_chart_spec(jwt_auth.user.id, pairs).await?;
182
3
    Ok(Json(spec))
183
4
}