1
//! Split-domain natives. Wraps `server::command::ListSplits`.
2
//!
3
//! `list-splits` returns a typed `pair<split>` of `$split` entity refs;
4
//! each carries id, account-id, commodity-id, and value (Ratio). The
5
//! `value_denom` ride alongside via the Ratio field. Notes / reconcile
6
//! state stay reachable from the underlying `Tag` rows but are not
7
//! surfaced on the typed entity yet — extend the `$split` shape +
8
//! `nomi_entity!` declaration to expose more fields.
9

            
10
use scripting::runtime::{
11
    alloc_entity_via_export, alloc_pair_chain, alloc_ratio_ref, alloc_string_ref, read_string_arg,
12
};
13
use server::command::split::{GetSplitTag, GetSplitTagValues, ListSplits, SetSplitTag};
14
use server::command::{CmdError, CmdResult};
15
use uuid::Uuid;
16
use wasmtime::{AnyRef, ArrayRef, Caller, Linker, Rooted, StructRef, Val};
17

            
18
use crate::host_failure::cmd_failure;
19
use crate::natives::args::{present, tag_name_arg, uuid_arg};
20
use crate::natives::native::register_native;
21
use crate::session::SessionData;
22

            
23
pub const REGISTERED_COMMANDS: &[&str] = &[
24
    "list-splits",
25
    "list-splits-by-transaction",
26
    "set-split-tag",
27
    "get-split-tag",
28
    "get-split-tags",
29
];
30

            
31
230200
pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
32
230200
    register_readonly(linker)?;
33
230200
    register_mutators(linker)?;
34
230200
    Ok(())
35
230200
}
36

            
37
236811
pub fn register_readonly(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
38
236811
    register_native(
39
236811
        linker,
40
236811
        "split_list_splits",
41
160
        |caller, (id_arg,): (Option<Rooted<wasmtime::ArrayRef>>,)| {
42
160
            Box::pin(async move {
43
160
                let user_id = caller.data().ctx().user_id;
44
160
                let id = read_string_arg(caller, id_arg)?;
45
160
                let account_id = parse_account_id_arg(id)?;
46
160
                let result = ListSplits::new()
47
160
                    .user_id(user_id)
48
160
                    .account(account_id)
49
160
                    .run()
50
160
                    .await;
51
160
                let entries = list_split_entries("list-splits", result)?;
52
160
                alloc_split_chain(caller, entries).await
53
160
            })
54
160
        },
55
    )?;
56
236811
    register_native(
57
236811
        linker,
58
236811
        "split_list_splits_by_transaction",
59
1120
        |caller, (id_arg,): (Option<Rooted<wasmtime::ArrayRef>>,)| {
60
1120
            Box::pin(async move {
61
1120
                let user_id = caller.data().ctx().user_id;
62
1120
                let id = read_string_arg(caller, id_arg)?;
63
1120
                let transaction_id = parse_transaction_id_arg(id)?;
64
1120
                let result = ListSplits::new()
65
1120
                    .user_id(user_id)
66
1120
                    .transaction(transaction_id)
67
1120
                    .run()
68
1120
                    .await;
69
1120
                let entries = list_split_entries("list-splits-by-transaction", result)?;
70
1120
                alloc_split_chain(caller, entries).await
71
1120
            })
72
1120
        },
73
    )?;
74
236811
    register_native(
75
236811
        linker,
76
236811
        "split_get_split_tag",
77
1120
        |caller, (id_arg, name_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
78
1120
            Box::pin(async move {
79
1120
                let user_id = caller.data().ctx().user_id;
80
1120
                let id = read_string_arg(caller, id_arg)?;
81
1120
                let name = read_string_arg(caller, name_arg)?;
82
1120
                let value = run_get_split_tag(user_id, id, name).await?;
83
1120
                Ok(Some(alloc_string_ref(caller, value.as_bytes())?))
84
1120
            })
85
1120
        },
86
    )?;
87
236811
    register_native(
88
236811
        linker,
89
236811
        "split_get_split_tags",
90
320
        |caller, (id_arg, name_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
91
320
            Box::pin(async move {
92
320
                let user_id = caller.data().ctx().user_id;
93
320
                let id = read_string_arg(caller, id_arg)?;
94
320
                let name = read_string_arg(caller, name_arg)?;
95
320
                let values = run_get_split_tags(user_id, id, name).await?;
96
320
                super::alloc_string_pair_chain(caller, values).await
97
320
            })
98
320
        },
99
    )?;
100
236811
    Ok(())
101
236811
}
102

            
103
230200
pub fn register_mutators(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
104
230200
    register_native(
105
230200
        linker,
106
230200
        "split_set_split_tag",
107
1280
        |caller, (id_arg, name_arg, value_arg): super::StringArgTriple| {
108
1280
            Box::pin(async move {
109
1280
                let user_id = caller.data().ctx().user_id;
110
1280
                let id = read_string_arg(caller, id_arg)?;
111
1280
                let name = read_string_arg(caller, name_arg)?;
112
1280
                let value = read_string_arg(caller, value_arg)?;
113
1280
                run_set_split_tag(user_id, id, name, value).await
114
1280
            })
115
1280
        },
116
    )?;
117
230200
    Ok(())
118
230200
}
119

            
120
/// `set-split-tag` upsert: either a fresh `(split, tag_name, tag_value)`
121
/// link or replace the existing value for that name. Returns 1 on
122
/// success; the i32 return matches `set-account-tag`'s shape so a
123
/// future error-cell migration only has to update one wire format.
124
1280
async fn run_set_split_tag(
125
1280
    user_id: Uuid,
126
1280
    id_arg: Option<String>,
127
1280
    name_arg: Option<String>,
128
1280
    value_arg: Option<String>,
129
1280
) -> wasmtime::Result<i32> {
130
1280
    let split_id = uuid_arg("set-split-tag", "split-id", id_arg)?;
131
1280
    let tag_name = tag_name_arg("set-split-tag", name_arg)?;
132
1280
    let tag_value = present("set-split-tag", "tag-value", value_arg)?;
133
1280
    SetSplitTag::new()
134
1280
        .user_id(user_id)
135
1280
        .split_id(split_id)
136
1280
        .tag_name(tag_name)
137
1280
        .tag_value(tag_value)
138
1280
        .run()
139
1280
        .await
140
        .map(|_| 1)
141
        .map_err(|err| cmd_failure("set-split-tag", err))
142
1280
}
143

            
144
/// `get-split-tag` lookup. Returns the empty string when the tag isn't
145
/// set on this split — keeps the wasm contract simple (`string` return,
146
/// no `Option` boxing). Scripts test absence with `(equal? v "")`.
147
1120
async fn run_get_split_tag(
148
1120
    user_id: Uuid,
149
1120
    id_arg: Option<String>,
150
1120
    name_arg: Option<String>,
151
1120
) -> wasmtime::Result<String> {
152
1120
    let split_id = uuid_arg("get-split-tag", "split-id", id_arg)?;
153
1120
    let tag_name = tag_name_arg("get-split-tag", name_arg)?;
154
1120
    match GetSplitTag::new()
155
1120
        .user_id(user_id)
156
1120
        .split_id(split_id)
157
1120
        .tag_name(tag_name)
158
1120
        .run()
159
1120
        .await
160
    {
161
1120
        Ok(Some(CmdResult::String(s))) => Ok(s),
162
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
163
            "get-split-tag: expected String, got {other:?}"
164
        ))),
165
        Ok(None) => Ok(String::new()),
166
        Err(err) => Err(cmd_failure("get-split-tag", err)),
167
    }
168
1120
}
169

            
170
/// `get-split-tags` lookup: every value of the name, ordered by value;
171
/// the empty list when the tag isn't set.
172
320
async fn run_get_split_tags(
173
320
    user_id: Uuid,
174
320
    id_arg: Option<String>,
175
320
    name_arg: Option<String>,
176
320
) -> wasmtime::Result<Vec<String>> {
177
320
    let split_id = uuid_arg("get-split-tags", "split-id", id_arg)?;
178
320
    let tag_name = tag_name_arg("get-split-tags", name_arg)?;
179
320
    match GetSplitTagValues::new()
180
320
        .user_id(user_id)
181
320
        .split_id(split_id)
182
320
        .tag_name(tag_name)
183
320
        .run()
184
320
        .await
185
    {
186
320
        Ok(Some(CmdResult::Lines(values))) => Ok(values),
187
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
188
            "get-split-tags: expected Lines, got {other:?}"
189
        ))),
190
        Ok(None) => Ok(Vec::new()),
191
        Err(err) => Err(cmd_failure("get-split-tags", err)),
192
    }
193
320
}
194

            
195
/// Validates the :account-id arg into a UUID. Extracted so the validation
196
/// contract is reachable from unit tests without a wasmtime `Caller`.
197
162
fn parse_account_id_arg(id_arg: Option<String>) -> wasmtime::Result<Uuid> {
198
162
    uuid_arg("list-splits", "account-id", id_arg)
199
162
}
200

            
201
/// Validates the :transaction-id arg into a UUID. Mirror of
202
/// [`parse_account_id_arg`] for the transaction-keyed splits query — the
203
/// server's `ListSplits` runs the by-transaction SQL when given a
204
/// `.transaction()` filter, but `list-splits` only ever wired the account
205
/// filter; this is the validation seam for the transaction variant.
206
1123
fn parse_transaction_id_arg(id_arg: Option<String>) -> wasmtime::Result<Uuid> {
207
1123
    uuid_arg("list-splits-by-transaction", "transaction-id", id_arg)
208
1123
}
209

            
210
/// (id, account_id, commodity_id, value_num, value_denom, reconcile_code)
211
/// per split, flattened from `TaggedSplits` for the wasm allocator loop.
212
/// `reconcile_code` is the `tribool` wire encoding of `Option<bool>`
213
/// (`entity_registry.org`): `0` = `None`/unknown, `1` = `Some(false)`, `2` =
214
/// `Some(true)`. Splits don't carry tags on the wire (yet), so the tuple
215
/// omits the tag map.
216
type SplitEntry = (String, String, String, i64, i64, i32);
217

            
218
/// Encodes `Option<bool>` as the `tribool` wire representation (ADR-0033
219
/// Phase 5): `None` and `Some(false)` are DISTINCT states, so this never
220
/// collapses "unknown" onto "false" the way a plain `unwrap_or(false)` would.
221
2723
fn tribool_code(reconciled: Option<bool>) -> i32 {
222
2723
    match reconciled {
223
2401
        None => 0,
224
161
        Some(false) => 1,
225
161
        Some(true) => 2,
226
    }
227
2723
}
228

            
229
1282
fn list_split_entries(
230
1282
    name: &str,
231
1282
    result: Result<Option<CmdResult>, CmdError>,
232
1282
) -> wasmtime::Result<Vec<SplitEntry>> {
233
1282
    match result {
234
1281
        Ok(Some(CmdResult::TaggedSplits { entities })) => Ok(entities
235
1281
            .into_iter()
236
2723
            .map(|(s, _)| {
237
2723
                (
238
2723
                    s.id.to_string(),
239
2723
                    s.account_id.to_string(),
240
2723
                    s.commodity_id.to_string(),
241
2723
                    s.value_num,
242
2723
                    s.value_denom,
243
2723
                    tribool_code(s.reconcile_state),
244
2723
                )
245
2723
            })
246
            .collect()),
247
1
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
248
1
            "{name}: expected TaggedSplits, got {other:?}"
249
1
        ))),
250
        Ok(None) => Ok(Vec::new()),
251
        Err(err) => Err(cmd_failure(name, err)),
252
    }
253
1282
}
254

            
255
2720
async fn alloc_split_entity(
256
2720
    caller: &mut Caller<'_, SessionData>,
257
2720
    id: &str,
258
2720
    account_id: &str,
259
2720
    commodity_id: &str,
260
2720
    value_num: i64,
261
2720
    value_denom: i64,
262
2720
    reconcile_code: i32,
263
2720
) -> wasmtime::Result<Rooted<StructRef>> {
264
2720
    let id_ref = alloc_string_ref(caller, id.as_bytes())?;
265
2720
    let account_ref = alloc_string_ref(caller, account_id.as_bytes())?;
266
2720
    let commodity_ref = alloc_string_ref(caller, commodity_id.as_bytes())?;
267
2720
    let ratio_ref = alloc_ratio_ref(caller, value_num, value_denom)?;
268
2720
    let args = [
269
2720
        Val::AnyRef(Some(id_ref.to_anyref())),
270
2720
        Val::AnyRef(Some(account_ref.to_anyref())),
271
2720
        Val::AnyRef(Some(commodity_ref.to_anyref())),
272
2720
        Val::AnyRef(Some(ratio_ref.to_anyref())),
273
2720
        Val::I32(reconcile_code),
274
2720
    ];
275
2720
    alloc_entity_via_export(caller, "alloc_split", &args).await
276
2720
}
277

            
278
1280
async fn alloc_split_chain(
279
1280
    caller: &mut Caller<'_, SessionData>,
280
1280
    entries: Vec<SplitEntry>,
281
1280
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
282
1280
    let mut anyrefs: Vec<Option<Rooted<AnyRef>>> = Vec::with_capacity(entries.len());
283
1280
    for (id, account_id, commodity_id, num, denom, reconcile_code) in entries {
284
2720
        let entity_ref = alloc_split_entity(
285
2720
            caller,
286
2720
            &id,
287
2720
            &account_id,
288
2720
            &commodity_id,
289
2720
            num,
290
2720
            denom,
291
2720
            reconcile_code,
292
2720
        )
293
2720
        .await?;
294
2720
        anyrefs.push(Some(entity_ref.to_anyref()));
295
    }
296
1280
    alloc_pair_chain(caller, anyrefs).await
297
1280
}
298

            
299
#[cfg(test)]
300
mod tests {
301
    use super::*;
302
    use finance::split::Split;
303
3
    fn split(value_num: i64, value_denom: i64, reconciled: Option<bool>) -> Split {
304
3
        Split {
305
3
            id: Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap(),
306
3
            tx_id: Uuid::nil(),
307
3
            account_id: Uuid::parse_str("22222222-2222-2222-2222-222222222222").unwrap(),
308
3
            commodity_id: Uuid::parse_str("33333333-3333-3333-3333-333333333333").unwrap(),
309
3
            reconcile_state: reconciled,
310
3
            reconcile_date: None,
311
3
            value_num,
312
3
            value_denom,
313
3
            lot_id: None,
314
3
        }
315
3
    }
316

            
317
    #[test]
318
1
    fn list_split_entries_keeps_unknown_apart_from_unreconciled() {
319
1
        let entities = vec![
320
1
            (split(1, 1, None), Vec::new()),
321
1
            (split(7, 3, Some(false)), Vec::new()),
322
1
            (split(3, 1, Some(true)), Vec::new()),
323
        ];
324
        let entries =
325
1
            list_split_entries("test", Ok(Some(CmdResult::TaggedSplits { entities }))).unwrap();
326
1
        let shown: Vec<_> = entries
327
1
            .iter()
328
3
            .map(|(_, _, _, num, denom, code)| (*num, *denom, *code))
329
            .collect();
330
1
        assert_eq!(shown, vec![(1, 1, 0), (7, 3, 1), (3, 1, 2)]);
331
1
        assert_eq!(entries[0].1, "22222222-2222-2222-2222-222222222222");
332
1
    }
333

            
334
    #[test]
335
1
    fn list_split_entries_refuses_another_result() {
336
1
        let err = list_split_entries("test", Ok(Some(CmdResult::String("x".into())))).unwrap_err();
337
1
        assert!(err.to_string().contains("expected TaggedSplits"), "{err}");
338
1
    }
339

            
340
    #[test]
341
1
    fn parse_account_id_rejects_missing() {
342
1
        let err = parse_account_id_arg(None).unwrap_err();
343
1
        assert!(err.to_string().contains("missing or empty"), "got: {err}");
344
1
    }
345

            
346
    #[test]
347
1
    fn parse_account_id_rejects_invalid_uuid() {
348
1
        let err = parse_account_id_arg(Some("nope".into())).unwrap_err();
349
1
        assert!(err.to_string().contains("invalid uuid"), "got: {err}");
350
1
    }
351

            
352
    #[test]
353
1
    fn parse_transaction_id_rejects_missing() {
354
1
        let err = parse_transaction_id_arg(None).unwrap_err();
355
1
        assert!(
356
1
            err.to_string()
357
1
                .contains("list-splits-by-transaction: missing or empty"),
358
            "got: {err}"
359
        );
360
1
    }
361

            
362
    #[test]
363
1
    fn parse_transaction_id_rejects_invalid_uuid() {
364
1
        let err = parse_transaction_id_arg(Some("nope".into())).unwrap_err();
365
1
        assert!(
366
1
            err.to_string()
367
1
                .contains("list-splits-by-transaction: invalid uuid"),
368
            "got: {err}"
369
        );
370
1
    }
371

            
372
    #[test]
373
1
    fn parse_transaction_id_accepts_valid_uuid() {
374
1
        let uuid = "11111111-1111-1111-1111-111111111111";
375
1
        let parsed = parse_transaction_id_arg(Some(uuid.into())).unwrap();
376
1
        assert_eq!(parsed, Uuid::parse_str(uuid).unwrap());
377
1
    }
378
}