1
//! Merging two accounts from the account manage page: pick both, review the
2
//! labels and the splits that move, merge.
3

            
4
use anyhow::{Result, ensure};
5
use chrono::Utc;
6
use finance::split::Split;
7
use server::command::FinanceEntity;
8
use server::command::transaction::CreateTransaction;
9
use uuid::Uuid;
10

            
11
use super::driver::Driver;
12
use super::harness::{Harness, with_harness};
13
use super::page::{Pick, login, open, pick, reference, wait_for};
14

            
15
/// One split pair moving `amount` JPY from `from` to `to`.
16
2
async fn transfer(h: &Harness, from: Uuid, to: Uuid, amount: i64) -> Result<()> {
17
2
    let tx_id = Uuid::new_v4();
18
2
    let splits = [(from, -amount), (to, amount)]
19
2
        .into_iter()
20
4
        .map(|(account_id, value_num)| {
21
4
            FinanceEntity::Split(Split {
22
4
                id: Uuid::new_v4(),
23
4
                tx_id,
24
4
                account_id,
25
4
                commodity_id: h.commodity("JPY"),
26
4
                value_num,
27
4
                value_denom: 1,
28
4
                reconcile_state: None,
29
4
                reconcile_date: None,
30
4
                lot_id: None,
31
4
            })
32
4
        })
33
        .collect();
34
2
    let now = Utc::now();
35
2
    CreateTransaction::new()
36
2
        .user_id(h.tenant.id)
37
2
        .splits(splits)
38
2
        .id(tx_id)
39
2
        .post_date(now)
40
2
        .enter_date(now)
41
2
        .run()
42
2
        .await
43
        .map_err(|e| anyhow::anyhow!("{e:?}"))?;
44
2
    Ok(())
45
2
}
46

            
47
/// The path the page's link reading `text` points to.
48
3
async fn link_to(driver: &Driver, text: &str) -> Result<String> {
49
3
    let href = driver
50
3
        .run(
51
3
            "const a = [...document.querySelectorAll('a')]\
52
3
             .find(a => a.textContent.trim() === arguments[0]);\
53
3
             return a ? a.getAttribute('href') : null;",
54
3
            vec![serde_json::json!(text)],
55
3
        )
56
3
        .await?;
57
3
    href.as_str()
58
3
        .map(str::to_string)
59
        .ok_or_else(|| anyhow::anyhow!("no link {text:?}"))
60
3
}
61

            
62
/// A label shown for the top-level `Cafe` accounts (not the child path).
63
3
fn top_cafe(label: &str) -> bool {
64
3
    label.starts_with("Cafe") && !label.contains(':') && !label.contains("McDonalds")
65
3
}
66

            
67
1
async fn merge_twins(h: &Harness) -> Result<()> {
68
1
    let (cafe, twin) = (h.account("Cafe"), h.account("Cafe2"));
69
1
    transfer(h, h.account("Wallet"), twin, 600).await?;
70
1
    transfer(h, h.account("Suica"), twin, 300).await?;
71
1
    login(h).await?;
72
1
    h.driver.goto(&h.url("/account/manage")).await?;
73
1
    let merge_page = link_to(&h.driver, "Merge accounts").await?;
74
1
    open(h, &merge_page).await?;
75
1
    let into = pick(h, "into", "Caf", top_cafe, 0, Pick::Mouse).await?;
76
1
    let from = pick(h, "from", "Caf", top_cafe, 1, Pick::Mouse).await?;
77
1
    let (_, into_id) = reference(h, "into").await?;
78
1
    let from_id = match into_id == cafe.to_string() {
79
1
        true => twin,
80
        false => cafe,
81
    };
82
1
    let button = h
83
1
        .driver
84
1
        .find("form.nomi-form button[type=\"submit\"]")
85
1
        .await?;
86
1
    h.driver.click(&button).await?;
87
1
    let summary = wait_for(
88
1
        &h.driver,
89
1
        "const s = document.querySelector('.merge-summary');\
90
1
         return s ? s.textContent.replace(/\\s+/g, ' ').trim() : null;",
91
1
        vec![],
92
1
        "the merge review",
93
1
    )
94
1
    .await?;
95
1
    let summary = summary.as_str().unwrap_or_default();
96
1
    ensure!(
97
1
        summary.starts_with(&format!("Merge {from} into {into}:")),
98
        "{summary}"
99
    );
100
1
    let moving = if from_id == twin {
101
1
        "2 splits move"
102
    } else {
103
        "0 splits move"
104
    };
105
1
    ensure!(summary.contains(moving), "{summary}");
106
1
    let button = h
107
1
        .driver
108
1
        .find("form.nomi-form button[type=\"submit\"]")
109
1
        .await?;
110
1
    h.driver.click(&button).await?;
111
1
    let result = wait_for(
112
1
        &h.driver,
113
1
        "const r = document.querySelector('.merge-result');\
114
1
         return r ? r.textContent.replace(/\\s+/g, ' ').trim() : null;",
115
1
        vec![],
116
1
        "the merge result",
117
1
    )
118
1
    .await?;
119
1
    let result = result.as_str().unwrap_or_default();
120
1
    ensure!(
121
1
        result.contains(&format!("{from} into {into}"))
122
1
            && result.contains(&format!("{into} was kept")),
123
        "{result}"
124
    );
125
1
    ensure!(
126
1
        result.contains(moving.replace("move", "moved").as_str()),
127
        "{result}"
128
    );
129
1
    let buttons = h
130
1
        .driver
131
1
        .run(
132
1
            "return document.querySelectorAll('#nf-account-merge button').length;",
133
1
            vec![],
134
1
        )
135
1
        .await?;
136
1
    ensure!(buttons == serde_json::json!(0), "a button stays: {buttons}");
137
1
    ensure!(
138
1
        link_to(&h.driver, "Merge more accounts").await? == "/account/merge",
139
        "no link to a fresh merge form"
140
    );
141
1
    ensure!(
142
1
        link_to(&h.driver, "Accounts").await? == "/account/list",
143
        "no link to the accounts list"
144
    );
145
1
    let mut conn = crate::common::tenant::tenant_connection(h.tenant.id).await;
146
1
    let gone: i64 = sqlx::query_scalar("SELECT count(*) FROM accounts WHERE id = $1")
147
1
        .bind(from_id)
148
1
        .fetch_one(&mut *conn)
149
1
        .await?;
150
1
    ensure!(gone == 0, "the merged account is still stored");
151
1
    Ok(())
152
1
}
153

            
154
#[supp_macro::shared_runtime_test]
155
1
async fn picked_twins_are_reviewed_and_merged() -> Result<()> {
156
1
    with_harness(|h| Box::pin(merge_twins(h))).await
157
}