Lines
100 %
Functions
38.61 %
Branches
use crate::command::connection;
use chrono::{DateTime, Utc};
use num_rational::Rational64;
use sqlx::types::Uuid;
use std::cmp::Ordering;
use std::collections::HashMap;
use supp_macro::command;
use crate::user::User;
use super::super::{
BreakdownData, BreakdownPeriod, BreakdownRow, BreakdownSort, CmdError, CmdResult,
CommodityAmount, FilterEntity, PeriodGrouping, ReportFilter, ReportMeta, UNCATEGORIZED_KEY,
};
use super::fetch::{
BreakdownSplit, fetch_date_range_breakdown_filtered_no_conversion,
fetch_date_range_breakdown_filtered_with_conversion, fetch_target_symbol,
use super::period::boundaries;
use super::size_order::{cmp_size, magnitude};
use super::tree::{add_amount, report_failure, sort_amounts};
use finance::error::ReportError;
const DEFAULT_TAG_NAME: &str = "category";
/// Default scope filter: only count splits that live on income or expense
/// accounts. Without this, the balancing asset/liability leg of every
/// transaction lands in `Uncategorized` and every balanced transaction
/// sums to zero across the breakdown.
///
// TODO(script-classifier): mirror ActivityReport's future script hook —
// swap this fixed TagIn for a user-supplied classifier expression.
fn default_scope_filter() -> ReportFilter {
ReportFilter::TagIn {
entity: FilterEntity::Account,
name: "type".to_owned(),
values: vec!["income".to_owned(), "expense".to_owned()],
}
fn compose_scope(user_filter: Option<&ReportFilter>) -> ReportFilter {
match user_filter {
Some(f) => ReportFilter::And(vec![default_scope_filter(), f.clone()]),
None => default_scope_filter(),
async fn fetch_splits(
conn: &mut sqlx::PgConnection,
target_commodity_id: Option<Uuid>,
target_symbol: Option<&str>,
from: DateTime<Utc>,
to: DateTime<Utc>,
tag_name: &str,
filter: &ReportFilter,
) -> Result<Vec<BreakdownSplit>, CmdError> {
match (target_commodity_id, target_symbol) {
(Some(tid), Some(sym)) => {
fetch_date_range_breakdown_filtered_with_conversion(
conn, tid, sym, from, to, tag_name, filter,
)
.await
_ => {
fetch_date_range_breakdown_filtered_no_conversion(conn, from, to, tag_name, filter)
type AmountByCommodity = HashMap<Uuid, (Rational64, String)>;
fn aggregate(
splits: Vec<BreakdownSplit>,
include_uncategorized: bool,
) -> Result<Vec<BreakdownRow>, ReportError> {
let mut by_tag: HashMap<String, AmountByCommodity> = HashMap::new();
for s in splits {
let key = s.category.unwrap_or_else(|| UNCATEGORIZED_KEY.to_owned());
add_amount(
by_tag.entry(key).or_default(),
s.commodity_id,
s.value,
&s.commodity_symbol,
)?;
Ok(by_tag
.into_iter()
.filter(|(k, _)| include_uncategorized || k != UNCATEGORIZED_KEY)
.map(|(tag_value, amounts)| {
let is_uncategorized = tag_value == UNCATEGORIZED_KEY;
let mut amounts: Vec<CommodityAmount> = amounts
.map(
|(commodity_id, (amount, commodity_symbol))| CommodityAmount {
commodity_id,
commodity_symbol,
amount,
},
.collect();
sort_amounts(&mut amounts);
BreakdownRow {
tag_value,
is_uncategorized,
amounts,
})
.collect())
fn target_size(row: &BreakdownRow, target: Uuid) -> Rational64 {
row.amounts
.iter()
.find(|a| a.commodity_id == target)
.map_or(Rational64::ZERO, |a| magnitude(a.amount))
fn symbol_amounts(row: &BreakdownRow) -> Vec<(&str, Rational64)> {
.map(|a| (a.commodity_symbol.as_str(), a.amount))
.collect()
fn cmp_rows(a: &BreakdownRow, b: &BreakdownRow, target: Option<Uuid>) -> Ordering {
match target {
Some(tid) => target_size(a, tid).cmp(&target_size(b, tid)),
None => cmp_size(&symbol_amounts(a), &symbol_amounts(b)),
fn uncategorized_last(a: &BreakdownRow, b: &BreakdownRow) -> Ordering {
a.is_uncategorized.cmp(&b.is_uncategorized)
fn sort_rows(rows: &mut [BreakdownRow], order: BreakdownSort, target_commodity_id: Option<Uuid>) {
match order {
// Rows arrive in hash-map order, so equal sizes fall back to the name.
BreakdownSort::AmountDesc => rows.sort_by(|a, b| {
cmp_rows(b, a, target_commodity_id).then_with(|| a.tag_value.cmp(&b.tag_value))
}),
BreakdownSort::AmountAsc => rows.sort_by(|a, b| {
cmp_rows(a, b, target_commodity_id).then_with(|| a.tag_value.cmp(&b.tag_value))
BreakdownSort::NameAsc => rows
.sort_by(|a, b| uncategorized_last(a, b).then_with(|| a.tag_value.cmp(&b.tag_value))),
BreakdownSort::NameDesc => rows
.sort_by(|a, b| uncategorized_last(a, b).then_with(|| b.tag_value.cmp(&a.tag_value))),
command! {
CategoryBreakdown {
#[required]
user_id: Uuid,
date_from: DateTime<Utc>,
date_to: DateTime<Utc>,
#[optional]
tag_name: String,
target_commodity_id: Uuid,
period_grouping: PeriodGrouping,
report_filter: ReportFilter,
sort_order: BreakdownSort,
// TODO(result-script): accept a nomiscript expression to filter/reshape
// BreakdownRow entries before returning. The format is not yet
// designed; see doc/reporting.org "Future work" for the intent.
result_script: String,
} => {
let user = User { id: user_id };
let mut conn = connection(&user).await?;
let tag_name = tag_name.unwrap_or_else(|| DEFAULT_TAG_NAME.to_owned());
let include_uncategorized = include_uncategorized.unwrap_or(true);
let sort_order = sort_order.unwrap_or_default();
let _ = result_script;
// Measured after scoping, because that is the filter the query runs:
// checking the user's half alone let a 64-leaf filter execute as 66.
let scoped_filter = compose_scope(report_filter.as_ref());
super::filter::check_filter_size(scoped_filter.leaves())?;
let target_symbol = match target_commodity_id {
Some(tid) => Some(fetch_target_symbol(&mut conn, tid).await?),
None => None,
super::period::check_range(date_from, date_to)?;
let period_boundaries = period_grouping
.map(|g| boundaries(g, date_from, date_to))
.transpose()?
.unwrap_or_default();
let mut periods = if period_boundaries.is_empty() {
let splits = fetch_splits(
&mut conn,
target_commodity_id,
target_symbol.as_deref(),
date_from,
date_to,
&tag_name,
&scoped_filter,
.await?;
let rows = aggregate(splits, include_uncategorized).map_err(report_failure)?;
vec![BreakdownPeriod { label: None, rows }]
} else {
let mut out = Vec::with_capacity(period_boundaries.len());
for (label, pfrom, pto) in &period_boundaries {
*pfrom,
*pto,
out.push(BreakdownPeriod {
label: Some(label.clone()),
rows,
});
out
for period in &mut periods {
sort_rows(&mut period.rows, sort_order, target_commodity_id);
Ok(Some(CmdResult::Breakdown(BreakdownData {
meta: ReportMeta {
date_from: Some(date_from),
date_to: Some(date_to),
tag_name,
periods,
})))
#[cfg(test)]
#[path = "category_breakdown_tests.rs"]
mod tests;