1
use super::account::CreateAccount;
2
use super::account_merge::MergeAccounts;
3
use super::account_reparent::ReparentAccount;
4
use super::{CmdError, CmdResult, FinanceEntity};
5
use crate::{db::install_test_pool, hierarchy::lock_hierarchy, user::User};
6
use sqlx::PgPool;
7
use supp_macro::local_db_sqlx_test;
8
use tokio::sync::OnceCell;
9
use uuid::Uuid;
10

            
11
mod concurrency;
12
mod moves;
13
mod refusals;
14

            
15
static USER: OnceCell<User> = OnceCell::const_new();
16

            
17
10
async fn setup() {
18
20
    USER.get_or_init(|| async { User { id: Uuid::new_v4() } })
19
10
        .await;
20
10
}
21

            
22
struct Fixture {
23
    user: &'static User,
24
}
25

            
26
10
async fn fixture() -> anyhow::Result<Fixture> {
27
10
    let user = USER.get().ok_or_else(|| anyhow::anyhow!("no user"))?;
28
10
    user.commit().await?;
29
10
    Ok(Fixture { user })
30
10
}
31

            
32
impl Fixture {
33
20
    async fn account(&self, name: &str, parent: Option<Uuid>) -> anyhow::Result<Uuid> {
34
20
        let mut cmd = CreateAccount::new()
35
20
            .name(name.to_string())
36
20
            .user_id(self.user.id);
37
20
        if let Some(parent) = parent {
38
5
            cmd = cmd.parent(parent);
39
15
        }
40
20
        match cmd.run().await? {
41
20
            Some(CmdResult::Entity(FinanceEntity::Account(account))) => Ok(account.id),
42
            other => anyhow::bail!("unexpected CreateAccount result {other:?}"),
43
        }
44
20
    }
45

            
46
11
    async fn reparent(
47
11
        &self,
48
11
        account: Uuid,
49
11
        parent: Option<Uuid>,
50
11
    ) -> Result<Option<CmdResult>, CmdError> {
51
11
        let mut cmd = ReparentAccount::new()
52
11
            .user_id(self.user.id)
53
11
            .account_id(account);
54
11
        if let Some(parent) = parent {
55
10
            cmd = cmd.parent(parent);
56
1
        }
57
11
        cmd.run().await
58
11
    }
59

            
60
1
    async fn merge(&self, into: Uuid, from: Uuid) -> Result<Option<CmdResult>, CmdError> {
61
1
        MergeAccounts::new()
62
1
            .user_id(self.user.id)
63
1
            .into(into)
64
1
            .from(from)
65
1
            .run()
66
1
            .await
67
1
    }
68

            
69
    /// `None` when the account is gone, else its stored parent.
70
13
    async fn parent_of(&self, account: Uuid) -> anyhow::Result<Option<Option<Uuid>>> {
71
13
        let mut conn = self.user.get_connection().await?;
72
        Ok(
73
13
            sqlx::query_scalar("SELECT parent_id FROM accounts WHERE id = $1")
74
13
                .bind(account)
75
13
                .fetch_optional(&mut *conn)
76
13
                .await?,
77
        )
78
13
    }
79
}
80

            
81
4
fn is_refused(result: &Result<Option<CmdResult>, CmdError>) -> bool {
82
4
    matches!(result, Err(CmdError::Refused(_)))
83
4
}