1
use finance::commodity::Commodity;
2
use num_rational::Rational64;
3
use server::command::account::{GetAccountCommodities, GetBalance, ListAccounts};
4
use server::command::{CmdResult, CommodityInfo};
5
use uuid::Uuid;
6

            
7
use crate::host_failure::cmd_failure;
8
use crate::natives::args::{args_error, uuid_arg};
9

            
10
2403
pub(super) async fn resolve_balance(
11
2403
    user_id: Uuid,
12
2403
    id_arg: Option<String>,
13
2403
) -> wasmtime::Result<(i64, i64, Uuid)> {
14
2403
    let account_id = uuid_arg("account-balance", "account-id", id_arg)?;
15
2403
    let commodity_id = single_commodity_for(user_id, account_id).await?;
16
1921
    let (numer, denom) = single_rational_for(user_id, account_id, commodity_id).await?;
17
1921
    Ok((numer, denom, commodity_id))
18
2403
}
19

            
20
2403
async fn single_commodity_for(user_id: Uuid, account_id: Uuid) -> wasmtime::Result<Uuid> {
21
2403
    match GetAccountCommodities::new()
22
2403
        .user_id(user_id)
23
2403
        .account_id(account_id)
24
2403
        .run()
25
2403
        .await
26
    {
27
2403
        Ok(Some(CmdResult::CommodityInfoList(items))) => match items.as_slice() {
28
1921
            [info] => Ok(info.commodity_id),
29
481
            [] => Err(args_error(
30
481
                "account-balance: account has no commodity yet (no splits); cannot produce \
31
481
                 Commodity-typed value",
32
481
            )),
33
1
            _ => Err(args_error(
34
1
                "account-balance: account holds multiple commodities; use get-balances instead",
35
1
            )),
36
        },
37
        Ok(other) => Err(wasmtime::Error::msg(format!(
38
            "account-balance: expected CommodityInfoList, got {other:?}"
39
        ))),
40
        Err(err) => Err(cmd_failure("account-balance", err)),
41
    }
42
2403
}
43

            
44
1921
async fn single_rational_for(
45
1921
    user_id: Uuid,
46
1921
    account_id: Uuid,
47
1921
    commodity_id: Uuid,
48
1921
) -> wasmtime::Result<(i64, i64)> {
49
1921
    match GetBalance::new()
50
1921
        .user_id(user_id)
51
1921
        .account_id(account_id)
52
1921
        .commodity_id(commodity_id)
53
1921
        .run()
54
1921
        .await
55
    {
56
1921
        Ok(Some(CmdResult::Rational(r))) => Ok((*r.numer(), *r.denom())),
57
        Ok(None) => Ok((0, 1)),
58
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
59
            "account-balance: unexpected variant {other:?}"
60
        ))),
61
        Err(err) => Err(cmd_failure("account-balance", err)),
62
    }
63
1921
}
64

            
65
161
pub(super) async fn count_accounts(user_id: Uuid) -> wasmtime::Result<i32> {
66
161
    match ListAccounts::new().user_id(user_id).run().await {
67
160
        Ok(Some(CmdResult::TaggedEntities { entities, .. })) => i32::try_from(entities.len())
68
            .map_err(|_| wasmtime::Error::msg("account-count: too many accounts")),
69
        Ok(None) => Ok(0),
70
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
71
            "account-count: unexpected variant {other:?}"
72
        ))),
73
1
        Err(err) => Err(cmd_failure("account-count", err)),
74
    }
75
161
}
76

            
77
165
pub(super) async fn run_get_balance_single(
78
165
    user_id: Uuid,
79
165
    id_arg: Option<String>,
80
165
) -> wasmtime::Result<(i64, i64)> {
81
165
    let account_id = uuid_arg("get-balance", "account-id", id_arg)?;
82
161
    match GetBalance::new()
83
161
        .user_id(user_id)
84
161
        .account_id(account_id)
85
161
        .run()
86
161
        .await
87
    {
88
160
        Ok(Some(CmdResult::Rational(r))) => Ok((*r.numer(), *r.denom())),
89
1
        Ok(Some(CmdResult::MultiCurrencyBalance(_))) => Err(args_error(
90
1
            "get-balance: multi-currency account — use get-balances for the typed pair return",
91
1
        )),
92
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
93
            "get-balance: expected Rational, got {other:?}"
94
        ))),
95
        Ok(None) => Ok((0, 1)),
96
        Err(err) => Err(cmd_failure("get-balance", err)),
97
    }
98
165
}
99

            
100
1762
pub(super) async fn run_get_balances(
101
1762
    user_id: Uuid,
102
1762
    id_arg: Option<String>,
103
1762
) -> wasmtime::Result<Vec<String>> {
104
1762
    let account_id = uuid_arg("get-balances", "account-id", id_arg)?;
105
1600
    let infos = fetch_commodity_infos(user_id, account_id).await?;
106
1600
    if infos.is_empty() {
107
480
        return Ok(Vec::new());
108
1120
    }
109
1120
    let balance = GetBalance::new()
110
1120
        .user_id(user_id)
111
1120
        .account_id(account_id)
112
1120
        .run()
113
1120
        .await
114
        .map_err(|err| cmd_failure("get-balances", err))?;
115
1120
    match balance {
116
        None => Ok(Vec::new()),
117
        Some(CmdResult::Rational(r)) => {
118
960
            let info = infos.into_iter().next().ok_or_else(|| {
119
                wasmtime::Error::msg("get-balances: rational balance but no commodity info")
120
            })?;
121
960
            Ok(vec![format_balance_plist(
122
960
                &info.commodity_id.to_string(),
123
960
                &info.symbol,
124
960
                &info.name,
125
960
                *r.numer(),
126
960
                *r.denom(),
127
960
            )])
128
        }
129
        Some(CmdResult::MultiCurrencyBalance(pairs)) => {
130
160
            let result: Vec<String> = pairs
131
160
                .iter()
132
320
                .filter_map(|(commodity, r)| balance_plist_for(commodity, r, &infos))
133
                .collect();
134
160
            Ok(result)
135
        }
136
        Some(other) => Err(wasmtime::Error::msg(format!(
137
            "get-balances: unexpected variant {other:?}"
138
        ))),
139
    }
140
1762
}
141

            
142
320
fn balance_plist_for(
143
320
    commodity: &Commodity,
144
320
    r: &Rational64,
145
320
    infos: &[CommodityInfo],
146
320
) -> Option<String> {
147
480
    let info = infos.iter().find(|i| i.commodity_id == commodity.id)?;
148
320
    Some(format_balance_plist(
149
320
        &commodity.id.to_string(),
150
320
        &info.symbol,
151
320
        &info.name,
152
320
        *r.numer(),
153
320
        *r.denom(),
154
320
    ))
155
320
}
156

            
157
1600
async fn fetch_commodity_infos(
158
1600
    user_id: Uuid,
159
1600
    account_id: Uuid,
160
1600
) -> wasmtime::Result<Vec<CommodityInfo>> {
161
1600
    match GetAccountCommodities::new()
162
1600
        .user_id(user_id)
163
1600
        .account_id(account_id)
164
1600
        .run()
165
1600
        .await
166
    {
167
1600
        Ok(Some(CmdResult::CommodityInfoList(items))) => Ok(items),
168
        Ok(None) => Ok(Vec::new()),
169
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
170
            "get-balances: expected CommodityInfoList, got {other:?}"
171
        ))),
172
        Err(err) => Err(cmd_failure("get-balances", err)),
173
    }
174
1600
}
175

            
176
1280
fn format_balance_plist(id: &str, symbol: &str, name: &str, numer: i64, denom: i64) -> String {
177
1280
    format!(
178
        "(:commodity-id {} :symbol {} :name {} :value-num {} :value-denom {})",
179
1280
        super::quote_string(id),
180
1280
        super::quote_string(symbol),
181
1280
        super::quote_string(name),
182
1280
        numer,
183
1280
        denom,
184
    )
185
1280
}