1
//! Merging two accounts: the one call the native and the `account-merge`
2
//! form share, and the form's preview and submit.
3

            
4
use forms::{ACCOUNT_MERGE, FieldError, FormValues};
5
use scripting::runtime::EvalValue;
6
use server::command::CmdResult;
7
use server::command::account_merge::{MergeAccounts, PreviewMergeAccounts};
8
use uuid::Uuid;
9

            
10
use super::Failure;
11
use super::outcome::key;
12
use super::transaction_rows::{error_at, joined};
13
use crate::resolve::Directory;
14

            
15
const CTX: &str = "merge-accounts";
16

            
17
/// What merging the picked accounts does: `splits` splits move to `into`.
18
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19
pub struct MergePreview {
20
    pub into: Uuid,
21
    pub from: Uuid,
22
    pub splits: i64,
23
}
24

            
25
impl MergePreview {
26
    /// `(:into "uuid" :from "uuid" :splits n)`.
27
    ///
28
    /// # Errors
29
    /// A split count beyond `i32`.
30
162
    pub fn to_value(&self) -> wasmtime::Result<EvalValue> {
31
162
        let splits = i32::try_from(self.splits)
32
            .map_err(|_| wasmtime::Error::msg(format!("{} splits exceed i32", self.splits)))?;
33
162
        Ok(EvalValue::List(vec![
34
162
            key("INTO"),
35
162
            EvalValue::String(self.into.to_string()),
36
162
            key("FROM"),
37
162
            EvalValue::String(self.from.to_string()),
38
162
            key("SPLITS"),
39
162
            EvalValue::I32(splits),
40
162
        ]))
41
162
    }
42
}
43

            
44
/// What a merge did: `moved` splits went from `from` to `into`.
45
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46
pub 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.
53
967
pub async fn merge_accounts(user_id: Uuid, into: Uuid, from: Uuid) -> Result<Merged, Failure> {
54
967
    let merged = MergeAccounts::new()
55
967
        .user_id(user_id)
56
967
        .into(into)
57
967
        .from(from)
58
967
        .run()
59
967
        .await
60
164
        .map_err(|err| Failure::from_command(CTX, err))?;
61
803
    match merged {
62
803
        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
967
}
68

            
69
/// The two accounts `values` pick, else a field error at each unresolved one.
70
1288
async fn picked(user_id: Uuid, values: &FormValues) -> Result<(Uuid, Uuid), Failure> {
71
1288
    let errors = values.check(&ACCOUNT_MERGE);
72
1288
    if !errors.is_empty() {
73
        return Err(errors.into());
74
1288
    }
75
1288
    let directory = Directory::load(CTX, user_id).await?;
76
2576
    let account = |key: &str| -> Result<Uuid, Vec<FieldError>> {
77
2576
        let text = values.text(key).unwrap_or_default().trim();
78
2576
        directory
79
2576
            .own_account(text)
80
6
            .map_err(|err| vec![error_at(key.to_string(), err.to_string())])
81
2576
    };
82
1288
    Ok(joined(account("into"), account("from"))?)
83
1288
}
84

            
85
/// What submitting `values` would merge.
86
325
pub async fn merge_preview(user_id: Uuid, values: &FormValues) -> Result<MergePreview, Failure> {
87
325
    let (into, from) = picked(user_id, values).await?;
88
323
    let counted = PreviewMergeAccounts::new()
89
323
        .user_id(user_id)
90
323
        .into(into)
91
323
        .from(from)
92
323
        .run()
93
323
        .await
94
1
        .map_err(|err| Failure::from_command(CTX, err))?;
95
322
    match counted {
96
322
        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
325
}
102

            
103
/// `account-merge` submit: the merge with the count it moved.
104
963
pub async fn merge_submit(user_id: Uuid, values: &FormValues) -> Result<Merged, Failure> {
105
963
    let (into, from) = picked(user_id, values).await?;
106
960
    merge_accounts(user_id, into, from).await
107
963
}
108

            
109
/// `account-merge` submit through the shared form path.
110
640
pub(super) async fn submit_merge(user_id: Uuid, values: &FormValues) -> Result<Uuid, Failure> {
111
640
    merge_submit(user_id, values).await.map(|m| m.into)
112
640
}