server/command/
account_reparent.rs1use crate::command::connection;
5use finance::account::Account;
6use sqlx::{PgConnection, types::Uuid};
7use supp_macro::command;
8
9use super::{CmdError, CmdResult, FinanceEntity};
10use crate::{hierarchy::lock_hierarchy, user::User};
11
12command! {
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}
30
31pub const CYCLE_REFUSED: &str =
33 "An account cannot be moved under itself or one of its own sub-accounts";
34
35async fn reparent(
36 conn: &mut PgConnection,
37 user_id: Uuid,
38 account_id: Uuid,
39 parent: Option<Uuid>,
40) -> Result<(), CmdError> {
41 let mut tx = crate::tag::lock::begin(conn).await?;
42 lock_hierarchy(&mut tx, user_id).await?;
43 move_account(&mut tx, account_id, parent).await?;
44 tx.commit().await?;
45 Ok(())
46}
47
48pub(super) async fn move_account(
51 conn: &mut PgConnection,
52 account_id: Uuid,
53 parent: Option<Uuid>,
54) -> Result<(), CmdError> {
55 lock_rows(conn, account_id, parent).await?;
56 if let Some(parent) = parent {
57 refuse_cycle(conn, account_id, parent).await?;
58 }
59 sqlx::query_file!("sql/update/accounts/set_parent.sql", account_id, parent)
60 .execute(conn)
61 .await?;
62 Ok(())
63}
64
65async fn lock_rows(
67 conn: &mut PgConnection,
68 account_id: Uuid,
69 parent: Option<Uuid>,
70) -> Result<(), CmdError> {
71 let mut ids: Vec<Uuid> = std::iter::once(account_id).chain(parent).collect();
72 ids.sort();
73 for id in ids {
74 let row = sqlx::query_file!("sql/select/accounts/by_id_locked.sql", id)
75 .fetch_optional(&mut *conn)
76 .await?;
77 if row.is_none() {
78 return Err(CmdError::NotFound(format!("Account {id} not found")));
79 }
80 }
81 Ok(())
82}
83
84async fn refuse_cycle(
85 conn: &mut PgConnection,
86 account_id: Uuid,
87 parent: Uuid,
88) -> Result<(), CmdError> {
89 let cyclic = parent == account_id
90 || sqlx::query_file!("sql/select/accounts/is_descendant.sql", parent, account_id)
91 .fetch_one(conn)
92 .await?
93 .is_descendant
94 .unwrap_or(false);
95 match cyclic {
96 true => Err(CmdError::Refused(CYCLE_REFUSED.to_string())),
97 false => Ok(()),
98 }
99}