1
use std::collections::HashMap;
2

            
3
use chrono::Utc;
4
use finance::split::Split;
5
use sqlx::PgPool;
6
use supp_macro::local_db_sqlx_test;
7
use tokio::sync::OnceCell;
8
use uuid::Uuid;
9

            
10
use super::ListAccountSingleCommodities;
11
use crate::command::account::CreateAccount;
12
use crate::command::commodity::CreateCommodity;
13
use crate::command::transaction::CreateTransaction;
14
use crate::command::{CmdResult, FinanceEntity};
15
use crate::db::install_test_pool;
16
use crate::user::User;
17

            
18
static USER: OnceCell<User> = OnceCell::const_new();
19

            
20
2
async fn setup() {
21
4
    USER.get_or_init(|| async { User { id: Uuid::new_v4() } })
22
2
        .await;
23
2
}
24

            
25
2
async fn user() -> anyhow::Result<&'static User> {
26
2
    let user = USER.get().ok_or_else(|| anyhow::anyhow!("no user"))?;
27
2
    user.commit().await?;
28
2
    Ok(user)
29
2
}
30

            
31
4
async fn commodity(user: &User, symbol: &str) -> anyhow::Result<Uuid> {
32
4
    let Some(CmdResult::String(id)) = CreateCommodity::new()
33
4
        .symbol(symbol.to_string())
34
4
        .name(symbol.to_string())
35
4
        .user_id(user.id)
36
4
        .run()
37
4
        .await?
38
    else {
39
        anyhow::bail!("commodity");
40
    };
41
4
    Ok(Uuid::parse_str(&id)?)
42
4
}
43

            
44
7
async fn account(user: &User, name: &str) -> anyhow::Result<Uuid> {
45
7
    let Some(CmdResult::Entity(FinanceEntity::Account(account))) = CreateAccount::new()
46
7
        .name(name.to_string())
47
7
        .user_id(user.id)
48
7
        .run()
49
7
        .await?
50
    else {
51
        anyhow::bail!("account");
52
    };
53
7
    Ok(account.id)
54
7
}
55

            
56
4
async fn transfer(user: &User, legs: [(Uuid, Uuid); 2]) -> anyhow::Result<()> {
57
4
    let tx_id = Uuid::new_v4();
58
4
    let now = Utc::now();
59
4
    let splits = legs
60
4
        .into_iter()
61
4
        .zip([-5, 5])
62
8
        .map(|((account_id, commodity_id), value_num)| {
63
8
            FinanceEntity::Split(Split {
64
8
                id: Uuid::new_v4(),
65
8
                tx_id,
66
8
                account_id,
67
8
                commodity_id,
68
8
                value_num,
69
8
                value_denom: 1,
70
8
                reconcile_state: None,
71
8
                reconcile_date: None,
72
8
                lot_id: None,
73
8
            })
74
8
        })
75
        .collect();
76
4
    CreateTransaction::new()
77
4
        .user_id(user.id)
78
4
        .splits(splits)
79
4
        .id(tx_id)
80
4
        .post_date(now)
81
4
        .enter_date(now)
82
4
        .run()
83
4
        .await?;
84
4
    Ok(())
85
4
}
86

            
87
2
async fn single_commodities(user: &User) -> anyhow::Result<HashMap<Uuid, Uuid>> {
88
2
    match ListAccountSingleCommodities::new()
89
2
        .user_id(user.id)
90
2
        .run()
91
2
        .await?
92
    {
93
2
        Some(CmdResult::SingleCommodities(held)) => Ok(held),
94
        other => anyhow::bail!("unexpected result: {other:?}"),
95
    }
96
2
}
97

            
98
#[local_db_sqlx_test]
99
async fn test_only_single_commodity_accounts_are_listed(pool: PgPool) -> Result<(), anyhow::Error> {
100
    let user = user().await?;
101
    let usd = commodity(user, "USD").await?;
102
    let eur = commodity(user, "EUR").await?;
103
    let wallet = account(user, "Wallet").await?;
104
    let cash = account(user, "Cash").await?;
105
    let food = account(user, "Food").await?;
106
    let idle = account(user, "Idle").await?;
107
    transfer(user, [(cash, usd), (wallet, usd)]).await?;
108
    transfer(user, [(cash, eur), (food, eur)]).await?;
109

            
110
    let held = single_commodities(user).await?;
111

            
112
    assert_eq!(
113
        held,
114
        HashMap::from([(wallet, usd), (food, eur)]),
115
        "cash holds two commodities and idle none"
116
    );
117
    assert!(!held.contains_key(&idle));
118
}
119

            
120
#[local_db_sqlx_test]
121
async fn test_a_commodity_without_a_name_tag_does_not_count(
122
    pool: PgPool,
123
) -> Result<(), anyhow::Error> {
124
    let user = user().await?;
125
    let usd = commodity(user, "USD").await?;
126
    let nameless = commodity(user, "NMS").await?;
127
    let wallet = account(user, "Wallet").await?;
128
    let mixed = account(user, "Mixed").await?;
129
    let other = account(user, "Other").await?;
130
    transfer(user, [(mixed, usd), (wallet, usd)]).await?;
131
    transfer(user, [(mixed, nameless), (other, nameless)]).await?;
132
    sqlx::query(
133
        "DELETE FROM commodity_tags WHERE commodity_id = $1 \
134
         AND tag_id IN (SELECT id FROM tags WHERE tag_name = 'name')",
135
    )
136
    .bind(nameless)
137
    .execute(&pool)
138
    .await?;
139

            
140
    let held = single_commodities(user).await?;
141

            
142
    assert_eq!(held.get(&mixed), Some(&usd));
143
    assert_eq!(held.get(&wallet), Some(&usd));
144
    assert!(!held.contains_key(&other));
145
}