Lines
98.31 %
Functions
100 %
Branches
//! `report-activity`: the groups rows and the activity command.
use forms::{FieldError, FormValues, REPORT_ACTIVITY, Row, address};
use server::command::report::ActivityReport;
use server::command::{ActivityData, ActivityGroup, CmdResult};
use server::timezone::Tz;
use uuid::Uuid;
use super::Failure;
use super::query::field_error;
use super::report::{command_failure, grouping, parse_filter, range, scope, unexpected};
/// A row naming a group and its filter; blank cells were already reported as required.
fn group(index: usize, row: &Row, errors: &mut Vec<FieldError>) -> Option<ActivityGroup> {
let cell = |key| {
row.get(key)
.map(|text| text.trim())
.filter(|t| !t.is_empty())
};
let (label, text) = (cell("name")?, cell("filter")?);
let filter = parse_filter(text)
.map_err(|message| {
errors.push(field_error(
&address::cell("groups", index, "filter"),
message,
));
})
.ok()?;
Some(ActivityGroup {
label: label.to_owned(),
filter,
flip_sign: cell("flip") == Some("yes"),
}
/// `None` when the form has no `groups` field at all: the command's default groups apply.
fn groups(values: &FormValues, errors: &mut Vec<FieldError>) -> Option<Vec<ActivityGroup>> {
let rows = values.rows("groups")?;
Some(
rows.iter()
.enumerate()
.filter_map(|(index, row)| group(index, row, errors))
.collect(),
)
pub(super) async fn activity(
user_id: Uuid,
values: &FormValues,
zone: Tz,
) -> Result<ActivityData, Failure> {
let values = &values.normalized(&REPORT_ACTIVITY);
let mut errors = values.check(&REPORT_ACTIVITY);
let scope = scope(user_id, values, &mut errors).await?;
let groups = groups(values, &mut errors);
let (from, to) = range(&REPORT_ACTIVITY, values, ("from", "to"), zone, &mut errors);
let (Some(from), Some(to), true) = (from, to, errors.is_empty()) else {
return Err(Failure::Invalid(errors));
let mut cmd = ActivityReport::new()
.user_id(user_id)
.date_from(from)
.date_to(to);
if let Some(target) = scope.target {
cmd = cmd.target_commodity_id(target);
if let Some(grouping) = grouping(values) {
cmd = cmd.period_grouping(grouping);
if let Some(groups) = groups {
cmd = cmd.groups(groups);
if let Some(filter) = scope.filter {
cmd = cmd.report_filter(filter);
match cmd.run().await.map_err(command_failure)? {
Some(CmdResult::Activity(data)) => Ok(data),
_ => Err(unexpected(&REPORT_ACTIVITY)),