1
//! `EditCommodity`: replace the symbol, the name and the other tags of a
2
//! commodity in one DB transaction. Lock order: the tag keys, then the
3
//! commodity row; a commodity has no hierarchy. The revision is checked under
4
//! the locks.
5

            
6
use crate::command::connection;
7
use finance::commodity::Commodity;
8
use finance::tag::Tag;
9
use sqlx::{PgConnection, types::Uuid};
10
use supp_macro::command;
11

            
12
use super::attempt::{Attempt, found, missing};
13
use super::commodity_tag::{IDENTITY_TAGS, not_found};
14
use super::tag_replace::{identities, lock_keys, replace_tags, wanted_tags};
15
use super::{CmdError, CmdResult, FinanceEntity};
16
use crate::attempt::Tries;
17
use crate::commodity_state::{STALE_COMMODITY, read_commodity};
18
use crate::tag::lock::begin;
19
use crate::tag::owned::Owner;
20
use crate::user::User;
21

            
22
command! {
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
16047
}
50

            
51
4350
fn identity_tag(name: &str, value: &str) -> Tag {
52
4350
    Tag {
53
4350
        id: Uuid::new_v4(),
54
4350
        tag_name: name.to_string(),
55
4350
        tag_value: value.to_string(),
56
4350
        description: None,
57
4350
    }
58
4350
}
59

            
60
/// The tags the commodity ends up with: the `symbol` and `name` tags and the
61
/// given ones.
62
2175
fn commodity_wanted(symbol: &str, name: &str, tags: Vec<Tag>) -> Result<Vec<Tag>, CmdError> {
63
2175
    let fixed: Vec<Tag> = IDENTITY_TAGS
64
2175
        .into_iter()
65
2175
        .zip([symbol, name])
66
4350
        .map(|(tag_name, value)| identity_tag(tag_name, value))
67
        .collect();
68
4349
    match fixed.iter().find(|tag| tag.is_blank()) {
69
2
        Some(blank) => Err(CmdError::Args(format!(
70
2
            "The commodity {} must not be blank",
71
2
            blank.tag_name
72
2
        ))),
73
2173
        None => wanted_tags("A commodity", fixed, tags),
74
    }
75
2175
}
76

            
77
2170
async fn edit_once(
78
2170
    conn: &mut PgConnection,
79
2170
    commodity_id: Uuid,
80
2170
    wanted: &[Tag],
81
2170
    revision: &str,
82
2170
) -> Result<(), Attempt> {
83
817
    let mut tx = begin(conn).await?;
84
817
    let before = found(read_commodity(&mut tx, commodity_id).await?, not_found)?;
85
816
    lock_keys(&mut tx, &before.tags, wanted).await?;
86
816
    Owner::Commodity
87
816
        .lock_row(&mut tx, commodity_id)
88
816
        .await
89
        .map_err(|err| missing(err, not_found))?;
90
816
    let stored = found(read_commodity(&mut tx, commodity_id).await?, not_found)?;
91
816
    if identities(&stored.tags) != identities(&before.tags) {
92
1
        return Err(Attempt::Retry);
93
815
    }
94
815
    if stored.revision() != revision {
95
164
        return Err(CmdError::Args(STALE_COMMODITY.to_string()).into());
96
651
    }
97
651
    replace_tags(
98
651
        &mut tx,
99
651
        Owner::Commodity,
100
651
        commodity_id,
101
651
        &stored.tags,
102
651
        wanted,
103
651
    )
104
651
    .await?;
105
651
    tx.commit().await?;
106
651
    Ok(())
107
817
}