1
//! What the edit-form loaders share: the refusals for stored tags a form
2
//! cannot hold, and the `tags` rows.
3

            
4
use std::collections::HashSet;
5

            
6
use finance::tag::Tag;
7
use forms::Row;
8
use server::logical::ensure_single_line_names;
9

            
10
use super::Failure;
11

            
12
331
pub(super) fn refused(subject: &str, reason: &str) -> Failure {
13
331
    Failure::Refused(format!(
14
331
        "the {subject} cannot be edited as a form: {reason}"
15
331
    ))
16
331
}
17

            
18
/// A line break in a name or value, or two values of one name.
19
5360
pub(super) fn ensure_representable(subject: &str, tags: &[Tag]) -> Result<(), Failure> {
20
5360
    ensure_single_line_names(tags).map_err(|reason| refused(subject, &reason))?;
21
5355
    let mut seen = HashSet::new();
22
11290
    match tags.iter().find(|tag| !seen.insert(tag.normalized().0)) {
23
326
        Some(tag) => Err(refused(
24
326
            subject,
25
326
            &format!(
26
326
                "the {subject} carries two values of the tag '{}'",
27
326
                tag.normalized().0
28
326
            ),
29
326
        )),
30
5029
        None => Ok(()),
31
    }
32
5360
}
33

            
34
3326
pub(super) fn tag_row(tag: &Tag) -> Row {
35
3326
    let mut row = Row::from([
36
3326
        ("name".to_string(), tag.normalized().0.to_string()),
37
3326
        ("value".to_string(), tag.normalized().1.to_string()),
38
3326
    ]);
39
3326
    if let Some(description) = &tag.description {
40
3
        row.insert("description".to_string(), description.clone());
41
3323
    }
42
3326
    row
43
3326
}