1
//! Account and commodity resolution shared by the logical natives and the
2
//! form path: a user's own entity UUID for submits, plus the name lookups.
3

            
4
use std::collections::HashMap;
5
use std::fmt;
6

            
7
use finance::tag::Tag;
8
use server::command::account::ListAccounts;
9
use server::command::commodity::ListCommodities;
10
use server::command::{CmdResult, FinanceEntity};
11
use uuid::Uuid;
12

            
13
use crate::host_failure::cmd_failure;
14

            
15
pub(crate) mod class;
16
pub(crate) mod options;
17

            
18
type Entry = (Uuid, Option<String>);
19

            
20
/// The user's accounts (by `name` tag) and commodities (by `symbol` tag).
21
pub(crate) struct Directory {
22
    accounts: Vec<Entry>,
23
    /// Accounts by their `:`-joined parent path, the label clients show.
24
    account_paths: Vec<Entry>,
25
    commodities: Vec<Entry>,
26
    parents: HashMap<Uuid, Uuid>,
27
}
28

            
29
#[derive(Debug, Clone, PartialEq, Eq)]
30
pub(crate) enum ResolveError {
31
    UnknownAccount(String),
32
    AmbiguousAccount { key: String, candidates: Vec<Uuid> },
33
    UnknownCommodity(String),
34
    AmbiguousCommodity(String),
35
}
36

            
37
impl fmt::Display for ResolveError {
38
1190
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39
1190
        match self {
40
1007
            Self::UnknownAccount(key) => write!(f, "unknown account '{key}'"),
41
            Self::AmbiguousAccount { key, candidates } => {
42
                let total = candidates.len();
43
                write!(f, "ambiguous account name '{key}' ({total} matches)")
44
            }
45
183
            Self::UnknownCommodity(key) => write!(f, "unknown commodity '{key}'"),
46
            Self::AmbiguousCommodity(key) => {
47
                write!(f, "symbol '{key}' is ambiguous; reference by uuid")
48
            }
49
        }
50
1190
    }
51
}
52

            
53
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54
pub(crate) enum RowField {
55
    From,
56
    To,
57
    FromCommodity,
58
    ToCommodity,
59
}
60

            
61
impl RowField {
62
1000
    pub(crate) fn key(self) -> &'static str {
63
1000
        match self {
64
653
            Self::From => "from",
65
171
            Self::To => "to",
66
171
            Self::FromCommodity => "from-commodity",
67
5
            Self::ToCommodity => "to-commodity",
68
        }
69
1000
    }
70
}
71

            
72
pub(crate) struct RowKeys<'a> {
73
    pub(crate) from: &'a str,
74
    pub(crate) to: &'a str,
75
    pub(crate) from_commodity: &'a str,
76
    /// `None` means the same commodity as `from_commodity`.
77
    pub(crate) to_commodity: Option<&'a str>,
78
}
79

            
80
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81
pub(crate) struct ResolvedIds {
82
    pub(crate) from: Uuid,
83
    pub(crate) to: Uuid,
84
    pub(crate) from_commodity: Uuid,
85
    pub(crate) to_commodity: Uuid,
86
}
87

            
88
pub(crate) type FieldFault = (RowField, ResolveError);
89

            
90
enum Pick {
91
    One(Uuid),
92
    Missing,
93
    Many(Vec<Uuid>),
94
}
95

            
96
15966
fn pick(entries: &[Entry], key: &str, same_name: fn(&str, &str) -> bool) -> Pick {
97
15966
    if let Ok(id) = Uuid::parse_str(key)
98
15
        && entries.iter().any(|(entry, _)| *entry == id)
99
    {
100
5
        return Pick::One(id);
101
15961
    }
102
15961
    let hits: Vec<Uuid> = entries
103
15961
        .iter()
104
25699
        .filter(|(_, name)| name.as_deref().is_some_and(|name| same_name(name, key)))
105
13372
        .map(|(id, _)| *id)
106
        .collect();
107
15961
    match hits.as_slice() {
108
2598
        [] => Pick::Missing,
109
13354
        [id] => Pick::One(*id),
110
9
        _ => Pick::Many(hits),
111
    }
112
15966
}
113

            
114
180189
fn own_id(entries: &[Entry], key: &str) -> Option<Uuid> {
115
180189
    let id = Uuid::parse_str(key).ok()?;
116
265634
    entries.iter().any(|(entry, _)| *entry == id).then_some(id)
117
180189
}
118

            
119
impl Directory {
120
204273
    pub(crate) async fn load(ctx: &str, user_id: Uuid) -> wasmtime::Result<Self> {
121
204273
        let accounts = ListAccounts::new()
122
204273
            .user_id(user_id)
123
204273
            .run()
124
204273
            .await
125
321
            .map_err(|err| cmd_failure(format!("{ctx}: account lookup failed"), err))?;
126
203952
        let commodities = ListCommodities::new()
127
203952
            .user_id(user_id)
128
203952
            .run()
129
203952
            .await
130
            .map_err(|err| cmd_failure(format!("{ctx}: commodity lookup failed"), err))?;
131
203952
        let parents = parent_links(accounts.as_ref());
132
        let mut directory = Self {
133
203952
            parents,
134
203952
            accounts: named_entries(ctx, accounts, "name")?,
135
203952
            account_paths: Vec::new(),
136
203952
            commodities: named_entries(ctx, commodities, "symbol")?,
137
        };
138
203952
        directory.account_paths = directory
139
203952
            .accounts
140
203952
            .iter()
141
402314
            .map(|(id, _)| (*id, Some(directory.account_path(*id))))
142
            .collect();
143
203952
        Ok(directory)
144
204273
    }
145

            
146
    /// An own account by UUID, then by unique full path, then by unique name.
147
14619
    pub(crate) fn account(&self, key: &str) -> Result<Uuid, ResolveError> {
148
25500
        let same = |name: &str, key: &str| name == key;
149
14619
        let found = match pick(&self.account_paths, key, same) {
150
1291
            Pick::Missing => pick(&self.accounts, key, same),
151
13328
            other => other,
152
        };
153
14619
        match found {
154
13332
            Pick::One(id) => Ok(id),
155
1284
            Pick::Missing => Err(ResolveError::UnknownAccount(key.to_string())),
156
3
            Pick::Many(candidates) => Err(ResolveError::AmbiguousAccount {
157
3
                key: key.to_string(),
158
3
                candidates,
159
3
            }),
160
        }
161
14619
    }
162

            
163
    /// The UUID of one of the user's own accounts; names are not accepted.
164
107581
    pub(crate) fn own_account(&self, key: &str) -> Result<Uuid, ResolveError> {
165
107581
        own_id(&self.accounts, key).ok_or_else(|| ResolveError::UnknownAccount(key.to_string()))
166
107581
    }
167

            
168
    /// The UUID of one of the user's own commodities; symbols are not accepted.
169
72608
    pub(crate) fn own_commodity(&self, key: &str) -> Result<Uuid, ResolveError> {
170
72608
        own_id(&self.commodities, key)
171
184
            .ok_or_else(|| ResolveError::UnknownCommodity(key.to_string()))
172
72608
    }
173

            
174
2
    pub(crate) fn commodity(&self, key: &str) -> Result<Uuid, ResolveError> {
175
2
        match pick(&self.commodities, key, str::eq_ignore_ascii_case) {
176
2
            Pick::One(id) => Ok(id),
177
            Pick::Missing => Err(ResolveError::UnknownCommodity(key.to_string())),
178
            Pick::Many(_) => Err(ResolveError::AmbiguousCommodity(key.to_string())),
179
        }
180
2
    }
181

            
182
    /// Resolve every UUID of a row; all failures are returned, in field order.
183
51766
    pub(crate) fn resolve_row(&self, keys: &RowKeys<'_>) -> Result<ResolvedIds, Vec<FieldFault>> {
184
1009
        let tag = |field| move |err| (field, err);
185
51766
        let from = self.own_account(keys.from).map_err(tag(RowField::From));
186
51766
        let to = self.own_account(keys.to).map_err(tag(RowField::To));
187
51766
        let from_commodity = self
188
51766
            .own_commodity(keys.from_commodity)
189
51766
            .map_err(tag(RowField::FromCommodity));
190
51766
        let to_commodity = match (keys.to_commodity, &from_commodity) {
191
17768
            (Some(key), _) => Some(self.own_commodity(key).map_err(tag(RowField::ToCommodity))),
192
33828
            (None, Ok(id)) => Some(Ok(*id)),
193
170
            (None, Err(_)) => None,
194
        };
195
51766
        match (from, to, from_commodity, to_commodity) {
196
51091
            (Ok(from), Ok(to), Ok(from_commodity), Some(Ok(to_commodity))) => Ok(ResolvedIds {
197
51091
                from,
198
51091
                to,
199
51091
                from_commodity,
200
51091
                to_commodity,
201
51091
            }),
202
675
            (from, to, from_commodity, to_commodity) => Err([from, to, from_commodity]
203
675
                .into_iter()
204
675
                .chain(to_commodity)
205
675
                .filter_map(Result::err)
206
675
                .collect()),
207
        }
208
51766
    }
209
}
210

            
211
203952
fn parent_links(result: Option<&CmdResult>) -> HashMap<Uuid, Uuid> {
212
203952
    let Some(CmdResult::TaggedEntities { entities, .. }) = result else {
213
        return HashMap::new();
214
    };
215
203952
    entities
216
203952
        .iter()
217
402314
        .filter_map(|(entity, _)| match entity {
218
402314
            FinanceEntity::Account(a) => a.parent.map(|parent| (a.id, parent)),
219
            _ => None,
220
402314
        })
221
        .collect()
222
203952
}
223

            
224
407904
fn named_entries(
225
407904
    ctx: &str,
226
407904
    result: Option<CmdResult>,
227
407904
    tag_name: &str,
228
407904
) -> wasmtime::Result<Vec<Entry>> {
229
407904
    match result {
230
407904
        Some(CmdResult::TaggedEntities { entities, .. }) => Ok(entities
231
407904
            .into_iter()
232
712459
            .filter_map(|(entity, tags)| {
233
712459
                let id = match entity {
234
402314
                    FinanceEntity::Account(a) => a.id,
235
310145
                    FinanceEntity::Commodity(c) => c.id,
236
                    _ => return None,
237
                };
238
712459
                let name = tags.get(tag_name).and_then(|t| match t {
239
712459
                    FinanceEntity::Tag(Tag { tag_value, .. }) => Some(tag_value.clone()),
240
                    _ => None,
241
712459
                });
242
712459
                Some((id, name))
243
712459
            })
244
            .collect()),
245
        Some(other) => Err(wasmtime::Error::msg(format!(
246
            "{ctx}: unexpected lookup result {other:?}"
247
        ))),
248
        None => Ok(Vec::new()),
249
    }
250
407904
}