Skip to main content

server/command/report/
category_breakdown.rs

1use crate::command::connection;
2use chrono::{DateTime, Utc};
3use num_rational::Rational64;
4use sqlx::types::Uuid;
5use std::cmp::Ordering;
6use std::collections::HashMap;
7use supp_macro::command;
8
9use crate::user::User;
10
11use super::super::{
12    BreakdownData, BreakdownPeriod, BreakdownRow, BreakdownSort, CmdError, CmdResult,
13    CommodityAmount, FilterEntity, PeriodGrouping, ReportFilter, ReportMeta, UNCATEGORIZED_KEY,
14};
15use super::fetch::{
16    BreakdownSplit, fetch_date_range_breakdown_filtered_no_conversion,
17    fetch_date_range_breakdown_filtered_with_conversion, fetch_target_symbol,
18};
19use super::period::boundaries;
20use super::size_order::{cmp_size, magnitude};
21use super::tree::{add_amount, report_failure, sort_amounts};
22use finance::error::ReportError;
23
24const DEFAULT_TAG_NAME: &str = "category";
25
26/// Default scope filter: only count splits that live on income or expense
27/// accounts. Without this, the balancing asset/liability leg of every
28/// transaction lands in `Uncategorized` and every balanced transaction
29/// sums to zero across the breakdown.
30///
31// TODO(script-classifier): mirror ActivityReport's future script hook —
32// swap this fixed TagIn for a user-supplied classifier expression.
33fn default_scope_filter() -> ReportFilter {
34    ReportFilter::TagIn {
35        entity: FilterEntity::Account,
36        name: "type".to_owned(),
37        values: vec!["income".to_owned(), "expense".to_owned()],
38    }
39}
40
41fn compose_scope(user_filter: Option<&ReportFilter>) -> ReportFilter {
42    match user_filter {
43        Some(f) => ReportFilter::And(vec![default_scope_filter(), f.clone()]),
44        None => default_scope_filter(),
45    }
46}
47
48async fn fetch_splits(
49    conn: &mut sqlx::PgConnection,
50    target_commodity_id: Option<Uuid>,
51    target_symbol: Option<&str>,
52    from: DateTime<Utc>,
53    to: DateTime<Utc>,
54    tag_name: &str,
55    filter: &ReportFilter,
56) -> Result<Vec<BreakdownSplit>, CmdError> {
57    match (target_commodity_id, target_symbol) {
58        (Some(tid), Some(sym)) => {
59            fetch_date_range_breakdown_filtered_with_conversion(
60                conn, tid, sym, from, to, tag_name, filter,
61            )
62            .await
63        }
64        _ => {
65            fetch_date_range_breakdown_filtered_no_conversion(conn, from, to, tag_name, filter)
66                .await
67        }
68    }
69}
70
71type AmountByCommodity = HashMap<Uuid, (Rational64, String)>;
72
73fn aggregate(
74    splits: Vec<BreakdownSplit>,
75    include_uncategorized: bool,
76) -> Result<Vec<BreakdownRow>, ReportError> {
77    let mut by_tag: HashMap<String, AmountByCommodity> = HashMap::new();
78
79    for s in splits {
80        let key = s.category.unwrap_or_else(|| UNCATEGORIZED_KEY.to_owned());
81        add_amount(
82            by_tag.entry(key).or_default(),
83            s.commodity_id,
84            s.value,
85            &s.commodity_symbol,
86        )?;
87    }
88
89    Ok(by_tag
90        .into_iter()
91        .filter(|(k, _)| include_uncategorized || k != UNCATEGORIZED_KEY)
92        .map(|(tag_value, amounts)| {
93            let is_uncategorized = tag_value == UNCATEGORIZED_KEY;
94            let mut amounts: Vec<CommodityAmount> = amounts
95                .into_iter()
96                .map(
97                    |(commodity_id, (amount, commodity_symbol))| CommodityAmount {
98                        commodity_id,
99                        commodity_symbol,
100                        amount,
101                    },
102                )
103                .collect();
104            sort_amounts(&mut amounts);
105            BreakdownRow {
106                tag_value,
107                is_uncategorized,
108                amounts,
109            }
110        })
111        .collect())
112}
113
114fn target_size(row: &BreakdownRow, target: Uuid) -> Rational64 {
115    row.amounts
116        .iter()
117        .find(|a| a.commodity_id == target)
118        .map_or(Rational64::ZERO, |a| magnitude(a.amount))
119}
120
121fn symbol_amounts(row: &BreakdownRow) -> Vec<(&str, Rational64)> {
122    row.amounts
123        .iter()
124        .map(|a| (a.commodity_symbol.as_str(), a.amount))
125        .collect()
126}
127
128fn cmp_rows(a: &BreakdownRow, b: &BreakdownRow, target: Option<Uuid>) -> Ordering {
129    match target {
130        Some(tid) => target_size(a, tid).cmp(&target_size(b, tid)),
131        None => cmp_size(&symbol_amounts(a), &symbol_amounts(b)),
132    }
133}
134
135fn uncategorized_last(a: &BreakdownRow, b: &BreakdownRow) -> Ordering {
136    a.is_uncategorized.cmp(&b.is_uncategorized)
137}
138
139fn sort_rows(rows: &mut [BreakdownRow], order: BreakdownSort, target_commodity_id: Option<Uuid>) {
140    match order {
141        // Rows arrive in hash-map order, so equal sizes fall back to the name.
142        BreakdownSort::AmountDesc => rows.sort_by(|a, b| {
143            cmp_rows(b, a, target_commodity_id).then_with(|| a.tag_value.cmp(&b.tag_value))
144        }),
145        BreakdownSort::AmountAsc => rows.sort_by(|a, b| {
146            cmp_rows(a, b, target_commodity_id).then_with(|| a.tag_value.cmp(&b.tag_value))
147        }),
148        BreakdownSort::NameAsc => rows
149            .sort_by(|a, b| uncategorized_last(a, b).then_with(|| a.tag_value.cmp(&b.tag_value))),
150        BreakdownSort::NameDesc => rows
151            .sort_by(|a, b| uncategorized_last(a, b).then_with(|| b.tag_value.cmp(&a.tag_value))),
152    }
153}
154
155command! {
156    CategoryBreakdown {
157        #[required]
158        user_id: Uuid,
159        #[required]
160        date_from: DateTime<Utc>,
161        #[required]
162        date_to: DateTime<Utc>,
163        #[optional]
164        tag_name: String,
165        #[optional]
166        target_commodity_id: Uuid,
167        #[optional]
168        period_grouping: PeriodGrouping,
169        #[optional]
170        report_filter: ReportFilter,
171        #[optional]
172        sort_order: BreakdownSort,
173        #[optional]
174        include_uncategorized: bool,
175        // TODO(result-script): accept a nomiscript expression to filter/reshape
176        // BreakdownRow entries before returning. The format is not yet
177        // designed; see doc/reporting.org "Future work" for the intent.
178        #[optional]
179        result_script: String,
180    } => {
181        let user = User { id: user_id };
182        let mut conn = connection(&user).await?;
183
184        let tag_name = tag_name.unwrap_or_else(|| DEFAULT_TAG_NAME.to_owned());
185        let include_uncategorized = include_uncategorized.unwrap_or(true);
186        let sort_order = sort_order.unwrap_or_default();
187        let _ = result_script;
188        // Measured after scoping, because that is the filter the query runs:
189        // checking the user's half alone let a 64-leaf filter execute as 66.
190        let scoped_filter = compose_scope(report_filter.as_ref());
191        super::filter::check_filter_size(scoped_filter.leaves())?;
192
193        let target_symbol = match target_commodity_id {
194            Some(tid) => Some(fetch_target_symbol(&mut conn, tid).await?),
195            None => None,
196        };
197
198        super::period::check_range(date_from, date_to)?;
199        let period_boundaries = period_grouping
200            .map(|g| boundaries(g, date_from, date_to))
201            .transpose()?
202            .unwrap_or_default();
203
204        let mut periods = if period_boundaries.is_empty() {
205            let splits = fetch_splits(
206                &mut conn,
207                target_commodity_id,
208                target_symbol.as_deref(),
209                date_from,
210                date_to,
211                &tag_name,
212                &scoped_filter,
213            )
214            .await?;
215            let rows = aggregate(splits, include_uncategorized).map_err(report_failure)?;
216            vec![BreakdownPeriod { label: None, rows }]
217        } else {
218            let mut out = Vec::with_capacity(period_boundaries.len());
219            for (label, pfrom, pto) in &period_boundaries {
220                let splits = fetch_splits(
221                    &mut conn,
222                    target_commodity_id,
223                    target_symbol.as_deref(),
224                    *pfrom,
225                    *pto,
226                    &tag_name,
227                    &scoped_filter,
228                )
229                .await?;
230                let rows = aggregate(splits, include_uncategorized).map_err(report_failure)?;
231                out.push(BreakdownPeriod {
232                    label: Some(label.clone()),
233                    rows,
234                });
235            }
236            out
237        };
238
239        for period in &mut periods {
240            sort_rows(&mut period.rows, sort_order, target_commodity_id);
241        }
242
243        Ok(Some(CmdResult::Breakdown(BreakdownData {
244            meta: ReportMeta {
245                date_from: Some(date_from),
246                date_to: Some(date_to),
247                target_commodity_id,
248            },
249            tag_name,
250            periods,
251        })))
252    }
253}
254
255#[cfg(test)]
256#[path = "category_breakdown_tests.rs"]
257mod tests;