1
//! The activity report's `groups.N.name`, `groups.N.filter` and
2
//! `groups.N.flip` rows, as the editor shows them.
3

            
4
use askama::Template;
5
use forms::{FieldError, FormValues, address};
6

            
7
const FLIP_ON: &str = "yes";
8

            
9
#[derive(Default)]
10
pub struct GroupRow {
11
    pub name: String,
12
    pub filter: String,
13
    pub flip: bool,
14
    pub name_errors: Vec<String>,
15
    pub filter_errors: Vec<String>,
16
    pub flip_errors: Vec<String>,
17
}
18

            
19
impl GroupRow {
20
16
    fn from_cells(index: usize, row: &forms::Row, errors: &[FieldError]) -> Self {
21
48
        let cell = |key: &str| row.get(key).map_or("", String::as_str);
22
48
        let problems = |key: &str| {
23
48
            let at = address::cell("groups", index, key);
24
48
            errors
25
48
                .iter()
26
33
                .filter(|error| error.field == at)
27
6
                .map(|error| error.message.clone())
28
                .collect()
29
48
        };
30
16
        Self {
31
16
            name: cell("name").trim().to_owned(),
32
16
            filter: cell("filter").to_owned(),
33
16
            flip: cell("flip") == FLIP_ON,
34
16
            name_errors: problems("name"),
35
16
            filter_errors: problems("filter"),
36
16
            flip_errors: problems("flip"),
37
16
        }
38
16
    }
39
}
40

            
41
/// The rows the form carries, each marked with the errors at its cells.
42
#[must_use]
43
20
pub fn group_rows(values: &FormValues, errors: &[FieldError]) -> Vec<GroupRow> {
44
20
    let rows = values.rows("groups").unwrap_or_default();
45
20
    rows.iter()
46
20
        .enumerate()
47
16
        .map(|(index, row)| GroupRow::from_cells(index, row, errors))
48
        .collect()
49
20
}
50

            
51
const CELLS: [&str; 3] = ["name", "filter", "flip"];
52

            
53
/// Whether the editor marks `error` on one of the cells it renders.
54
#[must_use]
55
19
pub fn is_marked(values: &FormValues, error: &FieldError) -> bool {
56
19
    let rows = values.rows("groups").map_or(0, |rows| rows.len());
57
31
    (0..rows).any(|index| {
58
29
        CELLS
59
29
            .iter()
60
79
            .any(|key| error.field == address::cell("groups", index, key))
61
29
    })
62
19
}
63

            
64
/// `oob` swaps the editor in beside a re-rendered form.
65
#[derive(Template)]
66
#[template(path = "components/report/activity_groups.html")]
67
pub struct GroupsEditor {
68
    pub groups: Vec<GroupRow>,
69
    pub oob: bool,
70
}
71

            
72
#[cfg(test)]
73
#[path = "activity_groups_tests.rs"]
74
mod tests;