server/command/
commodity_edit.rs1use crate::command::connection;
7use finance::commodity::Commodity;
8use finance::tag::Tag;
9use sqlx::{PgConnection, types::Uuid};
10use supp_macro::command;
11
12use super::attempt::{Attempt, found, missing};
13use super::commodity_tag::{IDENTITY_TAGS, not_found};
14use super::tag_replace::{identities, lock_keys, replace_tags, wanted_tags};
15use super::{CmdError, CmdResult, FinanceEntity};
16use crate::attempt::Tries;
17use crate::commodity_state::{STALE_COMMODITY, read_commodity};
18use crate::tag::lock::begin;
19use crate::tag::owned::Owner;
20use crate::user::User;
21
22command! {
23 EditCommodity {
24 #[required]
25 user_id: Uuid,
26 #[required]
27 commodity_id: Uuid,
28 #[required]
29 symbol: String,
30 #[required]
31 name: String,
32 #[required]
33 tags: Vec<Tag>,
34 #[required]
35 revision: String,
36 } => {
37 let wanted = commodity_wanted(&symbol, &name, tags)?;
38 let user = User { id: user_id };
39 let mut conn = connection(&user).await?;
40 let mut tries = Tries::default();
41 while tries
42 .step(edit_once(&mut conn, commodity_id, &wanted, &revision).await)?
43 .is_none()
44 {}
45 Ok(Some(CmdResult::Entity(FinanceEntity::Commodity(Commodity {
46 id: commodity_id,
47 }))))
48 }
49}
50
51fn identity_tag(name: &str, value: &str) -> Tag {
52 Tag {
53 id: Uuid::new_v4(),
54 tag_name: name.to_string(),
55 tag_value: value.to_string(),
56 description: None,
57 }
58}
59
60fn commodity_wanted(symbol: &str, name: &str, tags: Vec<Tag>) -> Result<Vec<Tag>, CmdError> {
63 let fixed: Vec<Tag> = IDENTITY_TAGS
64 .into_iter()
65 .zip([symbol, name])
66 .map(|(tag_name, value)| identity_tag(tag_name, value))
67 .collect();
68 match fixed.iter().find(|tag| tag.is_blank()) {
69 Some(blank) => Err(CmdError::Args(format!(
70 "The commodity {} must not be blank",
71 blank.tag_name
72 ))),
73 None => wanted_tags("A commodity", fixed, tags),
74 }
75}
76
77async fn edit_once(
78 conn: &mut PgConnection,
79 commodity_id: Uuid,
80 wanted: &[Tag],
81 revision: &str,
82) -> Result<(), Attempt> {
83 let mut tx = begin(conn).await?;
84 let before = found(read_commodity(&mut tx, commodity_id).await?, not_found)?;
85 lock_keys(&mut tx, &before.tags, wanted).await?;
86 Owner::Commodity
87 .lock_row(&mut tx, commodity_id)
88 .await
89 .map_err(|err| missing(err, not_found))?;
90 let stored = found(read_commodity(&mut tx, commodity_id).await?, not_found)?;
91 if identities(&stored.tags) != identities(&before.tags) {
92 return Err(Attempt::Retry);
93 }
94 if stored.revision() != revision {
95 return Err(CmdError::Args(STALE_COMMODITY.to_string()).into());
96 }
97 replace_tags(
98 &mut tx,
99 Owner::Commodity,
100 commodity_id,
101 &stored.tags,
102 wanted,
103 )
104 .await?;
105 tx.commit().await?;
106 Ok(())
107}