1
use crate::command::connection;
2
use chrono::{DateTime, Utc};
3
use sqlx::types::Uuid;
4
use supp_macro::command;
5

            
6
use crate::user::User;
7

            
8
use super::super::{
9
    ActivityData, ActivityGroup, ActivityGroupResult, ActivityPeriod, CmdError, CmdResult,
10
    FilterEntity, PeriodGrouping, ReportFilter, ReportMeta,
11
};
12
use super::fetch::{
13
    fetch_accounts, fetch_date_range_splits_filtered_no_conversion,
14
    fetch_date_range_splits_filtered_with_conversion, fetch_target_symbol,
15
};
16
use 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.
23
pub(super) const MAX_QUERIES: usize = 4096;
24
use 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.
29
11356
fn default_activity_groups() -> Vec<ActivityGroup> {
30
11356
    vec![
31
11356
        ActivityGroup {
32
11356
            label: "Income".to_owned(),
33
11356
            filter: ReportFilter::Tag {
34
11356
                entity: FilterEntity::Account,
35
11356
                name: "type".to_owned(),
36
11356
                value: "income".to_owned(),
37
11356
            },
38
11356
            flip_sign: true,
39
11356
        },
40
11356
        ActivityGroup {
41
11356
            label: "Expense".to_owned(),
42
11356
            filter: ReportFilter::Tag {
43
11356
                entity: FilterEntity::Account,
44
11356
                name: "type".to_owned(),
45
11356
                value: "expense".to_owned(),
46
11356
            },
47
11356
            flip_sign: false,
48
11356
        },
49
    ]
50
11356
}
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.
58
13345
pub(super) fn widest_query_leaves(
59
13345
    report_filter: Option<&ReportFilter>,
60
13345
    groups: &[ActivityGroup],
61
13345
) -> usize {
62
13345
    report_filter.map_or(0, ReportFilter::leaves)
63
25262
        + groups.iter().map(|g| g.filter.leaves()).max().unwrap_or(0)
64
13345
}
65

            
66
29044
fn compose_group_filter(group: &ActivityGroup, user_filter: Option<&ReportFilter>) -> ReportFilter {
67
29044
    match user_filter {
68
2890
        Some(f) => ReportFilter::And(vec![group.filter.clone(), f.clone()]),
69
26154
        None => group.filter.clone(),
70
    }
71
29044
}
72

            
73
29044
async fn fetch_range(
74
29044
    conn: &mut sqlx::PgConnection,
75
29044
    target_commodity_id: Option<Uuid>,
76
29044
    target_symbol: Option<&str>,
77
29044
    from: DateTime<Utc>,
78
29044
    to: DateTime<Utc>,
79
29044
    filter: &ReportFilter,
80
29044
) -> Result<super::tree::AccountAmounts, CmdError> {
81
11355
    match (target_commodity_id, target_symbol) {
82
        (Some(tid), Some(sym)) => {
83
994
            fetch_date_range_splits_filtered_with_conversion(conn, tid, sym, from, to, filter).await
84
        }
85
10361
        _ => fetch_date_range_splits_filtered_no_conversion(conn, from, to, filter).await,
86
    }
87
11355
}
88

            
89
struct 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

            
96
29044
async fn run_group_for_period(
97
29044
    conn: &mut sqlx::PgConnection,
98
29044
    ctx: &RunCtx<'_>,
99
29044
    group: &ActivityGroup,
100
29044
    from: DateTime<Utc>,
101
29044
    to: DateTime<Utc>,
102
29044
) -> Result<ActivityGroupResult, CmdError> {
103
11355
    let filter = compose_group_filter(group, ctx.user_filter);
104
11355
    let amounts = fetch_range(
105
11355
        conn,
106
11355
        ctx.target_commodity_id,
107
11355
        ctx.target_symbol,
108
11355
        from,
109
11355
        to,
110
11355
        &filter,
111
11355
    )
112
11355
    .await?;
113
11031
    let roots = build_tree(ctx.accounts, &amounts).map_err(report_failure)?;
114
11031
    ActivityGroupResult::new(group.label.clone(), group.flip_sign, roots).map_err(report_failure)
115
11355
}
116

            
117
command! {
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
1135
            .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
66736
}