1
//! The report query forms: values to command parameters, then the command.
2

            
3
use chrono::{DateTime, Utc};
4
use forms::{FieldError, Form, FormValues, REPORT_BALANCE};
5
use server::command::report::BalanceReport;
6
use server::command::{CmdError, CmdResult, PeriodGrouping, ReportData, ReportFilter};
7
use server::timezone::{Tz, local_day};
8
use uuid::Uuid;
9

            
10
use super::handler::{Handler, unknown};
11
use super::query::{date, field_error, filled};
12
use super::report_activity::activity;
13
use super::report_category::category;
14
use super::report_clock::user_zone;
15
use super::report_defaults::apply_report_defaults;
16
use super::{Failure, Outcome, ReportOutcome};
17
use crate::resolve::Directory;
18

            
19
const CTX: &str = "report";
20
const INVERTED: &str = "the report range ends before it starts";
21

            
22
/// The parameters every report shares.
23
pub(super) struct Scope {
24
    pub target: Option<Uuid>,
25
    pub filter: Option<ReportFilter>,
26
}
27

            
28
4506
pub(super) fn parse_filter(text: &str) -> Result<ReportFilter, String> {
29
4506
    ReportFilter::from_sexpr(text).map_err(|err| err.to_string())
30
4506
}
31

            
32
26384
pub(super) async fn scope(
33
26384
    user_id: Uuid,
34
26384
    values: &FormValues,
35
26384
    errors: &mut Vec<FieldError>,
36
26384
) -> Result<Scope, Failure> {
37
26384
    let mut target = None;
38
26384
    if let Some(key) = filled(values, "target") {
39
1138
        let directory = Directory::load(CTX, user_id).await?;
40
1138
        match directory.own_commodity(key) {
41
1134
            Ok(id) => target = Some(id),
42
4
            Err(fault) => errors.push(field_error("target", fault.to_string())),
43
        }
44
25246
    }
45
26384
    let filter = filled(values, "filter").and_then(|text| match parse_filter(text) {
46
1774
        Ok(filter) => Some(filter),
47
        Err(message) => {
48
962
            errors.push(field_error("filter", message));
49
962
            None
50
        }
51
2736
    });
52
26384
    Ok(Scope { target, filter })
53
26384
}
54

            
55
/// The two dates of a report; an upper bound not after the lower is an error at the upper.
56
26384
pub(super) fn range(
57
26384
    form: &Form,
58
26384
    values: &FormValues,
59
26384
    (lower, upper): (&str, &str),
60
26384
    zone: Tz,
61
26384
    errors: &mut Vec<FieldError>,
62
26384
) -> (Option<DateTime<Utc>>, Option<DateTime<Utc>>) {
63
26384
    let from = date(form, values, (lower, zone), errors);
64
26384
    let to = date(form, values, (upper, zone), errors);
65
26384
    if from.zip(to).is_some_and(|(from, to)| to <= from) {
66
170
        errors.push(field_error(upper, INVERTED));
67
26214
    }
68
26384
    (from, to)
69
26384
}
70

            
71
12866
pub(super) fn grouping(values: &FormValues) -> Option<PeriodGrouping> {
72
12866
    match filled(values, "grouping") {
73
1125
        Some("month") => Some(PeriodGrouping::Month),
74
4
        Some("quarter") => Some(PeriodGrouping::Quarter),
75
2
        Some("year") => Some(PeriodGrouping::Year),
76
11735
        _ => None,
77
    }
78
12866
}
79

            
80
350
pub(super) fn command_failure(err: CmdError) -> Failure {
81
350
    Failure::from_command(CTX, err)
82
350
}
83

            
84
pub(crate) fn unexpected(form: &Form) -> Failure {
85
    Failure::Internal(wasmtime::Error::msg(format!(
86
        "{}: unexpected result",
87
        form.name
88
    )))
89
}
90

            
91
/// The balance report of the `report-balance` values.
92
9346
async fn balance(user_id: Uuid, values: &FormValues, zone: Tz) -> Result<ReportData, Failure> {
93
9346
    let values = &values.normalized(&REPORT_BALANCE);
94
9346
    let mut errors = values.check(&REPORT_BALANCE);
95
9346
    let scope = scope(user_id, values, &mut errors).await?;
96
9346
    let (from, as_of) = range(
97
9346
        &REPORT_BALANCE,
98
9346
        values,
99
9346
        ("from", "as-of"),
100
9346
        zone,
101
9346
        &mut errors,
102
9346
    );
103
9346
    if !errors.is_empty() {
104
651
        return Err(Failure::Invalid(errors));
105
8695
    }
106
8695
    let mut cmd = BalanceReport::new().user_id(user_id);
107
8695
    if let Some(target) = scope.target {
108
326
        cmd = cmd.target_commodity_id(target);
109
8369
    }
110
8695
    if let Some(from) = from {
111
3216
        cmd = cmd.date_from(from);
112
5479
    }
113
8695
    if let Some(as_of) = as_of {
114
8695
        cmd = cmd.as_of(as_of);
115
    }
116
8695
    if let Some(filter) = scope.filter {
117
647
        cmd = cmd.report_filter(filter);
118
8048
    }
119
8695
    match cmd.run().await.map_err(command_failure)? {
120
8690
        Some(CmdResult::Report(data)) => Ok(data),
121
        _ => Err(unexpected(&REPORT_BALANCE)),
122
    }
123
9346
}
124

            
125
/// Runs the report of the compiled-in query form `form`.
126
8528
pub async fn typed_report(
127
8528
    user_id: Uuid,
128
8528
    form: &Form,
129
8528
    values: &FormValues,
130
8528
) -> Result<ReportOutcome, Failure> {
131
8528
    typed_report_on(user_id, form, values, Utc::now()).await
132
8528
}
133

            
134
/// [`typed_report`] at the instant `now`: the user's zone is read once, the empty dates
135
/// default from the local day of `now`, and typed days are read in that zone.
136
10064
pub async fn typed_report_on(
137
10064
    user_id: Uuid,
138
10064
    form: &Form,
139
10064
    values: &FormValues,
140
10064
    now: DateTime<Utc>,
141
10064
) -> Result<ReportOutcome, Failure> {
142
10064
    let zone = user_zone(user_id).await?;
143
10064
    typed_report_in(user_id, form, values, (zone, now)).await
144
10064
}
145

            
146
/// [`typed_report_on`] for a caller that already holds the user's `zone`.
147
26384
pub async fn typed_report_in(
148
26384
    user_id: Uuid,
149
26384
    form: &Form,
150
26384
    values: &FormValues,
151
26384
    (zone, now): (Tz, DateTime<Utc>),
152
26384
) -> Result<ReportOutcome, Failure> {
153
26384
    let mut values = values.clone();
154
26384
    apply_report_defaults(form, &mut values, local_day(now, zone));
155
26384
    let values = &values;
156
26384
    match Handler::of(form)? {
157
9346
        Handler::ReportBalance => balance(user_id, values, zone)
158
9346
            .await
159
9346
            .map(ReportOutcome::Balance),
160
7559
        Handler::ReportActivity => activity(user_id, values, zone)
161
7559
            .await
162
7559
            .map(ReportOutcome::Activity),
163
9479
        Handler::ReportCategory => category(user_id, values, zone)
164
9479
            .await
165
9479
            .map(ReportOutcome::Breakdown),
166
        _ => Err(unknown(form.name)),
167
    }
168
26384
}
169

            
170
/// [`typed_report_in`] as the general outcome.
171
16320
pub async fn run_report_in(
172
16320
    user_id: Uuid,
173
16320
    form: &Form,
174
16320
    values: &FormValues,
175
16320
    clock: (Tz, DateTime<Utc>),
176
16320
) -> Result<Outcome, Failure> {
177
16320
    typed_report_in(user_id, form, values, clock)
178
16320
        .await
179
16320
        .map(Outcome::from)
180
16320
}