1
//! `EditAccount`: rename, re-parent and replace the tags of an account in one
2
//! DB transaction. Lock order: the hierarchy lock (always, so the cycle check
3
//! and the write are serialized with every hierarchy writer), then the tag
4
//! keys, then the account rows. The revision is checked under the locks.
5

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

            
12
use super::account_reparent::move_account;
13
use super::account_tag::not_found;
14
use super::attempt::{Attempt, found, missing};
15
use super::tag_replace::{args, identities, lock_keys, replace_tags, wanted_tags};
16
use super::{CmdError, CmdResult, FinanceEntity};
17
use crate::account_state::{STALE_ACCOUNT, read_account};
18
use crate::attempt::Tries;
19
use crate::hierarchy::lock_hierarchy;
20
use crate::tag::lock::begin;
21
use crate::tag::owned::Owner;
22
use crate::user::User;
23

            
24
command! {
25
    EditAccount {
26
        #[required]
27
        user_id: Uuid,
28
        #[required]
29
        account_id: Uuid,
30
        #[required]
31
        name: String,
32
        #[required]
33
        tags: Vec<Tag>,
34
        #[required]
35
        revision: String,
36
        #[optional]
37
        parent: Uuid,
38
    } => {
39
        let wanted = account_wanted(&name, tags)?;
40
        let user = User { id: user_id };
41
        let mut conn = connection(&user).await?;
42
        let mut tries = Tries::default();
43
        while tries
44
            .step(edit_once(&mut conn, user_id, account_id, &wanted, &revision, parent).await)?
45
            .is_none()
46
        {}
47
        Ok(Some(CmdResult::Entity(FinanceEntity::Account(Account {
48
            id: account_id,
49
            parent,
50
        }))))
51
    }
52
30248
}
53

            
54
/// The tags the account ends up with: the `name` tag and the given ones.
55
4338
fn account_wanted(name: &str, tags: Vec<Tag>) -> Result<Vec<Tag>, CmdError> {
56
4338
    let name = Tag {
57
4338
        id: Uuid::new_v4(),
58
4338
        tag_name: "name".to_string(),
59
4338
        tag_value: name.to_string(),
60
4338
        description: None,
61
4338
    };
62
4338
    match name.is_blank() {
63
1
        true => Err(args("The account name must not be blank")),
64
4337
        false => wanted_tags("An account", vec![name], tags),
65
    }
66
4338
}
67

            
68
4335
async fn edit_once(
69
4335
    conn: &mut PgConnection,
70
4335
    user_id: Uuid,
71
4335
    account_id: Uuid,
72
4335
    wanted: &[Tag],
73
4335
    revision: &str,
74
4335
    parent: Option<Uuid>,
75
4335
) -> Result<(), Attempt> {
76
1152
    let mut tx = begin(conn).await?;
77
1152
    lock_hierarchy(&mut tx, user_id).await?;
78
1152
    let before = found(read_account(&mut tx, account_id).await?, not_found)?;
79
1151
    lock_keys(&mut tx, &before.tags, wanted).await?;
80
1151
    Owner::Account
81
1151
        .lock_row(&mut tx, account_id)
82
1151
        .await
83
        .map_err(|err| missing(err, not_found))?;
84
1151
    let stored = found(read_account(&mut tx, account_id).await?, not_found)?;
85
1151
    if identities(&stored.tags) != identities(&before.tags) {
86
1
        return Err(Attempt::Retry);
87
1150
    }
88
1150
    if stored.revision() != revision {
89
165
        return Err(CmdError::Args(STALE_ACCOUNT.to_string()).into());
90
985
    }
91
985
    if stored.parent != parent {
92
170
        ensure_parent(&mut tx, parent).await?;
93
169
        move_account(&mut tx, account_id, parent).await?;
94
815
    }
95
980
    replace_tags(&mut tx, Owner::Account, account_id, &stored.tags, wanted).await?;
96
980
    tx.commit().await?;
97
980
    Ok(())
98
1152
}
99

            
100
/// Only a merge deletes accounts and it holds the hierarchy lock, so the
101
/// parent seen here stays until commit.
102
906
async fn ensure_parent(conn: &mut PgConnection, parent: Option<Uuid>) -> Result<(), Attempt> {
103
170
    let Some(parent) = parent else {
104
2
        return Ok(());
105
    };
106
168
    match read_account(conn, parent).await? {
107
167
        Some(_) => Ok(()),
108
1
        None => Err(CmdError::ParentGone(parent).into()),
109
    }
110
170
}