1use crate::command::connection;
5use std::collections::{BTreeSet, HashMap, HashSet};
6
7use sqlx::{PgConnection, types::Uuid};
8use supp_macro::command;
9
10use super::attempt::Attempt;
11use super::{CmdError, CmdResult};
12use crate::attempt::Tries;
13use 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
22command! {
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}
35
36command! {
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}
49
50#[derive(Clone, Copy)]
52enum Finish {
53 Commit,
54 Rollback,
55}
56
57async fn run_merge(user_id: Uuid, into: Uuid, from: Uuid, finish: Finish) -> Result<i64, CmdError> {
58 if into == from {
59 return Err(CmdError::Refused(
60 "An account cannot be merged into itself".to_string(),
61 ));
62 }
63 let user = User { id: user_id };
64 let mut conn = connection(&user).await?;
65 merge_with_retry(&mut conn, user_id, into, from, finish).await
66}
67
68async fn merge_with_retry(
69 conn: &mut PgConnection,
70 user_id: Uuid,
71 into: Uuid,
72 from: Uuid,
73 finish: Finish,
74) -> Result<i64, CmdError> {
75 let mut tries = Tries::default();
76 loop {
77 if let Some(moved) = tries.step(merge_once(conn, user_id, into, from, finish).await)? {
78 return Ok(moved);
79 }
80 }
81}
82
83async fn merge_once(
84 conn: &mut PgConnection,
85 user_id: Uuid,
86 into: Uuid,
87 from: Uuid,
88 finish: Finish,
89) -> Result<i64, Attempt> {
90 let mut tx = begin(conn).await?;
91 lock_hierarchy(&mut tx, user_id).await?;
92 let from_tags = lock_from_tags(&mut tx, from).await?;
93 lock_accounts(&mut tx, into, from).await?;
94 ensure_from_tags(&mut tx, from, &from_tags).await?;
95 refuse_cycle(&mut tx, into, from).await?;
96 refuse_budget_conflicts(&mut tx, into, from).await?;
97 let moving = tags_to_move(&account_tags(&mut tx, into).await?, &from_tags)?;
98 let moved = move_references(&mut tx, into, from).await?;
99 for tag_id in moving {
100 sqlx::query_file!("sql/insert/account_tags/account_tag.sql", into, tag_id)
101 .execute(&mut *tx)
102 .await?;
103 }
104 sqlx::query_file!("sql/delete/account_tags/by_account.sql", from)
105 .execute(&mut *tx)
106 .await?;
107 sqlx::query_file!("sql/delete/accounts/by_id.sql", from)
108 .execute(&mut *tx)
109 .await?;
110 for tag in &from_tags {
111 delete_tag_if_orphaned(&mut tx, tag.id).await?;
112 }
113 match finish {
114 Finish::Commit => tx.commit().await?,
115 Finish::Rollback => tx.rollback().await?,
116 }
117 Ok(moved)
118}
119
120async fn lock_accounts(conn: &mut PgConnection, into: Uuid, from: Uuid) -> Result<(), Attempt> {
122 let mut ids = [into, from];
123 ids.sort();
124 for id in ids {
125 let row = match id == from {
126 true => sqlx::query_file!("sql/select/accounts/by_id_locked_for_delete.sql", id)
127 .fetch_optional(&mut *conn)
128 .await?
129 .map(|row| row.id),
130 false => sqlx::query_file!("sql/select/accounts/by_id_locked.sql", id)
131 .fetch_optional(&mut *conn)
132 .await?
133 .map(|row| row.id),
134 };
135 if row.is_none() {
136 return Err(CmdError::NotFound(format!("Account {id} not found")).into());
137 }
138 }
139 Ok(())
140}
141
142async fn refuse_cycle(conn: &mut PgConnection, into: Uuid, from: Uuid) -> Result<(), Attempt> {
143 let is_descendant = sqlx::query_file!("sql/select/accounts/is_descendant.sql", into, from)
144 .fetch_one(conn)
145 .await?
146 .is_descendant
147 .unwrap_or(false);
148 match is_descendant {
149 true => Err(CmdError::Refused(
150 "An account cannot be merged into one of its own sub-accounts".to_string(),
151 )
152 .into()),
153 false => Ok(()),
154 }
155}
156
157async fn refuse_budget_conflicts(
158 conn: &mut PgConnection,
159 into: Uuid,
160 from: Uuid,
161) -> Result<(), Attempt> {
162 let conflicts = sqlx::query_file!("sql/select/budget_amounts/merge_conflicts.sql", into, from)
163 .fetch_all(conn)
164 .await?;
165 match conflicts.first() {
166 None => Ok(()),
167 Some(row) => Err(CmdError::Refused(format!(
168 "Both accounts have an amount for budget {} period {}; \
169 resolve the budget before merging",
170 row.budget_id, row.period_num
171 ))
172 .into()),
173 }
174}
175
176async fn move_references(conn: &mut PgConnection, into: Uuid, from: Uuid) -> Result<i64, Attempt> {
178 let moved = sqlx::query_file!("sql/update/splits/merge_account.sql", into, from)
179 .execute(&mut *conn)
180 .await?
181 .rows_affected();
182 sqlx::query_file!("sql/update/lots/merge_account.sql", into, from)
183 .execute(&mut *conn)
184 .await?;
185 sqlx::query_file!("sql/update/budget_amounts/merge_account.sql", into, from)
186 .execute(&mut *conn)
187 .await?;
188 sqlx::query_file!("sql/update/books/merge_root_account.sql", into, from)
189 .execute(&mut *conn)
190 .await?;
191 sqlx::query_file!("sql/update/accounts/merge_children.sql", into, from)
192 .execute(&mut *conn)
193 .await?;
194 Ok(i64::try_from(moved).unwrap_or(i64::MAX))
195}
196
197#[derive(Debug, Clone, PartialEq, Eq)]
198pub(crate) struct StoredTag {
199 pub(crate) id: Uuid,
200 pub(crate) name: String,
201 pub(crate) value: String,
202}
203
204async fn account_tags(conn: &mut PgConnection, account: Uuid) -> Result<Vec<StoredTag>, Attempt> {
205 Ok(sqlx::query_file!("sql/select/tags/by_account.sql", account)
206 .fetch_all(conn)
207 .await?
208 .into_iter()
209 .map(|row| StoredTag {
210 id: row.id,
211 name: row.tag_name,
212 value: row.tag_value,
213 })
214 .collect())
215}
216
217fn identities(tags: &[StoredTag]) -> BTreeSet<(Uuid, &str, &str)> {
218 tags.iter()
219 .map(|tag| (tag.id, tag.name.as_str(), tag.value.as_str()))
220 .collect()
221}
222
223async fn lock_from_tags(conn: &mut PgConnection, from: Uuid) -> Result<Vec<StoredTag>, Attempt> {
228 let tags = account_tags(conn, from).await?;
229 let touched: Vec<(Uuid, Key)> = tags
230 .iter()
231 .map(|tag| (tag.id, (tag.name.clone(), tag.value.clone())))
232 .collect();
233 match lock(conn, &touched, &[]).await? {
234 Ok(()) => Ok(tags),
235 Err(KeyChanged) => Err(Attempt::Retry),
236 }
237}
238
239async fn ensure_from_tags(
241 conn: &mut PgConnection,
242 from: Uuid,
243 locked: &[StoredTag],
244) -> Result<(), Attempt> {
245 match identities(&account_tags(conn, from).await?) == identities(locked) {
246 true => Ok(()),
247 false => Err(Attempt::Retry),
248 }
249}
250
251pub(crate) fn tags_to_move(into: &[StoredTag], from: &[StoredTag]) -> Result<Vec<Uuid>, CmdError> {
254 let mut held: HashMap<&str, HashSet<&str>> = HashMap::new();
255 for tag in into {
256 held.entry(&tag.name).or_default().insert(&tag.value);
257 }
258 let mut moving = Vec::new();
259 for tag in from {
260 match held.get(tag.name.as_str()) {
261 None => moving.push(tag.id),
262 Some(_) if tag.name == "name" => {}
263 Some(values) if values.contains(tag.value.as_str()) => {}
264 Some(_) => {
265 return Err(CmdError::Refused(format!(
266 "Both accounts carry the tag '{}' with different values",
267 tag.name
268 )));
269 }
270 }
271 }
272 Ok(moving)
273}