1
//! `MergeAccounts`: fold one account into another in one DB transaction,
2
//! under the hierarchy lock, then the tag keys, then the account rows.
3

            
4
use crate::command::connection;
5
use std::collections::{BTreeSet, HashMap, HashSet};
6

            
7
use sqlx::{PgConnection, types::Uuid};
8
use supp_macro::command;
9

            
10
use super::attempt::Attempt;
11
use super::{CmdError, CmdResult};
12
use crate::attempt::Tries;
13
use crate::{
14
    hierarchy::lock_hierarchy,
15
    tag::{
16
        lock::{Key, KeyChanged, begin, lock},
17
        user::delete_tag_if_orphaned,
18
    },
19
    user::User,
20
};
21

            
22
command! {
23
    MergeAccounts {
24
        #[required]
25
        user_id: Uuid,
26
        #[required]
27
        into: Uuid,
28
        #[required]
29
        from: Uuid,
30
    } => {
31
        let moved = run_merge(user_id, into, from, Finish::Commit).await?;
32
        Ok(Some(CmdResult::Merged { into, moved }))
33
    }
34
10412
}
35

            
36
command! {
37
    PreviewMergeAccounts {
38
        #[required]
39
        user_id: Uuid,
40
        #[required]
41
        into: Uuid,
42
        #[required]
43
        from: Uuid,
44
    } => {
45
        let moved = run_merge(user_id, into, from, Finish::Rollback).await?;
46
        Ok(Some(CmdResult::Count(moved)))
47
    }
48
3948
}
49

            
50
/// Whether a finished merge keeps its changes or is only a dry run.
51
#[derive(Clone, Copy)]
52
enum Finish {
53
    Commit,
54
    Rollback,
55
}
56

            
57
3262
async fn run_merge(user_id: Uuid, into: Uuid, from: Uuid, finish: Finish) -> Result<i64, CmdError> {
58
1312
    if into == from {
59
164
        return Err(CmdError::Refused(
60
164
            "An account cannot be merged into itself".to_string(),
61
164
        ));
62
1148
    }
63
1148
    let user = User { id: user_id };
64
1148
    let mut conn = connection(&user).await?;
65
1148
    merge_with_retry(&mut conn, user_id, into, from, finish).await
66
1312
}
67

            
68
2720
async fn merge_with_retry(
69
2720
    conn: &mut PgConnection,
70
2720
    user_id: Uuid,
71
2720
    into: Uuid,
72
2720
    from: Uuid,
73
2720
    finish: Finish,
74
2720
) -> Result<i64, CmdError> {
75
1148
    let mut tries = Tries::default();
76
    loop {
77
1150
        if let Some(moved) = tries.step(merge_once(conn, user_id, into, from, finish).await)? {
78
1136
            return Ok(moved);
79
2
        }
80
    }
81
1148
}
82

            
83
2722
async fn merge_once(
84
2722
    conn: &mut PgConnection,
85
2722
    user_id: Uuid,
86
2722
    into: Uuid,
87
2722
    from: Uuid,
88
2722
    finish: Finish,
89
2722
) -> Result<i64, Attempt> {
90
1150
    let mut tx = begin(conn).await?;
91
1150
    lock_hierarchy(&mut tx, user_id).await?;
92
1150
    let from_tags = lock_from_tags(&mut tx, from).await?;
93
1147
    lock_accounts(&mut tx, into, from).await?;
94
1142
    ensure_from_tags(&mut tx, from, &from_tags).await?;
95
1142
    refuse_cycle(&mut tx, into, from).await?;
96
1140
    refuse_budget_conflicts(&mut tx, into, from).await?;
97
1138
    let moving = tags_to_move(&account_tags(&mut tx, into).await?, &from_tags)?;
98
1136
    let moved = move_references(&mut tx, into, from).await?;
99
1136
    for tag_id in moving {
100
4
        sqlx::query_file!("sql/insert/account_tags/account_tag.sql", into, tag_id)
101
4
            .execute(&mut *tx)
102
4
            .await?;
103
    }
104
1136
    sqlx::query_file!("sql/delete/account_tags/by_account.sql", from)
105
1136
        .execute(&mut *tx)
106
1136
        .await?;
107
1136
    sqlx::query_file!("sql/delete/accounts/by_id.sql", from)
108
1136
        .execute(&mut *tx)
109
1136
        .await?;
110
1136
    for tag in &from_tags {
111
1141
        delete_tag_if_orphaned(&mut tx, tag.id).await?;
112
    }
113
1136
    match finish {
114
813
        Finish::Commit => tx.commit().await?,
115
323
        Finish::Rollback => tx.rollback().await?,
116
    }
117
1136
    Ok(moved)
118
1150
}
119

            
120
/// Lock both rows in id order: `from` for deletion, `into` as a writer.
121
2719
async fn lock_accounts(conn: &mut PgConnection, into: Uuid, from: Uuid) -> Result<(), Attempt> {
122
1147
    let mut ids = [into, from];
123
1147
    ids.sort();
124
1147
    for id in ids {
125
2289
        let row = match id == from {
126
1146
            true => sqlx::query_file!("sql/select/accounts/by_id_locked_for_delete.sql", id)
127
1146
                .fetch_optional(&mut *conn)
128
1146
                .await?
129
1142
                .map(|row| row.id),
130
1143
            false => sqlx::query_file!("sql/select/accounts/by_id_locked.sql", id)
131
1143
                .fetch_optional(&mut *conn)
132
1143
                .await?
133
1142
                .map(|row| row.id),
134
        };
135
2289
        if row.is_none() {
136
5
            return Err(CmdError::NotFound(format!("Account {id} not found")).into());
137
2284
        }
138
    }
139
1142
    Ok(())
140
1147
}
141

            
142
2177
async fn refuse_cycle(conn: &mut PgConnection, into: Uuid, from: Uuid) -> Result<(), Attempt> {
143
1142
    let is_descendant = sqlx::query_file!("sql/select/accounts/is_descendant.sql", into, from)
144
1142
        .fetch_one(conn)
145
1142
        .await?
146
        .is_descendant
147
1142
        .unwrap_or(false);
148
1142
    match is_descendant {
149
2
        true => Err(CmdError::Refused(
150
2
            "An account cannot be merged into one of its own sub-accounts".to_string(),
151
2
        )
152
2
        .into()),
153
1140
        false => Ok(()),
154
    }
155
1142
}
156

            
157
2175
async fn refuse_budget_conflicts(
158
2175
    conn: &mut PgConnection,
159
2175
    into: Uuid,
160
2175
    from: Uuid,
161
2175
) -> Result<(), Attempt> {
162
1140
    let conflicts = sqlx::query_file!("sql/select/budget_amounts/merge_conflicts.sql", into, from)
163
1140
        .fetch_all(conn)
164
1140
        .await?;
165
1140
    match conflicts.first() {
166
1138
        None => Ok(()),
167
2
        Some(row) => Err(CmdError::Refused(format!(
168
2
            "Both accounts have an amount for budget {} period {}; \
169
2
             resolve the budget before merging",
170
2
            row.budget_id, row.period_num
171
2
        ))
172
2
        .into()),
173
    }
174
1140
}
175

            
176
/// Moves everything referencing `from` to `into`; returns the splits moved.
177
2171
async fn move_references(conn: &mut PgConnection, into: Uuid, from: Uuid) -> Result<i64, Attempt> {
178
1136
    let moved = sqlx::query_file!("sql/update/splits/merge_account.sql", into, from)
179
1136
        .execute(&mut *conn)
180
1136
        .await?
181
        .rows_affected();
182
1136
    sqlx::query_file!("sql/update/lots/merge_account.sql", into, from)
183
1136
        .execute(&mut *conn)
184
1136
        .await?;
185
1136
    sqlx::query_file!("sql/update/budget_amounts/merge_account.sql", into, from)
186
1136
        .execute(&mut *conn)
187
1136
        .await?;
188
1136
    sqlx::query_file!("sql/update/books/merge_root_account.sql", into, from)
189
1136
        .execute(&mut *conn)
190
1136
        .await?;
191
1136
    sqlx::query_file!("sql/update/accounts/merge_children.sql", into, from)
192
1136
        .execute(&mut *conn)
193
1136
        .await?;
194
1136
    Ok(i64::try_from(moved).unwrap_or(i64::MAX))
195
1136
}
196

            
197
#[derive(Debug, Clone, PartialEq, Eq)]
198
pub(crate) struct StoredTag {
199
    pub(crate) id: Uuid,
200
    pub(crate) name: String,
201
    pub(crate) value: String,
202
}
203

            
204
7072
async fn account_tags(conn: &mut PgConnection, account: Uuid) -> Result<Vec<StoredTag>, Attempt> {
205
3430
    Ok(sqlx::query_file!("sql/select/tags/by_account.sql", account)
206
3430
        .fetch_all(conn)
207
3430
        .await?
208
        .into_iter()
209
        .map(|row| StoredTag {
210
3446
            id: row.id,
211
3446
            name: row.tag_name,
212
3446
            value: row.tag_value,
213
3446
        })
214
        .collect())
215
3430
}
216

            
217
4354
fn identities(tags: &[StoredTag]) -> BTreeSet<(Uuid, &str, &str)> {
218
4354
    tags.iter()
219
4368
        .map(|tag| (tag.id, tag.name.as_str(), tag.value.as_str()))
220
        .collect()
221
4354
}
222

            
223
/// Lock the stored keys of `from`'s tags through the tag lock protocol,
224
/// before any account row: edits and creates hold keys while they insert
225
/// splits. A concurrent rename of one of those tag rows makes this attempt
226
/// retry.
227
2722
async fn lock_from_tags(conn: &mut PgConnection, from: Uuid) -> Result<Vec<StoredTag>, Attempt> {
228
1150
    let tags = account_tags(conn, from).await?;
229
1150
    let touched: Vec<(Uuid, Key)> = tags
230
1150
        .iter()
231
1156
        .map(|tag| (tag.id, (tag.name.clone(), tag.value.clone())))
232
        .collect();
233
1150
    match lock(conn, &touched, &[]).await? {
234
1147
        Ok(()) => Ok(tags),
235
3
        Err(KeyChanged) => Err(Attempt::Retry),
236
    }
237
1150
}
238

            
239
/// Under the account locks `from` must still carry exactly the locked tags.
240
2177
async fn ensure_from_tags(
241
2177
    conn: &mut PgConnection,
242
2177
    from: Uuid,
243
2177
    locked: &[StoredTag],
244
2177
) -> Result<(), Attempt> {
245
1142
    match identities(&account_tags(conn, from).await?) == identities(locked) {
246
1142
        true => Ok(()),
247
        false => Err(Attempt::Retry),
248
    }
249
1142
}
250

            
251
/// The ids of `from`'s tags whose name `into` lacks. `into` keeps its `name`;
252
/// any other name both carry with different values is a refusal.
253
2175
pub(crate) fn tags_to_move(into: &[StoredTag], from: &[StoredTag]) -> Result<Vec<Uuid>, CmdError> {
254
2175
    let mut held: HashMap<&str, HashSet<&str>> = HashMap::new();
255
2175
    for tag in into {
256
2179
        held.entry(&tag.name).or_default().insert(&tag.value);
257
    }
258
2175
    let mut moving = Vec::new();
259
2175
    for tag in from {
260
2184
        match held.get(tag.name.as_str()) {
261
5
            None => moving.push(tag.id),
262
2179
            Some(_) if tag.name == "name" => {}
263
5
            Some(values) if values.contains(tag.value.as_str()) => {}
264
            Some(_) => {
265
3
                return Err(CmdError::Refused(format!(
266
3
                    "Both accounts carry the tag '{}' with different values",
267
3
                    tag.name
268
3
                )));
269
            }
270
        }
271
    }
272
2172
    Ok(moving)
273
2175
}