1
//! The tag replacement an edit command shares across owners: the wanted tags,
2
//! the key locks and the writes of the difference.
3

            
4
use std::collections::{BTreeMap, HashSet};
5

            
6
use finance::tag::Tag;
7
use sqlx::{PgConnection, types::Uuid};
8

            
9
use super::CmdError;
10
use super::attempt::Attempt;
11
use crate::tag::lock::{Key, lock};
12
use crate::tag::owned::Owner;
13

            
14
3
pub(super) fn args(reason: &str) -> CmdError {
15
3
    CmdError::Args(reason.to_string())
16
3
}
17

            
18
/// The `fixed` tags followed by the given ones, none blank, none named like a
19
/// fixed one, one value per name; `subject` opens the duplicate message.
20
6510
pub(super) fn wanted_tags(
21
6510
    subject: &str,
22
6510
    fixed: Vec<Tag>,
23
6510
    tags: Vec<Tag>,
24
6510
) -> Result<Vec<Tag>, CmdError> {
25
6510
    let fixed_names: Vec<String> = fixed
26
6510
        .iter()
27
8683
        .map(|tag| tag.normalized().0.to_string())
28
        .collect();
29
6510
    let mut seen = HashSet::new();
30
6510
    let mut wanted = fixed;
31
6510
    for tag in tags {
32
8841
        let name = tag.normalized().0.to_string();
33
8841
        let blank = tag.is_blank();
34
8841
        let first = seen.insert(name.clone());
35
8841
        match (blank, first, fixed_names.contains(&name)) {
36
2
            (true, ..) => return Err(args("Tag name and value must not be blank")),
37
            (_, _, true) => {
38
3
                return Err(CmdError::Args(format!(
39
3
                    "The {name} tag is edited in the {name} field"
40
3
                )));
41
            }
42
            (_, false, _) => {
43
2
                return Err(CmdError::Args(format!(
44
2
                    "{subject} carries one value per tag name"
45
2
                )));
46
            }
47
8834
            _ => wanted.push(tag),
48
        }
49
    }
50
6503
    Ok(wanted)
51
6510
}
52

            
53
7949
pub(super) fn keys(tags: &[Tag]) -> Vec<(Uuid, Key)> {
54
7949
    tags.iter()
55
19859
        .map(|tag| (tag.id, (tag.tag_name.clone(), tag.tag_value.clone())))
56
        .collect()
57
7949
}
58

            
59
13006
pub(super) fn identities(tags: &[Tag]) -> Vec<(Uuid, &str, &str)> {
60
13006
    tags.iter()
61
36828
        .map(|tag| (tag.id, tag.tag_name.as_str(), tag.tag_value.as_str()))
62
        .collect()
63
13006
}
64

            
65
/// Lock the keys of the stored and the wanted tags.
66
6503
pub(super) async fn lock_keys(
67
6503
    conn: &mut PgConnection,
68
6503
    stored: &[Tag],
69
6503
    wanted: &[Tag],
70
6503
) -> Result<(), Attempt> {
71
1967
    let destinations: Vec<&Tag> = wanted.iter().collect();
72
1967
    match lock(conn, &keys(stored), &destinations).await? {
73
1967
        Ok(()) => Ok(()),
74
        Err(_) => Err(Attempt::Retry),
75
    }
76
1967
}
77

            
78
/// Set the wanted tags that differ from the stored ones, clear the stored
79
/// names that are no longer wanted.
80
5053
pub(super) async fn replace_tags(
81
5053
    conn: &mut PgConnection,
82
5053
    owner: Owner,
83
5053
    id: Uuid,
84
5053
    stored: &[Tag],
85
5053
    wanted: &[Tag],
86
5053
) -> Result<(), sqlx::Error> {
87
1631
    let mut by_name: BTreeMap<&str, Vec<&Tag>> = BTreeMap::new();
88
1631
    for tag in stored {
89
3134
        by_name.entry(tag.normalized().0).or_default().push(tag);
90
    }
91
1631
    for tag in wanted {
92
3285
        match by_name.remove(tag.normalized().0) {
93
2801
            Some(held) if unchanged(&held, tag) => {}
94
2104
            _ => owner.write_set(conn, id, tag).await?,
95
        }
96
    }
97
1631
    for (name, held) in by_name {
98
332
        let released: Vec<(Uuid, Key)> = keys(&held.into_iter().cloned().collect::<Vec<_>>());
99
332
        owner.write_clear(conn, id, name, &released).await?;
100
    }
101
1631
    Ok(())
102
1631
}
103

            
104
/// The owner holds exactly `tag`; a blank description keeps the stored one.
105
51135
pub(super) fn unchanged(held: &[&Tag], tag: &Tag) -> bool {
106
51135
    matches!(held, [stored]
107
50231
        if stored.normalized().1 == tag.normalized().1
108
46956
            && (tag.description.is_none() || stored.description == tag.description))
109
51135
}