server/command/
commodity_tag.rs1use crate::command::connection;
4use finance::tag::{Tag, normalize};
5use sqlx::types::Uuid;
6use supp_macro::command;
7
8use super::attempt::settled;
9use super::{CmdError, CmdResult};
10use crate::attempt::Tries;
11use crate::{tag::owned::Owner, user::User};
12
13pub const IDENTITY_TAGS: [&str; 2] = ["symbol", "name"];
15
16pub(super) fn not_found() -> CmdError {
17 CmdError::NotFound("Commodity not found".to_string())
18}
19
20command! {
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}
52
53command! {
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}