Skip to main content

rpc/forms/
report.rs

1//! The report query forms: values to command parameters, then the command.
2
3use chrono::{DateTime, Utc};
4use forms::{FieldError, Form, FormValues, REPORT_BALANCE};
5use server::command::report::BalanceReport;
6use server::command::{CmdError, CmdResult, PeriodGrouping, ReportData, ReportFilter};
7use server::timezone::{Tz, local_day};
8use uuid::Uuid;
9
10use super::handler::{Handler, unknown};
11use super::query::{date, field_error, filled};
12use super::report_activity::activity;
13use super::report_category::category;
14use super::report_clock::user_zone;
15use super::report_defaults::apply_report_defaults;
16use super::{Failure, Outcome, ReportOutcome};
17use crate::resolve::Directory;
18
19const CTX: &str = "report";
20const INVERTED: &str = "the report range ends before it starts";
21
22/// The parameters every report shares.
23pub(super) struct Scope {
24    pub target: Option<Uuid>,
25    pub filter: Option<ReportFilter>,
26}
27
28pub(super) fn parse_filter(text: &str) -> Result<ReportFilter, String> {
29    ReportFilter::from_sexpr(text).map_err(|err| err.to_string())
30}
31
32pub(super) async fn scope(
33    user_id: Uuid,
34    values: &FormValues,
35    errors: &mut Vec<FieldError>,
36) -> Result<Scope, Failure> {
37    let mut target = None;
38    if let Some(key) = filled(values, "target") {
39        let directory = Directory::load(CTX, user_id).await?;
40        match directory.own_commodity(key) {
41            Ok(id) => target = Some(id),
42            Err(fault) => errors.push(field_error("target", fault.to_string())),
43        }
44    }
45    let filter = filled(values, "filter").and_then(|text| match parse_filter(text) {
46        Ok(filter) => Some(filter),
47        Err(message) => {
48            errors.push(field_error("filter", message));
49            None
50        }
51    });
52    Ok(Scope { target, filter })
53}
54
55/// The two dates of a report; an upper bound not after the lower is an error at the upper.
56pub(super) fn range(
57    form: &Form,
58    values: &FormValues,
59    (lower, upper): (&str, &str),
60    zone: Tz,
61    errors: &mut Vec<FieldError>,
62) -> (Option<DateTime<Utc>>, Option<DateTime<Utc>>) {
63    let from = date(form, values, (lower, zone), errors);
64    let to = date(form, values, (upper, zone), errors);
65    if from.zip(to).is_some_and(|(from, to)| to <= from) {
66        errors.push(field_error(upper, INVERTED));
67    }
68    (from, to)
69}
70
71pub(super) fn grouping(values: &FormValues) -> Option<PeriodGrouping> {
72    match filled(values, "grouping") {
73        Some("month") => Some(PeriodGrouping::Month),
74        Some("quarter") => Some(PeriodGrouping::Quarter),
75        Some("year") => Some(PeriodGrouping::Year),
76        _ => None,
77    }
78}
79
80pub(super) fn command_failure(err: CmdError) -> Failure {
81    Failure::from_command(CTX, err)
82}
83
84pub(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.
92async fn balance(user_id: Uuid, values: &FormValues, zone: Tz) -> Result<ReportData, Failure> {
93    let values = &values.normalized(&REPORT_BALANCE);
94    let mut errors = values.check(&REPORT_BALANCE);
95    let scope = scope(user_id, values, &mut errors).await?;
96    let (from, as_of) = range(
97        &REPORT_BALANCE,
98        values,
99        ("from", "as-of"),
100        zone,
101        &mut errors,
102    );
103    if !errors.is_empty() {
104        return Err(Failure::Invalid(errors));
105    }
106    let mut cmd = BalanceReport::new().user_id(user_id);
107    if let Some(target) = scope.target {
108        cmd = cmd.target_commodity_id(target);
109    }
110    if let Some(from) = from {
111        cmd = cmd.date_from(from);
112    }
113    if let Some(as_of) = as_of {
114        cmd = cmd.as_of(as_of);
115    }
116    if let Some(filter) = scope.filter {
117        cmd = cmd.report_filter(filter);
118    }
119    match cmd.run().await.map_err(command_failure)? {
120        Some(CmdResult::Report(data)) => Ok(data),
121        _ => Err(unexpected(&REPORT_BALANCE)),
122    }
123}
124
125/// Runs the report of the compiled-in query form `form`.
126pub async fn typed_report(
127    user_id: Uuid,
128    form: &Form,
129    values: &FormValues,
130) -> Result<ReportOutcome, Failure> {
131    typed_report_on(user_id, form, values, Utc::now()).await
132}
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.
136pub async fn typed_report_on(
137    user_id: Uuid,
138    form: &Form,
139    values: &FormValues,
140    now: DateTime<Utc>,
141) -> Result<ReportOutcome, Failure> {
142    let zone = user_zone(user_id).await?;
143    typed_report_in(user_id, form, values, (zone, now)).await
144}
145
146/// [`typed_report_on`] for a caller that already holds the user's `zone`.
147pub async fn typed_report_in(
148    user_id: Uuid,
149    form: &Form,
150    values: &FormValues,
151    (zone, now): (Tz, DateTime<Utc>),
152) -> Result<ReportOutcome, Failure> {
153    let mut values = values.clone();
154    apply_report_defaults(form, &mut values, local_day(now, zone));
155    let values = &values;
156    match Handler::of(form)? {
157        Handler::ReportBalance => balance(user_id, values, zone)
158            .await
159            .map(ReportOutcome::Balance),
160        Handler::ReportActivity => activity(user_id, values, zone)
161            .await
162            .map(ReportOutcome::Activity),
163        Handler::ReportCategory => category(user_id, values, zone)
164            .await
165            .map(ReportOutcome::Breakdown),
166        _ => Err(unknown(form.name)),
167    }
168}
169
170/// [`typed_report_in`] as the general outcome.
171pub async fn run_report_in(
172    user_id: Uuid,
173    form: &Form,
174    values: &FormValues,
175    clock: (Tz, DateTime<Utc>),
176) -> Result<Outcome, Failure> {
177    typed_report_in(user_id, form, values, clock)
178        .await
179        .map(Outcome::from)
180}