1
//! `ReparentAccount`: move an account under another parent, or to the root,
2
//! under the hierarchy lock, then the account rows.
3

            
4
use crate::command::connection;
5
use finance::account::Account;
6
use sqlx::{PgConnection, types::Uuid};
7
use supp_macro::command;
8

            
9
use super::{CmdError, CmdResult, FinanceEntity};
10
use crate::{hierarchy::lock_hierarchy, user::User};
11

            
12
command! {
13
    ReparentAccount {
14
        #[required]
15
        user_id: Uuid,
16
        #[required]
17
        account_id: Uuid,
18
        #[optional]
19
        parent: Uuid,
20
    } => {
21
        let user = User { id: user_id };
22
        let mut conn = connection(&user).await?;
23
        reparent(&mut conn, user_id, account_id, parent).await?;
24
        Ok(Some(CmdResult::Entity(FinanceEntity::Account(Account {
25
            id: account_id,
26
            parent,
27
        }))))
28
    }
29
54
}
30

            
31
/// The refusal of a move under the account itself or one of its descendants.
32
pub const CYCLE_REFUSED: &str =
33
    "An account cannot be moved under itself or one of its own sub-accounts";
34

            
35
11
async fn reparent(
36
11
    conn: &mut PgConnection,
37
11
    user_id: Uuid,
38
11
    account_id: Uuid,
39
11
    parent: Option<Uuid>,
40
11
) -> Result<(), CmdError> {
41
11
    let mut tx = crate::tag::lock::begin(conn).await?;
42
11
    lock_hierarchy(&mut tx, user_id).await?;
43
10
    move_account(&mut tx, account_id, parent).await?;
44
4
    tx.commit().await?;
45
4
    Ok(())
46
11
}
47

            
48
/// Move the account under `parent` (or to the root); the caller holds the
49
/// hierarchy lock.
50
915
pub(super) async fn move_account(
51
915
    conn: &mut PgConnection,
52
915
    account_id: Uuid,
53
915
    parent: Option<Uuid>,
54
915
) -> Result<(), CmdError> {
55
179
    lock_rows(conn, account_id, parent).await?;
56
176
    if let Some(parent) = parent {
57
173
        refuse_cycle(conn, account_id, parent).await?;
58
3
    }
59
169
    sqlx::query_file!("sql/update/accounts/set_parent.sql", account_id, parent)
60
169
        .execute(conn)
61
169
        .await?;
62
169
    Ok(())
63
179
}
64

            
65
/// Lock the account and its new parent in id order.
66
915
async fn lock_rows(
67
915
    conn: &mut PgConnection,
68
915
    account_id: Uuid,
69
915
    parent: Option<Uuid>,
70
915
) -> Result<(), CmdError> {
71
179
    let mut ids: Vec<Uuid> = std::iter::once(account_id).chain(parent).collect();
72
179
    ids.sort();
73
179
    for id in ids {
74
354
        let row = sqlx::query_file!("sql/select/accounts/by_id_locked.sql", id)
75
354
            .fetch_optional(&mut *conn)
76
354
            .await?;
77
354
        if row.is_none() {
78
3
            return Err(CmdError::NotFound(format!("Account {id} not found")));
79
351
        }
80
    }
81
176
    Ok(())
82
179
}
83

            
84
730
async fn refuse_cycle(
85
730
    conn: &mut PgConnection,
86
730
    account_id: Uuid,
87
730
    parent: Uuid,
88
730
) -> Result<(), CmdError> {
89
173
    let cyclic = parent == account_id
90
171
        || sqlx::query_file!("sql/select/accounts/is_descendant.sql", parent, account_id)
91
171
            .fetch_one(conn)
92
171
            .await?
93
            .is_descendant
94
171
            .unwrap_or(false);
95
173
    match cyclic {
96
7
        true => Err(CmdError::Refused(CYCLE_REFUSED.to_string())),
97
166
        false => Ok(()),
98
    }
99
173
}