1
use finance::tag::Tag;
2
use scripting::runtime::{alloc_entity_via_export, alloc_pair_chain, alloc_string_ref};
3
#[cfg(test)]
4
use server::command::CommodityInfo;
5
use server::command::account::{GetAccount, GetAccountCommodities, GetAccountForManage};
6
use server::command::{CmdError, CmdResult, FinanceEntity};
7
use uuid::Uuid;
8
use wasmtime::{AnyRef, Caller, Rooted, StructRef, Val};
9

            
10
use crate::host_failure::cmd_failure;
11
use crate::lookup_log::LookupKind;
12
use crate::natives::args::{args_error, required, uuid_arg};
13
use crate::resolve::{Directory, ResolveError};
14
use crate::session::SessionData;
15

            
16
pub(super) type AccountEntry = (String, Option<String>, Option<String>, Option<String>);
17

            
18
16062
pub(super) async fn run_get_account(
19
16062
    caller: &mut Caller<'_, SessionData>,
20
16062
    user_id: Uuid,
21
16062
    key_arg: Option<String>,
22
16062
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
23
16062
    let key = validate_lookup_key("get-account", key_arg)?;
24
16062
    caller.data().ctx().record_lookup(LookupKind::Account, &key);
25
16062
    let id = match Uuid::parse_str(&key) {
26
1445
        Ok(id) => id,
27
14617
        Err(_) => match resolve_account_key(user_id, &key).await? {
28
13330
            Some(id) => id,
29
1284
            None => return Ok(None),
30
        },
31
    };
32
14775
    let result = GetAccount::new()
33
14775
        .user_id(user_id)
34
14775
        .account_id(id)
35
14775
        .run()
36
14775
        .await;
37
14775
    let entries = list_account_entries("get-account", result)?;
38
14775
    match entries.into_iter().next() {
39
        Some((id, name, parent, type_val)) => Ok(Some(
40
14614
            alloc_account_entity(
41
14614
                caller,
42
14614
                &id,
43
14614
                name.as_deref(),
44
14614
                parent.as_deref(),
45
14614
                type_val.as_deref(),
46
14614
            )
47
14614
            .await?,
48
        )),
49
161
        None => Ok(None),
50
    }
51
16062
}
52

            
53
14617
async fn resolve_account_key(user_id: Uuid, key: &str) -> wasmtime::Result<Option<Uuid>> {
54
14617
    let directory = Directory::load("get-account", user_id).await?;
55
14617
    match directory.account(key) {
56
13330
        Ok(id) => Ok(Some(id)),
57
        Err(ResolveError::AmbiguousAccount { candidates, .. }) => {
58
3
            let listed: Vec<String> = candidates
59
3
                .iter()
60
6
                .map(|id| format!("{} ({id})", directory.account_path(*id)))
61
                .collect();
62
3
            Err(args_error(format!(
63
3
                "get-account: name '{key}' is ambiguous ({} accounts); use one of: {}",
64
3
                listed.len(),
65
3
                listed.join(", ")
66
3
            )))
67
        }
68
1284
        Err(_) => Ok(None),
69
    }
70
14617
}
71

            
72
16064
pub(super) fn validate_lookup_key(name: &str, key_arg: Option<String>) -> wasmtime::Result<String> {
73
16064
    required(name, "lookup-key", key_arg)
74
16064
}
75

            
76
320
pub(super) async fn run_get_account_for_manage(
77
320
    caller: &mut Caller<'_, SessionData>,
78
320
    user_id: Uuid,
79
320
    id_arg: Option<String>,
80
320
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
81
320
    let account_id = parse_get_account_for_manage_id(id_arg)?;
82
320
    let result = GetAccountForManage::new()
83
320
        .user_id(user_id)
84
320
        .account_id(account_id)
85
320
        .run()
86
320
        .await;
87
320
    let entries = list_account_entries("get-account-for-manage", result)?;
88
320
    match entries.into_iter().next() {
89
        Some((id, name, parent, type_val)) => Ok(Some(
90
160
            alloc_account_entity(
91
160
                caller,
92
160
                &id,
93
160
                name.as_deref(),
94
160
                parent.as_deref(),
95
160
                type_val.as_deref(),
96
160
            )
97
160
            .await?,
98
        )),
99
160
        None => Ok(None),
100
    }
101
320
}
102

            
103
322
pub(super) fn parse_get_account_for_manage_id(id_arg: Option<String>) -> wasmtime::Result<Uuid> {
104
322
    uuid_arg("get-account-for-manage", "account-id", id_arg)
105
322
}
106

            
107
160
pub(super) async fn run_get_account_commodities(
108
160
    caller: &mut Caller<'_, SessionData>,
109
160
    user_id: Uuid,
110
160
    id_arg: Option<String>,
111
160
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
112
160
    let account_id = parse_account_commodities_id(id_arg)?;
113
160
    let result = GetAccountCommodities::new()
114
160
        .user_id(user_id)
115
160
        .account_id(account_id)
116
160
        .run()
117
160
        .await;
118
160
    let items = match result {
119
160
        Ok(Some(CmdResult::CommodityInfoList(items))) => items,
120
        Ok(Some(other)) => {
121
            return Err(wasmtime::Error::msg(format!(
122
                "get-account-commodities: expected CommodityInfoList, got {other:?}"
123
            )));
124
        }
125
        Ok(None) => Vec::new(),
126
        Err(err) => return Err(cmd_failure("get-account-commodities", err)),
127
    };
128
160
    let mut anyrefs: Vec<Option<Rooted<AnyRef>>> = Vec::with_capacity(items.len());
129
160
    for info in items {
130
        let id_ref = alloc_string_ref(caller, info.commodity_id.to_string().as_bytes())?;
131
        let symbol_ref = alloc_string_ref(caller, info.symbol.as_bytes())?;
132
        let name_ref = alloc_string_ref(caller, info.name.as_bytes())?;
133
        let args = [
134
            Val::AnyRef(Some(id_ref.to_anyref())),
135
            Val::AnyRef(Some(symbol_ref.to_anyref())),
136
            Val::AnyRef(Some(name_ref.to_anyref())),
137
        ];
138
        let entity_ref = alloc_entity_via_export(caller, "alloc_commodity_entity", &args).await?;
139
        anyrefs.push(Some(entity_ref.to_anyref()));
140
    }
141
160
    alloc_pair_chain(caller, anyrefs).await
142
160
}
143

            
144
162
pub(super) fn parse_account_commodities_id(id_arg: Option<String>) -> wasmtime::Result<Uuid> {
145
162
    uuid_arg("get-account-commodities", "account-id", id_arg)
146
162
}
147

            
148
17496
pub(super) fn list_account_entries(
149
17496
    name: &str,
150
17496
    result: Result<Option<CmdResult>, CmdError>,
151
17496
) -> wasmtime::Result<Vec<AccountEntry>> {
152
17496
    match result {
153
17496
        Ok(Some(CmdResult::TaggedEntities { entities, .. })) => Ok(entities
154
17496
            .into_iter()
155
25815
            .filter_map(|(entity, tags)| match entity {
156
                FinanceEntity::Account(a) => Some((
157
25815
                    a.id.to_string(),
158
25815
                    tag_value_str(&tags, "name"),
159
25815
                    a.parent.map(|u| u.to_string()),
160
25815
                    tag_value_str(&tags, "type"),
161
                )),
162
                _ => None,
163
25815
            })
164
            .collect()),
165
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
166
            "{name}: expected TaggedEntities, got {other:?}"
167
        ))),
168
        Ok(None) => Ok(Vec::new()),
169
        Err(err) => Err(cmd_failure(name, err)),
170
    }
171
17496
}
172

            
173
51630
pub(super) fn tag_value_str(
174
51630
    tags: &std::collections::HashMap<String, FinanceEntity>,
175
51630
    key: &str,
176
51630
) -> Option<String> {
177
51630
    tags.get(key).and_then(|t| match t {
178
25815
        FinanceEntity::Tag(Tag { tag_value, .. }) => Some(tag_value.clone()),
179
        _ => None,
180
25815
    })
181
51630
}
182

            
183
25814
pub(super) async fn alloc_account_entity(
184
25814
    caller: &mut Caller<'_, SessionData>,
185
25814
    id: &str,
186
25814
    name: Option<&str>,
187
25814
    parent: Option<&str>,
188
25814
    type_val: Option<&str>,
189
25814
) -> wasmtime::Result<Rooted<StructRef>> {
190
25814
    let id_ref = alloc_string_ref(caller, id.as_bytes())?;
191
25814
    let name_ref = name
192
25814
        .map(|s| alloc_string_ref(caller, s.as_bytes()))
193
        .transpose()?;
194
25814
    let parent_ref = parent
195
490
        .map(|s| alloc_string_ref(caller, s.as_bytes()))
196
        .transpose()?;
197
25814
    let type_ref = type_val
198
        .map(|s| alloc_string_ref(caller, s.as_bytes()))
199
        .transpose()?;
200
    let args = [
201
25814
        Val::AnyRef(Some(id_ref.to_anyref())),
202
25814
        Val::AnyRef(name_ref.map(|r| r.to_anyref())),
203
25814
        Val::AnyRef(parent_ref.map(|r| r.to_anyref())),
204
25814
        Val::AnyRef(type_ref.map(|r| r.to_anyref())),
205
    ];
206
25814
    alloc_entity_via_export(caller, "alloc_account", &args).await
207
25814
}
208

            
209
2400
pub(super) async fn alloc_account_chain(
210
2400
    caller: &mut Caller<'_, SessionData>,
211
2400
    entries: Vec<AccountEntry>,
212
2400
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
213
2400
    let mut anyrefs: Vec<Option<Rooted<AnyRef>>> = Vec::with_capacity(entries.len());
214
2400
    for (id, name, parent, type_val) in entries {
215
11040
        let entity_ref = alloc_account_entity(
216
11040
            caller,
217
11040
            &id,
218
11040
            name.as_deref(),
219
11040
            parent.as_deref(),
220
11040
            type_val.as_deref(),
221
11040
        )
222
11040
        .await?;
223
11040
        anyrefs.push(Some(entity_ref.to_anyref()));
224
    }
225
2400
    alloc_pair_chain(caller, anyrefs).await
226
2400
}
227

            
228
#[cfg(test)]
229
3
pub(super) fn format_manage_tree(
230
3
    entities: &[(
231
3
        FinanceEntity,
232
3
        std::collections::HashMap<String, FinanceEntity>,
233
3
    )],
234
3
) -> String {
235
3
    let mut out = String::from("(:accounts-tree (");
236
3
    for (idx, (entity, tags)) in entities.iter().enumerate() {
237
2
        if idx > 0 {
238
            out.push(' ');
239
2
        }
240
2
        match entity {
241
            FinanceEntity::Account(account) => {
242
2
                let parent = match account.parent {
243
1
                    Some(p) => format!("\"{p}\""),
244
1
                    None => "nil".to_string(),
245
                };
246
2
                out.push_str(&format!("(:id \"{}\" :parent-id {}", account.id, parent));
247
2
                if let Some(name) = tags.get("name").and_then(|t| match t {
248
1
                    FinanceEntity::Tag(Tag { tag_value, .. }) => Some(tag_value.as_str()),
249
                    _ => None,
250
1
                }) {
251
1
                    out.push_str(&format!(" :name {}", super::quote_string(name)));
252
1
                }
253
2
                out.push(')');
254
            }
255
            other => {
256
                out.push_str(&format!("(:error \"unexpected entity {other:?}\")"));
257
            }
258
        }
259
    }
260
3
    out.push_str("))");
261
3
    out
262
3
}
263

            
264
#[cfg(test)]
265
4
pub(super) fn format_tagged_entities(
266
4
    entities: &[(
267
4
        FinanceEntity,
268
4
        std::collections::HashMap<String, FinanceEntity>,
269
4
    )],
270
4
) -> String {
271
4
    let mut out = String::from("(:accounts (");
272
4
    for (idx, (entity, tags)) in entities.iter().enumerate() {
273
3
        if idx > 0 {
274
            out.push(' ');
275
3
        }
276
3
        let id = match entity {
277
3
            FinanceEntity::Account(a) => a.id,
278
            other => {
279
                out.push_str(&format!("(:error \"unexpected entity {other:?}\")"));
280
                continue;
281
            }
282
        };
283
3
        let name = tags.get("name").and_then(|t| match t {
284
2
            FinanceEntity::Tag(Tag { tag_value, .. }) => Some(tag_value.as_str()),
285
            _ => None,
286
2
        });
287
3
        out.push_str(&format!("(:id \"{id}\""));
288
3
        if let Some(name) = name {
289
2
            out.push_str(&format!(" :name {}", super::quote_string(name)));
290
1
        }
291
3
        out.push(')');
292
    }
293
4
    out.push_str("))");
294
4
    out
295
4
}
296

            
297
#[cfg(test)]
298
2
pub(super) fn format_commodity_info_list(items: &[CommodityInfo]) -> String {
299
2
    let mut out = String::from("(:account-commodities (");
300
2
    for (idx, info) in items.iter().enumerate() {
301
2
        if idx > 0 {
302
1
            out.push(' ');
303
1
        }
304
2
        out.push_str(&format!(
305
2
            "(:commodity-id \"{}\" :symbol {} :name {})",
306
2
            info.commodity_id,
307
2
            super::quote_string(&info.symbol),
308
2
            super::quote_string(&info.name),
309
2
        ));
310
    }
311
2
    out.push_str("))");
312
2
    out
313
2
}