1
use super::account::{CreateAccount, GetBalance, SetAccountTag};
2
use super::account_merge::{MergeAccounts, PreviewMergeAccounts};
3
use super::commodity::CreateCommodity;
4
use super::transaction::CreateTransaction;
5
use super::{CmdError, CmdResult, FinanceEntity};
6
use crate::{db::install_test_pool, user::User};
7
use chrono::Utc;
8
use finance::{account::Account, split::Split};
9
use num_rational::Rational64;
10
use sqlx::PgPool;
11
use supp_macro::local_db_sqlx_test;
12
use tokio::sync::OnceCell;
13
use uuid::Uuid;
14

            
15
mod balances;
16
mod gone;
17
mod kept;
18
mod moves;
19
mod previews;
20
mod pure;
21
mod refusals;
22

            
23
static USER: OnceCell<User> = OnceCell::const_new();
24

            
25
17
async fn setup() {
26
34
    USER.get_or_init(|| async { User { id: Uuid::new_v4() } })
27
17
        .await;
28
17
}
29

            
30
type SplitFacts = (
31
    Uuid,
32
    Option<bool>,
33
    Option<chrono::DateTime<Utc>>,
34
    Option<Uuid>,
35
);
36

            
37
struct Fixture {
38
    user: &'static User,
39
    commodity: Uuid,
40
}
41

            
42
17
async fn fixture() -> anyhow::Result<Fixture> {
43
17
    let user = USER.get().ok_or_else(|| anyhow::anyhow!("no user"))?;
44
17
    user.commit().await?;
45
17
    let Some(CmdResult::String(id)) = CreateCommodity::new()
46
17
        .symbol("TST".to_string())
47
17
        .name("Test".to_string())
48
17
        .user_id(user.id)
49
17
        .run()
50
17
        .await?
51
    else {
52
        anyhow::bail!("commodity");
53
    };
54
    Ok(Fixture {
55
17
        user,
56
17
        commodity: Uuid::parse_str(&id)?,
57
    })
58
17
}
59

            
60
impl Fixture {
61
42
    async fn account(&self, name: &str, parent: Option<Uuid>) -> anyhow::Result<Uuid> {
62
42
        let mut cmd = CreateAccount::new()
63
42
            .name(name.to_string())
64
42
            .user_id(self.user.id);
65
42
        if let Some(parent) = parent {
66
4
            cmd = cmd.parent(parent);
67
38
        }
68
42
        match cmd.run().await? {
69
42
            Some(CmdResult::Entity(FinanceEntity::Account(account))) => Ok(account.id),
70
            other => anyhow::bail!("unexpected CreateAccount result {other:?}"),
71
        }
72
42
    }
73

            
74
12
    async fn transfer(&self, from: Uuid, to: Uuid, amount: i64) -> anyhow::Result<Uuid> {
75
12
        let tx_id = Uuid::new_v4();
76
12
        let splits = [(from, -amount), (to, amount)]
77
12
            .into_iter()
78
24
            .map(|(account_id, value_num)| {
79
24
                FinanceEntity::Split(Split {
80
24
                    id: Uuid::new_v4(),
81
24
                    tx_id,
82
24
                    account_id,
83
24
                    commodity_id: self.commodity,
84
24
                    value_num,
85
24
                    value_denom: 1,
86
24
                    reconcile_state: None,
87
24
                    reconcile_date: None,
88
24
                    lot_id: None,
89
24
                })
90
24
            })
91
            .collect();
92
12
        let now = Utc::now();
93
12
        CreateTransaction::new()
94
12
            .user_id(self.user.id)
95
12
            .splits(splits)
96
12
            .id(tx_id)
97
12
            .post_date(now)
98
12
            .enter_date(now)
99
12
            .run()
100
12
            .await?;
101
12
        Ok(tx_id)
102
12
    }
103

            
104
14
    async fn merge(&self, into: Uuid, from: Uuid) -> Result<Option<CmdResult>, CmdError> {
105
14
        MergeAccounts::new()
106
14
            .user_id(self.user.id)
107
14
            .into(into)
108
14
            .from(from)
109
14
            .run()
110
14
            .await
111
14
    }
112

            
113
8
    async fn tag(&self, account: Uuid, name: &str, value: &str) -> anyhow::Result<()> {
114
8
        SetAccountTag::new()
115
8
            .user_id(self.user.id)
116
8
            .account_id(account)
117
8
            .tag_name(name.to_string())
118
8
            .tag_value(value.to_string())
119
8
            .run()
120
8
            .await?;
121
8
        Ok(())
122
8
    }
123

            
124
7
    async fn tags(&self, account: Uuid) -> anyhow::Result<Vec<(String, String)>> {
125
7
        let mut pairs: Vec<_> = self
126
7
            .user
127
7
            .get_account_tags(&Account {
128
7
                id: account,
129
7
                parent: None,
130
7
            })
131
7
            .await?
132
            .into_iter()
133
12
            .map(|tag| (tag.tag_name, tag.tag_value))
134
            .collect();
135
7
        pairs.sort();
136
7
        Ok(pairs)
137
7
    }
138

            
139
7
    async fn balance(&self, account: Uuid) -> anyhow::Result<Rational64> {
140
7
        match GetBalance::new()
141
7
            .user_id(self.user.id)
142
7
            .account_id(account)
143
7
            .run()
144
7
            .await?
145
        {
146
7
            Some(CmdResult::Rational(balance)) => Ok(balance),
147
            other => anyhow::bail!("unexpected GetBalance result {other:?}"),
148
        }
149
7
    }
150

            
151
9
    async fn split_count(&self, account: Uuid) -> anyhow::Result<i64> {
152
9
        self.referencing("splits", "account_id", account).await
153
9
    }
154

            
155
5
    async fn preview(&self, into: Uuid, from: Uuid) -> Result<Option<CmdResult>, CmdError> {
156
5
        PreviewMergeAccounts::new()
157
5
            .user_id(self.user.id)
158
5
            .into(into)
159
5
            .from(from)
160
5
            .run()
161
5
            .await
162
5
    }
163

            
164
    /// `(split id, reconcile state, reconcile date, lot)` of the account's
165
    /// splits, sorted.
166
2
    async fn split_facts(&self, account: Uuid) -> anyhow::Result<Vec<SplitFacts>> {
167
2
        let mut conn = self.user.get_connection().await?;
168
2
        let mut facts: Vec<SplitFacts> = sqlx::query_as(
169
2
            "SELECT id, reconcile_state, reconcile_date, lot_id FROM splits WHERE account_id = $1",
170
2
        )
171
2
        .bind(account)
172
2
        .fetch_all(&mut *conn)
173
2
        .await?;
174
2
        facts.sort_by_key(|fact| fact.0);
175
2
        Ok(facts)
176
2
    }
177

            
178
10
    async fn exists(&self, account: Uuid) -> anyhow::Result<bool> {
179
10
        let mut conn = self.user.get_connection().await?;
180
10
        Ok(sqlx::query("SELECT 1 FROM accounts WHERE id = $1")
181
10
            .bind(account)
182
10
            .fetch_optional(&mut *conn)
183
10
            .await?
184
            .is_some())
185
10
    }
186

            
187
    /// How many rows of `table` reference `account` through `key`.
188
22
    async fn referencing(
189
22
        &self,
190
22
        table: &'static str,
191
22
        key: &'static str,
192
22
        account: Uuid,
193
22
    ) -> anyhow::Result<i64> {
194
22
        let mut conn = self.user.get_connection().await?;
195
22
        let query = format!("SELECT count(*) FROM {table} WHERE {key} = $1");
196
22
        Ok(sqlx::query_scalar(sqlx::AssertSqlSafe(query))
197
22
            .bind(account)
198
22
            .fetch_one(&mut *conn)
199
22
            .await?)
200
22
    }
201

            
202
12
    async fn execute(&self, sql: &'static str, ids: &[Uuid]) -> anyhow::Result<()> {
203
12
        let mut conn = self.user.get_connection().await?;
204
12
        let mut query = sqlx::query(sql);
205
12
        for id in ids {
206
17
            query = query.bind(*id);
207
        }
208
12
        query.execute(&mut *conn).await?;
209
12
        Ok(())
210
12
    }
211

            
212
2
    async fn add_lot(&self, account: Uuid) -> anyhow::Result<()> {
213
2
        self.execute(
214
2
            "INSERT INTO lots (id, account_id, is_closed) VALUES (gen_random_uuid(), $1, 0)",
215
2
            &[account],
216
2
        )
217
2
        .await
218
2
    }
219

            
220
3
    async fn add_budget(&self) -> anyhow::Result<Uuid> {
221
3
        let budget = Uuid::new_v4();
222
3
        self.execute(
223
3
            "INSERT INTO budgets (id, periods) VALUES ($1, 12)",
224
3
            &[budget],
225
3
        )
226
3
        .await?;
227
3
        Ok(budget)
228
3
    }
229

            
230
5
    async fn add_budget_amount(&self, budget: Uuid, account: Uuid) -> anyhow::Result<()> {
231
5
        self.execute(
232
5
            "INSERT INTO budget_amounts (budget_id, account_id, period_num, amount_num, amount_denom)
233
5
             VALUES ($1, $2, 1, 100, 1)",
234
5
            &[budget, account],
235
5
        )
236
5
        .await
237
5
    }
238

            
239
1
    async fn add_book(&self, root: Uuid) -> anyhow::Result<()> {
240
1
        self.execute(
241
1
            "INSERT INTO books (id, root_account_id) VALUES (gen_random_uuid(), $1)",
242
1
            &[root],
243
1
        )
244
1
        .await
245
1
    }
246
}
247

            
248
8
fn pair(name: &str, value: &str) -> (String, String) {
249
8
    (name.to_string(), value.to_string())
250
8
}
251

            
252
10
fn refusal(result: Result<Option<CmdResult>, CmdError>) -> String {
253
10
    match result {
254
10
        Err(CmdError::Refused(message) | CmdError::NotFound(message)) => message,
255
        other => format!("not a refusal: {other:?}"),
256
    }
257
10
}