Skip to main content

server/command/report/
activity.rs

1use crate::command::connection;
2use chrono::{DateTime, Utc};
3use sqlx::types::Uuid;
4use supp_macro::command;
5
6use crate::user::User;
7
8use super::super::{
9    ActivityData, ActivityGroup, ActivityGroupResult, ActivityPeriod, CmdError, CmdResult,
10    FilterEntity, PeriodGrouping, ReportFilter, ReportMeta,
11};
12use super::fetch::{
13    fetch_accounts, fetch_date_range_splits_filtered_no_conversion,
14    fetch_date_range_splits_filtered_with_conversion, fetch_target_symbol,
15};
16use super::period::boundaries;
17
18/// Queries a single activity report may issue.
19///
20/// The report runs one query per period per group; 4096 is already far past a
21/// readable report and keeps one request off a cluster shared with other
22/// tenants.
23pub(super) const MAX_QUERIES: usize = 4096;
24use super::tree::{build_tree, report_failure};
25
26// TODO(script-classifier): swap this helper for one that evaluates a
27// user-supplied nomiscript expression returning a Vec<ActivityGroup>. See
28// doc/reporting.org "Future work" for the intent.
29fn default_activity_groups() -> Vec<ActivityGroup> {
30    vec![
31        ActivityGroup {
32            label: "Income".to_owned(),
33            filter: ReportFilter::Tag {
34                entity: FilterEntity::Account,
35                name: "type".to_owned(),
36                value: "income".to_owned(),
37            },
38            flip_sign: true,
39        },
40        ActivityGroup {
41            label: "Expense".to_owned(),
42            filter: ReportFilter::Tag {
43                entity: FilterEntity::Account,
44                name: "type".to_owned(),
45                value: "expense".to_owned(),
46            },
47            flip_sign: false,
48        },
49    ]
50}
51
52/// Leaves in the largest query this report will run.
53///
54/// The MAX, not the sum: each query is `And(group.filter, report_filter)` for
55/// ONE group (see [`compose_group_filter`]), so summing across groups measures
56/// a cost no query ever incurs. How MANY groups there are is bounded separately,
57/// by the query budget.
58pub(super) fn widest_query_leaves(
59    report_filter: Option<&ReportFilter>,
60    groups: &[ActivityGroup],
61) -> usize {
62    report_filter.map_or(0, ReportFilter::leaves)
63        + groups.iter().map(|g| g.filter.leaves()).max().unwrap_or(0)
64}
65
66fn compose_group_filter(group: &ActivityGroup, user_filter: Option<&ReportFilter>) -> ReportFilter {
67    match user_filter {
68        Some(f) => ReportFilter::And(vec![group.filter.clone(), f.clone()]),
69        None => group.filter.clone(),
70    }
71}
72
73async fn fetch_range(
74    conn: &mut sqlx::PgConnection,
75    target_commodity_id: Option<Uuid>,
76    target_symbol: Option<&str>,
77    from: DateTime<Utc>,
78    to: DateTime<Utc>,
79    filter: &ReportFilter,
80) -> Result<super::tree::AccountAmounts, CmdError> {
81    match (target_commodity_id, target_symbol) {
82        (Some(tid), Some(sym)) => {
83            fetch_date_range_splits_filtered_with_conversion(conn, tid, sym, from, to, filter).await
84        }
85        _ => fetch_date_range_splits_filtered_no_conversion(conn, from, to, filter).await,
86    }
87}
88
89struct RunCtx<'a> {
90    accounts: &'a [super::tree::AccountRow],
91    user_filter: Option<&'a ReportFilter>,
92    target_commodity_id: Option<Uuid>,
93    target_symbol: Option<&'a str>,
94}
95
96async fn run_group_for_period(
97    conn: &mut sqlx::PgConnection,
98    ctx: &RunCtx<'_>,
99    group: &ActivityGroup,
100    from: DateTime<Utc>,
101    to: DateTime<Utc>,
102) -> Result<ActivityGroupResult, CmdError> {
103    let filter = compose_group_filter(group, ctx.user_filter);
104    let amounts = fetch_range(
105        conn,
106        ctx.target_commodity_id,
107        ctx.target_symbol,
108        from,
109        to,
110        &filter,
111    )
112    .await?;
113    let roots = build_tree(ctx.accounts, &amounts).map_err(report_failure)?;
114    ActivityGroupResult::new(group.label.clone(), group.flip_sign, roots).map_err(report_failure)
115}
116
117command! {
118    ActivityReport {
119        #[required]
120        user_id: Uuid,
121        #[required]
122        date_from: DateTime<Utc>,
123        #[required]
124        date_to: DateTime<Utc>,
125        #[optional]
126        target_commodity_id: Uuid,
127        #[optional]
128        period_grouping: PeriodGrouping,
129        #[optional]
130        groups: Vec<ActivityGroup>,
131        #[optional]
132        report_filter: ReportFilter,
133    } => {
134        let user = User { id: user_id };
135        let mut conn = connection(&user).await?;
136
137        let accounts = fetch_accounts(&mut conn).await?;
138        let groups = groups.unwrap_or_else(default_activity_groups);
139
140        let target_symbol = match target_commodity_id {
141            Some(tid) => Some(fetch_target_symbol(&mut conn, tid).await?),
142            None => None,
143        };
144
145        super::period::check_range(date_from, date_to)?;
146        let period_boundaries = period_grouping
147            .map(|g| boundaries(g, date_from, date_to))
148            .transpose()?
149            .unwrap_or_default();
150
151        // The loop below runs one query per period PER GROUP, and both factors
152        // come from the caller: `groups` is JSON on the query string with no
153        // length of its own. Bounding only the periods leaves the product
154        // unbounded, which is the whole defect over again.
155        super::period::query_budget(period_boundaries.len(), groups.len(), MAX_QUERIES)?;
156
157        super::filter::check_filter_size(widest_query_leaves(report_filter.as_ref(), &groups))?;
158
159        let ctx = RunCtx {
160            accounts: &accounts,
161            user_filter: report_filter.as_ref(),
162            target_commodity_id,
163            target_symbol: target_symbol.as_deref(),
164        };
165
166        let periods = if period_boundaries.is_empty() {
167            let mut group_results = Vec::with_capacity(groups.len());
168            for group in &groups {
169                group_results.push(
170                    run_group_for_period(&mut conn, &ctx, group, date_from, date_to).await?,
171                );
172            }
173            vec![ActivityPeriod::new(None, group_results).map_err(report_failure)?]
174        } else {
175            let mut out = Vec::with_capacity(period_boundaries.len());
176            for (label, pfrom, pto) in &period_boundaries {
177                let mut group_results = Vec::with_capacity(groups.len());
178                for group in &groups {
179                    group_results
180                        .push(run_group_for_period(&mut conn, &ctx, group, *pfrom, *pto).await?);
181                }
182                out.push(
183                    ActivityPeriod::new(Some(label.clone()), group_results).map_err(report_failure)?,
184                );
185            }
186            out
187        };
188
189        Ok(Some(CmdResult::Activity(ActivityData {
190            meta: ReportMeta {
191                date_from: Some(date_from),
192                date_to: Some(date_to),
193                target_commodity_id,
194            },
195            periods,
196        })))
197    }
198}