1
//! `SetCommodityTag` and `ClearCommodityTag` on the tag lock protocol.
2

            
3
use crate::command::connection;
4
use finance::tag::{Tag, normalize};
5
use sqlx::types::Uuid;
6
use supp_macro::command;
7

            
8
use super::attempt::settled;
9
use super::{CmdError, CmdResult};
10
use crate::attempt::Tries;
11
use crate::{tag::owned::Owner, user::User};
12

            
13
/// Names every commodity keeps: they identify it.
14
pub const IDENTITY_TAGS: [&str; 2] = ["symbol", "name"];
15

            
16
1443
pub(super) fn not_found() -> CmdError {
17
1443
    CmdError::NotFound("Commodity not found".to_string())
18
1443
}
19

            
20
command! {
21
    SetCommodityTag {
22
        #[required]
23
        user_id: Uuid,
24
        #[required]
25
        commodity_id: Uuid,
26
        #[required]
27
        tag_name: String,
28
        #[required]
29
        tag_value: String,
30
        #[optional]
31
        description: String,
32
    } => {
33
        let tag = Tag {
34
            id: Uuid::new_v4(),
35
            tag_name,
36
            tag_value,
37
            description: description.filter(|text| !text.trim().is_empty()),
38
        };
39
        if tag.is_blank() {
40
            return Err(CmdError::Args("Tag name and value must not be blank".to_string()));
41
        }
42
        let user = User { id: user_id };
43
        let mut conn = connection(&user).await?;
44
        let mut tries = Tries::default();
45
        while tries
46
            .step(settled(Owner::Commodity.set(&mut conn, commodity_id, &tag).await, not_found))?
47
            .is_none()
48
        {}
49
        Ok(Some(CmdResult::String("ok".to_string())))
50
    }
51
59815
}
52

            
53
command! {
54
    ClearCommodityTag {
55
        #[required]
56
        user_id: Uuid,
57
        #[required]
58
        commodity_id: Uuid,
59
        #[required]
60
        tag_name: String,
61
    } => {
62
        let (tag_name, _) = normalize(&tag_name, "");
63
        if tag_name.is_empty() {
64
            return Err(CmdError::Args("Tag name must not be blank".to_string()));
65
        }
66
        if IDENTITY_TAGS.contains(&tag_name) {
67
            return Err(CmdError::Args("The symbol and name tags cannot be cleared".to_string()));
68
        }
69
        let user = User { id: user_id };
70
        let mut conn = connection(&user).await?;
71
        let mut tries = Tries::default();
72
        while tries
73
            .step(settled(Owner::Commodity.clear(&mut conn, commodity_id, tag_name).await, not_found))?
74
            .is_none()
75
        {}
76
        Ok(Some(CmdResult::String("ok".to_string())))
77
    }
78
3640
}