1use scripting::runtime::{
11 alloc_entity_via_export, alloc_pair_chain, alloc_ratio_ref, alloc_string_ref, read_string_arg,
12};
13use server::command::split::{GetSplitTag, GetSplitTagValues, ListSplits, SetSplitTag};
14use server::command::{CmdError, CmdResult};
15use uuid::Uuid;
16use wasmtime::{AnyRef, ArrayRef, Caller, Linker, Rooted, StructRef, Val};
17
18use crate::host_failure::cmd_failure;
19use crate::natives::args::{present, tag_name_arg, uuid_arg};
20use crate::natives::native::register_native;
21use crate::session::SessionData;
22
23pub 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
31pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
32 register_readonly(linker)?;
33 register_mutators(linker)?;
34 Ok(())
35}
36
37pub fn register_readonly(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
38 register_native(
39 linker,
40 "split_list_splits",
41 |caller, (id_arg,): (Option<Rooted<wasmtime::ArrayRef>>,)| {
42 Box::pin(async move {
43 let user_id = caller.data().ctx().user_id;
44 let id = read_string_arg(caller, id_arg)?;
45 let account_id = parse_account_id_arg(id)?;
46 let result = ListSplits::new()
47 .user_id(user_id)
48 .account(account_id)
49 .run()
50 .await;
51 let entries = list_split_entries("list-splits", result)?;
52 alloc_split_chain(caller, entries).await
53 })
54 },
55 )?;
56 register_native(
57 linker,
58 "split_list_splits_by_transaction",
59 |caller, (id_arg,): (Option<Rooted<wasmtime::ArrayRef>>,)| {
60 Box::pin(async move {
61 let user_id = caller.data().ctx().user_id;
62 let id = read_string_arg(caller, id_arg)?;
63 let transaction_id = parse_transaction_id_arg(id)?;
64 let result = ListSplits::new()
65 .user_id(user_id)
66 .transaction(transaction_id)
67 .run()
68 .await;
69 let entries = list_split_entries("list-splits-by-transaction", result)?;
70 alloc_split_chain(caller, entries).await
71 })
72 },
73 )?;
74 register_native(
75 linker,
76 "split_get_split_tag",
77 |caller, (id_arg, name_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
78 Box::pin(async move {
79 let user_id = caller.data().ctx().user_id;
80 let id = read_string_arg(caller, id_arg)?;
81 let name = read_string_arg(caller, name_arg)?;
82 let value = run_get_split_tag(user_id, id, name).await?;
83 Ok(Some(alloc_string_ref(caller, value.as_bytes())?))
84 })
85 },
86 )?;
87 register_native(
88 linker,
89 "split_get_split_tags",
90 |caller, (id_arg, name_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
91 Box::pin(async move {
92 let user_id = caller.data().ctx().user_id;
93 let id = read_string_arg(caller, id_arg)?;
94 let name = read_string_arg(caller, name_arg)?;
95 let values = run_get_split_tags(user_id, id, name).await?;
96 super::alloc_string_pair_chain(caller, values).await
97 })
98 },
99 )?;
100 Ok(())
101}
102
103pub fn register_mutators(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
104 register_native(
105 linker,
106 "split_set_split_tag",
107 |caller, (id_arg, name_arg, value_arg): super::StringArgTriple| {
108 Box::pin(async move {
109 let user_id = caller.data().ctx().user_id;
110 let id = read_string_arg(caller, id_arg)?;
111 let name = read_string_arg(caller, name_arg)?;
112 let value = read_string_arg(caller, value_arg)?;
113 run_set_split_tag(user_id, id, name, value).await
114 })
115 },
116 )?;
117 Ok(())
118}
119
120async fn run_set_split_tag(
125 user_id: Uuid,
126 id_arg: Option<String>,
127 name_arg: Option<String>,
128 value_arg: Option<String>,
129) -> wasmtime::Result<i32> {
130 let split_id = uuid_arg("set-split-tag", "split-id", id_arg)?;
131 let tag_name = tag_name_arg("set-split-tag", name_arg)?;
132 let tag_value = present("set-split-tag", "tag-value", value_arg)?;
133 SetSplitTag::new()
134 .user_id(user_id)
135 .split_id(split_id)
136 .tag_name(tag_name)
137 .tag_value(tag_value)
138 .run()
139 .await
140 .map(|_| 1)
141 .map_err(|err| cmd_failure("set-split-tag", err))
142}
143
144async fn run_get_split_tag(
148 user_id: Uuid,
149 id_arg: Option<String>,
150 name_arg: Option<String>,
151) -> wasmtime::Result<String> {
152 let split_id = uuid_arg("get-split-tag", "split-id", id_arg)?;
153 let tag_name = tag_name_arg("get-split-tag", name_arg)?;
154 match GetSplitTag::new()
155 .user_id(user_id)
156 .split_id(split_id)
157 .tag_name(tag_name)
158 .run()
159 .await
160 {
161 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}
169
170async fn run_get_split_tags(
173 user_id: Uuid,
174 id_arg: Option<String>,
175 name_arg: Option<String>,
176) -> wasmtime::Result<Vec<String>> {
177 let split_id = uuid_arg("get-split-tags", "split-id", id_arg)?;
178 let tag_name = tag_name_arg("get-split-tags", name_arg)?;
179 match GetSplitTagValues::new()
180 .user_id(user_id)
181 .split_id(split_id)
182 .tag_name(tag_name)
183 .run()
184 .await
185 {
186 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}
194
195fn parse_account_id_arg(id_arg: Option<String>) -> wasmtime::Result<Uuid> {
198 uuid_arg("list-splits", "account-id", id_arg)
199}
200
201fn parse_transaction_id_arg(id_arg: Option<String>) -> wasmtime::Result<Uuid> {
207 uuid_arg("list-splits-by-transaction", "transaction-id", id_arg)
208}
209
210type SplitEntry = (String, String, String, i64, i64, i32);
217
218fn tribool_code(reconciled: Option<bool>) -> i32 {
222 match reconciled {
223 None => 0,
224 Some(false) => 1,
225 Some(true) => 2,
226 }
227}
228
229fn list_split_entries(
230 name: &str,
231 result: Result<Option<CmdResult>, CmdError>,
232) -> wasmtime::Result<Vec<SplitEntry>> {
233 match result {
234 Ok(Some(CmdResult::TaggedSplits { entities })) => Ok(entities
235 .into_iter()
236 .map(|(s, _)| {
237 (
238 s.id.to_string(),
239 s.account_id.to_string(),
240 s.commodity_id.to_string(),
241 s.value_num,
242 s.value_denom,
243 tribool_code(s.reconcile_state),
244 )
245 })
246 .collect()),
247 Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
248 "{name}: expected TaggedSplits, got {other:?}"
249 ))),
250 Ok(None) => Ok(Vec::new()),
251 Err(err) => Err(cmd_failure(name, err)),
252 }
253}
254
255async fn alloc_split_entity(
256 caller: &mut Caller<'_, SessionData>,
257 id: &str,
258 account_id: &str,
259 commodity_id: &str,
260 value_num: i64,
261 value_denom: i64,
262 reconcile_code: i32,
263) -> wasmtime::Result<Rooted<StructRef>> {
264 let id_ref = alloc_string_ref(caller, id.as_bytes())?;
265 let account_ref = alloc_string_ref(caller, account_id.as_bytes())?;
266 let commodity_ref = alloc_string_ref(caller, commodity_id.as_bytes())?;
267 let ratio_ref = alloc_ratio_ref(caller, value_num, value_denom)?;
268 let args = [
269 Val::AnyRef(Some(id_ref.to_anyref())),
270 Val::AnyRef(Some(account_ref.to_anyref())),
271 Val::AnyRef(Some(commodity_ref.to_anyref())),
272 Val::AnyRef(Some(ratio_ref.to_anyref())),
273 Val::I32(reconcile_code),
274 ];
275 alloc_entity_via_export(caller, "alloc_split", &args).await
276}
277
278async fn alloc_split_chain(
279 caller: &mut Caller<'_, SessionData>,
280 entries: Vec<SplitEntry>,
281) -> wasmtime::Result<Option<Rooted<StructRef>>> {
282 let mut anyrefs: Vec<Option<Rooted<AnyRef>>> = Vec::with_capacity(entries.len());
283 for (id, account_id, commodity_id, num, denom, reconcile_code) in entries {
284 let entity_ref = alloc_split_entity(
285 caller,
286 &id,
287 &account_id,
288 &commodity_id,
289 num,
290 denom,
291 reconcile_code,
292 )
293 .await?;
294 anyrefs.push(Some(entity_ref.to_anyref()));
295 }
296 alloc_pair_chain(caller, anyrefs).await
297}
298
299#[cfg(test)]
300mod tests {
301 use super::*;
302 use finance::split::Split;
303 fn split(value_num: i64, value_denom: i64, reconciled: Option<bool>) -> Split {
304 Split {
305 id: Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap(),
306 tx_id: Uuid::nil(),
307 account_id: Uuid::parse_str("22222222-2222-2222-2222-222222222222").unwrap(),
308 commodity_id: Uuid::parse_str("33333333-3333-3333-3333-333333333333").unwrap(),
309 reconcile_state: reconciled,
310 reconcile_date: None,
311 value_num,
312 value_denom,
313 lot_id: None,
314 }
315 }
316
317 #[test]
318 fn list_split_entries_keeps_unknown_apart_from_unreconciled() {
319 let entities = vec![
320 (split(1, 1, None), Vec::new()),
321 (split(7, 3, Some(false)), Vec::new()),
322 (split(3, 1, Some(true)), Vec::new()),
323 ];
324 let entries =
325 list_split_entries("test", Ok(Some(CmdResult::TaggedSplits { entities }))).unwrap();
326 let shown: Vec<_> = entries
327 .iter()
328 .map(|(_, _, _, num, denom, code)| (*num, *denom, *code))
329 .collect();
330 assert_eq!(shown, vec![(1, 1, 0), (7, 3, 1), (3, 1, 2)]);
331 assert_eq!(entries[0].1, "22222222-2222-2222-2222-222222222222");
332 }
333
334 #[test]
335 fn list_split_entries_refuses_another_result() {
336 let err = list_split_entries("test", Ok(Some(CmdResult::String("x".into())))).unwrap_err();
337 assert!(err.to_string().contains("expected TaggedSplits"), "{err}");
338 }
339
340 #[test]
341 fn parse_account_id_rejects_missing() {
342 let err = parse_account_id_arg(None).unwrap_err();
343 assert!(err.to_string().contains("missing or empty"), "got: {err}");
344 }
345
346 #[test]
347 fn parse_account_id_rejects_invalid_uuid() {
348 let err = parse_account_id_arg(Some("nope".into())).unwrap_err();
349 assert!(err.to_string().contains("invalid uuid"), "got: {err}");
350 }
351
352 #[test]
353 fn parse_transaction_id_rejects_missing() {
354 let err = parse_transaction_id_arg(None).unwrap_err();
355 assert!(
356 err.to_string()
357 .contains("list-splits-by-transaction: missing or empty"),
358 "got: {err}"
359 );
360 }
361
362 #[test]
363 fn parse_transaction_id_rejects_invalid_uuid() {
364 let err = parse_transaction_id_arg(Some("nope".into())).unwrap_err();
365 assert!(
366 err.to_string()
367 .contains("list-splits-by-transaction: invalid uuid"),
368 "got: {err}"
369 );
370 }
371
372 #[test]
373 fn parse_transaction_id_accepts_valid_uuid() {
374 let uuid = "11111111-1111-1111-1111-111111111111";
375 let parsed = parse_transaction_id_arg(Some(uuid.into())).unwrap();
376 assert_eq!(parsed, Uuid::parse_str(uuid).unwrap());
377 }
378}