1
use crate::command::connection;
2
use chrono::{DateTime, Utc};
3
use num_rational::Rational64;
4
use sqlx::types::Uuid;
5
use std::cmp::Ordering;
6
use std::collections::HashMap;
7
use supp_macro::command;
8

            
9
use crate::user::User;
10

            
11
use super::super::{
12
    BreakdownData, BreakdownPeriod, BreakdownRow, BreakdownSort, CmdError, CmdResult,
13
    CommodityAmount, FilterEntity, PeriodGrouping, ReportFilter, ReportMeta, UNCATEGORIZED_KEY,
14
};
15
use super::fetch::{
16
    BreakdownSplit, fetch_date_range_breakdown_filtered_no_conversion,
17
    fetch_date_range_breakdown_filtered_with_conversion, fetch_target_symbol,
18
};
19
use super::period::boundaries;
20
use super::size_order::{cmp_size, magnitude};
21
use super::tree::{add_amount, report_failure, sort_amounts};
22
use finance::error::ReportError;
23

            
24
const 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.
33
18035
fn default_scope_filter() -> ReportFilter {
34
18035
    ReportFilter::TagIn {
35
18035
        entity: FilterEntity::Account,
36
18035
        name: "type".to_owned(),
37
18035
        values: vec!["income".to_owned(), "expense".to_owned()],
38
18035
    }
39
18035
}
40

            
41
18035
fn compose_scope(user_filter: Option<&ReportFilter>) -> ReportFilter {
42
18035
    match user_filter {
43
1444
        Some(f) => ReportFilter::And(vec![default_scope_filter(), f.clone()]),
44
16591
        None => default_scope_filter(),
45
    }
46
18035
}
47

            
48
20207
async fn fetch_splits(
49
20207
    conn: &mut sqlx::PgConnection,
50
20207
    target_commodity_id: Option<Uuid>,
51
20207
    target_symbol: Option<&str>,
52
20207
    from: DateTime<Utc>,
53
20207
    to: DateTime<Utc>,
54
20207
    tag_name: &str,
55
20207
    filter: &ReportFilter,
56
20207
) -> Result<Vec<BreakdownSplit>, CmdError> {
57
9699
    match (target_commodity_id, target_symbol) {
58
        (Some(tid), Some(sym)) => {
59
660
            fetch_date_range_breakdown_filtered_with_conversion(
60
660
                conn, tid, sym, from, to, tag_name, filter,
61
660
            )
62
660
            .await
63
        }
64
        _ => {
65
9039
            fetch_date_range_breakdown_filtered_no_conversion(conn, from, to, tag_name, filter)
66
9039
                .await
67
        }
68
    }
69
9699
}
70

            
71
type AmountByCommodity = HashMap<Uuid, (Rational64, String)>;
72

            
73
19846
fn aggregate(
74
19846
    splits: Vec<BreakdownSplit>,
75
19846
    include_uncategorized: bool,
76
19846
) -> Result<Vec<BreakdownRow>, ReportError> {
77
19846
    let mut by_tag: HashMap<String, AmountByCommodity> = HashMap::new();
78

            
79
19846
    for s in splits {
80
64246
        let key = s.category.unwrap_or_else(|| UNCATEGORIZED_KEY.to_owned());
81
64246
        add_amount(
82
64246
            by_tag.entry(key).or_default(),
83
64246
            s.commodity_id,
84
64246
            s.value,
85
64246
            &s.commodity_symbol,
86
64246
        )?;
87
    }
88

            
89
19845
    Ok(by_tag
90
19845
        .into_iter()
91
46011
        .filter(|(k, _)| include_uncategorized || k != UNCATEGORIZED_KEY)
92
45108
        .map(|(tag_value, amounts)| {
93
45108
            let is_uncategorized = tag_value == UNCATEGORIZED_KEY;
94
45108
            let mut amounts: Vec<CommodityAmount> = amounts
95
45108
                .into_iter()
96
                .map(
97
                    |(commodity_id, (amount, commodity_symbol))| CommodityAmount {
98
45832
                        commodity_id,
99
45832
                        commodity_symbol,
100
45832
                        amount,
101
45832
                    },
102
                )
103
                .collect();
104
45108
            sort_amounts(&mut amounts);
105
45108
            BreakdownRow {
106
45108
                tag_value,
107
45108
                is_uncategorized,
108
45108
                amounts,
109
45108
            }
110
45108
        })
111
        .collect())
112
19846
}
113

            
114
8314
fn target_size(row: &BreakdownRow, target: Uuid) -> Rational64 {
115
8314
    row.amounts
116
8314
        .iter()
117
8314
        .find(|a| a.commodity_id == target)
118
8314
        .map_or(Rational64::ZERO, |a| magnitude(a.amount))
119
8314
}
120

            
121
82306
fn symbol_amounts(row: &BreakdownRow) -> Vec<(&str, Rational64)> {
122
82306
    row.amounts
123
82306
        .iter()
124
83227
        .map(|a| (a.commodity_symbol.as_str(), a.amount))
125
        .collect()
126
82306
}
127

            
128
45310
fn cmp_rows(a: &BreakdownRow, b: &BreakdownRow, target: Option<Uuid>) -> Ordering {
129
45310
    match target {
130
4157
        Some(tid) => target_size(a, tid).cmp(&target_size(b, tid)),
131
41153
        None => cmp_size(&symbol_amounts(a), &symbol_amounts(b)),
132
    }
133
45310
}
134

            
135
6690
fn uncategorized_last(a: &BreakdownRow, b: &BreakdownRow) -> Ordering {
136
6690
    a.is_uncategorized.cmp(&b.is_uncategorized)
137
6690
}
138

            
139
19860
fn sort_rows(rows: &mut [BreakdownRow], order: BreakdownSort, target_commodity_id: Option<Uuid>) {
140
19860
    match order {
141
        // Rows arrive in hash-map order, so equal sizes fall back to the name.
142
41861
        BreakdownSort::AmountDesc => rows.sort_by(|a, b| {
143
41861
            cmp_rows(b, a, target_commodity_id).then_with(|| a.tag_value.cmp(&b.tag_value))
144
41861
        }),
145
3449
        BreakdownSort::AmountAsc => rows.sort_by(|a, b| {
146
3449
            cmp_rows(a, b, target_commodity_id).then_with(|| a.tag_value.cmp(&b.tag_value))
147
3449
        }),
148
2163
        BreakdownSort::NameAsc => rows
149
4337
            .sort_by(|a, b| uncategorized_last(a, b).then_with(|| a.tag_value.cmp(&b.tag_value))),
150
902
        BreakdownSort::NameDesc => rows
151
2353
            .sort_by(|a, b| uncategorized_last(a, b).then_with(|| b.tag_value.cmp(&a.tag_value))),
152
    }
153
19860
}
154

            
155
command! {
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
8870
        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
329
            .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
107594
}
254

            
255
#[cfg(test)]
256
#[path = "category_breakdown_tests.rs"]
257
mod tests;