1
//! Account merge: pick two accounts, confirm naming both, merged.
2

            
3
use crate::tabs::fetch::Fetch;
4
use cli_core::account::merge_preview_call;
5
use cli_core::transaction::submit_call;
6
use forms::{ACCOUNT_MERGE, FormValues};
7
use nomiscript::Value;
8
use rpc::{ResponsePayload, ScriptCtx, Session};
9
use server::command::account::CreateAccount;
10
use server::command::{CmdResult, FinanceEntity};
11
use sqlx::PgPool;
12
use sqlx::types::Uuid;
13

            
14
use crate::event::{Intent, apply};
15
use crate::form::Form;
16
use crate::modal::{ConfirmAction, Modal};
17
use crate::widgets::Widget;
18

            
19
3
async fn reply(session: &mut Session, form: &str) -> String {
20
3
    session.handle_form(&format!("(:id 1 :form {form})")).await
21
3
}
22

            
23
4
pub(super) async fn seed_user(pool: &PgPool) -> anyhow::Result<Uuid> {
24
4
    let user_id = Uuid::new_v4();
25
4
    sqlx::query(
26
4
        "INSERT INTO users \
27
4
         (id, user_name, email, photo, verified, user_password, user_role, database_name, created_at) \
28
4
         VALUES ($1, $2, $3, 'x', false, 'pw', 'user', 'db', NOW())",
29
4
    )
30
4
    .bind(user_id)
31
4
    .bind(format!("u{user_id}"))
32
4
    .bind(format!("{user_id}@test.com"))
33
4
    .execute(pool)
34
4
    .await?;
35
4
    Ok(user_id)
36
4
}
37

            
38
2
async fn account(user_id: Uuid, name: &str) -> anyhow::Result<Uuid> {
39
2
    match CreateAccount::new()
40
2
        .name(name.to_string())
41
2
        .user_id(user_id)
42
2
        .run()
43
2
        .await?
44
    {
45
2
        Some(CmdResult::Entity(FinanceEntity::Account(account))) => Ok(account.id),
46
        other => anyhow::bail!("unexpected CreateAccount result: {other:?}"),
47
    }
48
2
}
49

            
50
2
fn pick(form: &mut Form, key: &str, text: &str) {
51
2
    let select = form
52
2
        .fields
53
2
        .iter_mut()
54
3
        .find(|field| field.key == Some(key))
55
2
        .map(|field| &mut field.widget);
56
2
    if let Some(Widget::Select(select)) = select {
57
10
        text.chars().for_each(|c| select.filter_push(c));
58
2
        select.confirm();
59
    }
60
2
}
61

            
62
#[sqlx::test(migrator = "server::db::MIGRATOR")]
63
async fn picked_accounts_are_confirmed_by_label_and_merged(pool: PgPool) -> anyhow::Result<()> {
64
    let _guard = server::db::install_test_pool(pool.clone());
65
    let user = seed_user(&pool).await?;
66
    let into = account(user, "Coffee").await?;
67
    let from = account(user, "Cafe").await?;
68
    let mut session = Session::new(ScriptCtx::new(user))?;
69
    let mut app = crate::test_support::app();
70
    app.attach_echo();
71
    app.accounts_mut().state = Fetch::Loaded(Vec::new());
72
    app.open_account_merge(FormValues::default());
73
    let options = reply(&mut session, r#"(form-options "accounts")"#).await;
74
    app.route_reply(1, &options);
75
    if let Some(Modal::Form(form)) = app.overlays.top_mut() {
76
        pick(form, "into", "Coffee");
77
        pick(form, "from", "Cafe");
78
    }
79

            
80
    let Some(Modal::Form(open)) = app.overlays.top() else {
81
        anyhow::bail!("the form is gone");
82
    };
83
    let picked = open.values();
84
    apply(&mut app, Intent::Submit);
85
    let preview = reply(&mut session, &merge_preview_call(&picked)).await;
86
    app.route_reply(2, &preview);
87

            
88
    let Some(Modal::Confirm {
89
        prompt,
90
        action: ConfirmAction::MergeAccounts(form),
91
        ..
92
    }) = app.overlays.top()
93
    else {
94
        anyhow::bail!("no merge confirmation: {:?}", app.overlays.top());
95
    };
96
    assert!(
97
        prompt.starts_with("Merge account Cafe into Coffee: 0 splits move"),
98
        "{prompt}"
99
    );
100
    let values = form.values();
101
    assert_eq!(values.text("into"), Some(into.to_string().as_str()));
102
    assert_eq!(values.text("from"), Some(from.to_string().as_str()));
103
    let wire = reply(&mut session, &submit_call(&ACCOUNT_MERGE, &values)).await;
104
1
    let merged = rpc::parse_response(&wire).map(|response| response.payload);
105
    assert!(
106
        matches!(&merged, Ok(ResponsePayload::Value(Value::String(id))) if *id == into.to_string()),
107
        "{wire}"
108
    );
109
    apply(&mut app, Intent::ConfirmYes);
110
    assert!(
111
        app.pending_form.is_some(),
112
        "the confirmed form awaits its reply"
113
    );
114
    Ok(())
115
}