Skip to main content

rpc/forms/
account_merge.rs

1//! Merging two accounts: the one call the native and the `account-merge`
2//! form share, and the form's preview and submit.
3
4use forms::{ACCOUNT_MERGE, FieldError, FormValues};
5use scripting::runtime::EvalValue;
6use server::command::CmdResult;
7use server::command::account_merge::{MergeAccounts, PreviewMergeAccounts};
8use uuid::Uuid;
9
10use super::Failure;
11use super::outcome::key;
12use super::transaction_rows::{error_at, joined};
13use crate::resolve::Directory;
14
15const CTX: &str = "merge-accounts";
16
17/// What merging the picked accounts does: `splits` splits move to `into`.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct MergePreview {
20    pub into: Uuid,
21    pub from: Uuid,
22    pub splits: i64,
23}
24
25impl MergePreview {
26    /// `(:into "uuid" :from "uuid" :splits n)`.
27    ///
28    /// # Errors
29    /// A split count beyond `i32`.
30    pub fn to_value(&self) -> wasmtime::Result<EvalValue> {
31        let splits = i32::try_from(self.splits)
32            .map_err(|_| wasmtime::Error::msg(format!("{} splits exceed i32", self.splits)))?;
33        Ok(EvalValue::List(vec![
34            key("INTO"),
35            EvalValue::String(self.into.to_string()),
36            key("FROM"),
37            EvalValue::String(self.from.to_string()),
38            key("SPLITS"),
39            EvalValue::I32(splits),
40        ]))
41    }
42}
43
44/// What a merge did: `moved` splits went from `from` to `into`.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct Merged {
47    pub into: Uuid,
48    pub from: Uuid,
49    pub moved: i64,
50}
51
52/// Merge `from` into `into`; a refusal names its reason.
53pub async fn merge_accounts(user_id: Uuid, into: Uuid, from: Uuid) -> Result<Merged, Failure> {
54    let merged = MergeAccounts::new()
55        .user_id(user_id)
56        .into(into)
57        .from(from)
58        .run()
59        .await
60        .map_err(|err| Failure::from_command(CTX, err))?;
61    match merged {
62        Some(CmdResult::Merged { into, moved }) => Ok(Merged { into, from, moved }),
63        other => Err(Failure::Internal(wasmtime::Error::msg(format!(
64            "{CTX}: unexpected merge result {other:?}"
65        )))),
66    }
67}
68
69/// The two accounts `values` pick, else a field error at each unresolved one.
70async fn picked(user_id: Uuid, values: &FormValues) -> Result<(Uuid, Uuid), Failure> {
71    let errors = values.check(&ACCOUNT_MERGE);
72    if !errors.is_empty() {
73        return Err(errors.into());
74    }
75    let directory = Directory::load(CTX, user_id).await?;
76    let account = |key: &str| -> Result<Uuid, Vec<FieldError>> {
77        let text = values.text(key).unwrap_or_default().trim();
78        directory
79            .own_account(text)
80            .map_err(|err| vec![error_at(key.to_string(), err.to_string())])
81    };
82    Ok(joined(account("into"), account("from"))?)
83}
84
85/// What submitting `values` would merge.
86pub async fn merge_preview(user_id: Uuid, values: &FormValues) -> Result<MergePreview, Failure> {
87    let (into, from) = picked(user_id, values).await?;
88    let counted = PreviewMergeAccounts::new()
89        .user_id(user_id)
90        .into(into)
91        .from(from)
92        .run()
93        .await
94        .map_err(|err| Failure::from_command(CTX, err))?;
95    match counted {
96        Some(CmdResult::Count(splits)) => Ok(MergePreview { into, from, splits }),
97        other => Err(Failure::Internal(wasmtime::Error::msg(format!(
98            "{CTX}: unexpected split count {other:?}"
99        )))),
100    }
101}
102
103/// `account-merge` submit: the merge with the count it moved.
104pub async fn merge_submit(user_id: Uuid, values: &FormValues) -> Result<Merged, Failure> {
105    let (into, from) = picked(user_id, values).await?;
106    merge_accounts(user_id, into, from).await
107}
108
109/// `account-merge` submit through the shared form path.
110pub(super) async fn submit_merge(user_id: Uuid, values: &FormValues) -> Result<Uuid, Failure> {
111    merge_submit(user_id, values).await.map(|m| m.into)
112}