Skip to main content

server/command/transaction/
update.rs

1//! `UpdateTransaction`.
2
3use crate::command::connection;
4use finance::{split::Split, tag::Tag, transaction::Transaction};
5use num_rational::Rational64;
6use sqlx::{
7    PgConnection,
8    types::Uuid,
9    types::chrono::{DateTime, Utc},
10};
11use std::collections::{HashMap, HashSet};
12use std::fmt::Debug;
13use supp_macro::command;
14
15use crate::attempt::{Attempt, Tries};
16use crate::command::transaction::{account_gone, refuse_cross_price};
17use crate::tag::lock::{KeyChanged, begin};
18use crate::tag::user::delete_tag_if_orphaned;
19use crate::user::User;
20use std::convert::identity;
21
22use crate::command::transaction_edit::{
23    add_split_tags, lock_edit_tags, note_tag, replace_transaction_tags, stored_split_tags,
24    stored_state, unlink_tags, validate_edit_tags,
25};
26use crate::command::{CmdError, CmdResult, FinanceEntity};
27
28command! {
29    UpdateTransaction {
30        #[required]
31        user_id: Uuid,
32        #[required]
33        transaction_id: Uuid,
34        #[optional]
35        splits: Vec<FinanceEntity>,
36        #[optional]
37        post_date: DateTime<Utc>,
38        #[optional]
39        enter_date: DateTime<Utc>,
40        #[optional]
41        note: String,
42        // `prices` replaces the prices linked to this transaction's splits; without it they
43        // stay, unless `splits` is given, which drops them with the old splits.
44        #[optional]
45        prices: Vec<FinanceEntity>,
46        // `tags` replaces all non-note transaction tags; the note changes only via `note`.
47        #[optional]
48        tags: HashMap<String, FinanceEntity>,
49        // `split_tags` are added to the splits as they exist after `splits` is applied.
50        #[optional]
51        split_tags: Vec<(Uuid, Tag)>,
52        // Refuse the update unless the locked transaction still has this revision.
53        #[optional]
54        expected_revision: String,
55        // Refuse, after the revision check, a transaction the logical form cannot keep.
56        #[optional]
57        refuse_unkeepable: bool,
58        // Per replacement split id, the fields that keep the stored split's value.
59        #[optional]
60        keep_stored: HashMap<Uuid, KeepStored>,
61    } => {
62        let user = User { id: user_id };
63        let mut conn = connection(&user).await?;
64        let edit = Edit {
65            transaction_id,
66            splits,
67            post_date,
68            enter_date,
69            note,
70            prices,
71            tags,
72            split_tags,
73            expected_revision,
74            refuse_unkeepable: refuse_unkeepable == Some(true),
75            keep_stored: keep_stored.unwrap_or_default(),
76        };
77        let mut tries = Tries::default();
78        loop {
79            let outcome = Attempt::of(
80                edit.attempt(&mut conn).await,
81                CmdError::is_retryable,
82                identity,
83            );
84            if let Some(updated) = tries.step(outcome)? {
85                return Ok(Some(CmdResult::Entity(FinanceEntity::Transaction(updated))));
86            }
87        }
88    }
89}
90
91/// The fields of a replacement split that keep the value of the stored split
92/// with its id. A lot is kept only while the split stays in its account, the
93/// reconcile state and date only while its account and amount are unchanged;
94/// a split with no stored namesake keeps nothing.
95#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
96pub struct KeepStored {
97    pub reconcile_state: bool,
98    pub reconcile_date: bool,
99    pub lot_id: bool,
100}
101
102/// A split's reconcile state, reconcile date and lot.
103type SplitState = (Option<bool>, Option<DateTime<Utc>>, Option<Uuid>);
104
105impl KeepStored {
106    /// The state of `split`, each kept field taken from `stored` while it
107    /// still applies, else unset.
108    fn state(self, split: &Split, stored: &Split) -> SplitState {
109        let same_account = split.account_id == stored.account_id;
110        let same_amount = same_account
111            && i128::from(split.value_num) * i128::from(stored.value_denom)
112                == i128::from(stored.value_num) * i128::from(split.value_denom);
113        (
114            kept(
115                self.reconcile_state,
116                same_amount,
117                split.reconcile_state,
118                stored.reconcile_state,
119            ),
120            kept(
121                self.reconcile_date,
122                same_amount,
123                split.reconcile_date,
124                stored.reconcile_date,
125            ),
126            kept(self.lot_id, same_account, split.lot_id, stored.lot_id),
127        )
128    }
129}
130
131/// `new` unless `keep`; when kept, `old` while it still `applies`, else unset.
132fn kept<T>(keep: bool, applies: bool, new: Option<T>, old: Option<T>) -> Option<T> {
133    match (keep, applies) {
134        (false, _) => new,
135        (true, true) => old,
136        (true, false) => None,
137    }
138}
139
140/// The arguments of one `UpdateTransaction`, applied once per attempt.
141struct Edit {
142    transaction_id: Uuid,
143    splits: Option<Vec<FinanceEntity>>,
144    post_date: Option<DateTime<Utc>>,
145    enter_date: Option<DateTime<Utc>>,
146    note: Option<String>,
147    prices: Option<Vec<FinanceEntity>>,
148    tags: Option<HashMap<String, FinanceEntity>>,
149    split_tags: Option<Vec<(Uuid, Tag)>>,
150    expected_revision: Option<String>,
151    refuse_unkeepable: bool,
152    keep_stored: HashMap<Uuid, KeepStored>,
153}
154
155impl Edit {
156    /// Apply the edit in one DB transaction: the transaction row lock, then
157    /// the tag lock protocol, then the guards, the writes and the deletion of
158    /// the tag rows the edit left unreferenced.
159    async fn attempt(
160        &self,
161        conn: &mut PgConnection,
162    ) -> Result<Result<Transaction, KeyChanged>, CmdError> {
163        let mut tx = begin(conn).await?;
164        let existing = sqlx::query_file!(
165            "sql/select/transactions/by_id_locked.sql",
166            self.transaction_id
167        )
168        .fetch_optional(&mut *tx)
169        .await?
170        .ok_or_else(|| CmdError::NotFound("Transaction not found".to_string()))?;
171
172        refuse_cross_price(&mut tx, self.transaction_id).await?;
173        let linked = match lock_edit_tags(
174            &mut tx,
175            self.transaction_id,
176            self.tags.as_ref(),
177            self.split_tags.as_deref(),
178            self.note.as_deref(),
179        )
180        .await?
181        {
182            Ok(linked) => linked,
183            Err(changed) => {
184                tx.rollback().await?;
185                return Ok(Err(changed));
186            }
187        };
188        self.check_guards(&mut tx, existing.post_date).await?;
189
190        let updated = Transaction {
191            id: self.transaction_id,
192            post_date: self.post_date.unwrap_or(existing.post_date),
193            enter_date: self.enter_date.unwrap_or(existing.enter_date),
194        };
195        let new_split_ids = self.validate_splits()?;
196
197        sqlx::query_file!(
198            "sql/update/transactions/update.sql",
199            updated.id,
200            updated.post_date,
201            updated.enter_date
202        )
203        .execute(&mut *tx)
204        .await?;
205
206        let stored_split_tags = match self.split_tags {
207            Some(_) => stored_split_tags(&mut tx, self.transaction_id).await?,
208            None => Vec::new(),
209        };
210        self.clear_prices(&mut tx).await?;
211        self.replace_splits(&mut tx).await?;
212        self.validate_prices(&mut tx, new_split_ids).await?;
213        validate_edit_tags(self.tags.as_ref(), self.split_tags.as_deref())?;
214        self.insert_prices(&mut tx).await?;
215
216        if let Some(new_tags) = &self.tags {
217            replace_transaction_tags(&mut tx, self.transaction_id, new_tags).await?;
218        }
219        if let Some(new_split_tags) = &self.split_tags {
220            add_split_tags(
221                &mut tx,
222                self.transaction_id,
223                new_split_tags,
224                &stored_split_tags,
225            )
226            .await?;
227        }
228        self.write_note(&mut tx).await?;
229        for tag_id in linked {
230            delete_tag_if_orphaned(&mut tx, tag_id).await?;
231        }
232
233        tx.commit().await?;
234        Ok(Ok(updated))
235    }
236
237    /// Refuse a stale revision or, when asked, an unkeepable transaction.
238    async fn check_guards(
239        &self,
240        conn: &mut PgConnection,
241        post_date: DateTime<Utc>,
242    ) -> Result<(), CmdError> {
243        if self.expected_revision.is_none() && !self.refuse_unkeepable {
244            return Ok(());
245        }
246        let stored = stored_state(conn, self.transaction_id, post_date).await?;
247        if self
248            .expected_revision
249            .as_ref()
250            .is_some_and(|expected| stored.revision != *expected)
251        {
252            return Err(CmdError::Args(crate::logical::STALE_REVISION.to_string()));
253        }
254        if self.refuse_unkeepable {
255            stored.ensure_keepable()?;
256        }
257        Ok(())
258    }
259
260    /// The ids of the replacement splits, checked to belong to this
261    /// transaction and, for a single commodity, to sum to zero.
262    fn validate_splits(&self) -> Result<Option<HashSet<Uuid>>, CmdError> {
263        let Some(new_splits) = &self.splits else {
264            return Ok(None);
265        };
266        let mut commodity_sums: HashMap<Uuid, Rational64> = HashMap::new();
267        let mut ids = HashSet::new();
268        for entity in new_splits {
269            let FinanceEntity::Split(split) = entity else {
270                return Err(CmdError::Args("Invalid entity type in splits".to_string()));
271            };
272            if split.tx_id != self.transaction_id {
273                return Err(CmdError::Args("Split transaction ID mismatch".to_string()));
274            }
275            ids.insert(split.id);
276            *commodity_sums.entry(split.commodity_id).or_default() +=
277                Rational64::new(split.value_num, split.value_denom);
278        }
279        // A multi-currency transaction balances through its prices, not per commodity.
280        if commodity_sums.len() == 1
281            && commodity_sums
282                .values()
283                .any(|sum| *sum != Rational64::default())
284        {
285            return Err(CmdError::Args("Splits must sum to zero".to_string()));
286        }
287        Ok(Some(ids))
288    }
289
290    /// Delete the stored prices of this transaction's splits when either the
291    /// prices or the splits are replaced.
292    async fn clear_prices(&self, conn: &mut PgConnection) -> Result<(), CmdError> {
293        if self.prices.is_none() && self.splits.is_none() {
294            return Ok(());
295        }
296        sqlx::query_file!("sql/delete/prices/by_splits.sql", self.transaction_id)
297            .execute(&mut *conn)
298            .await?;
299        Ok(())
300    }
301
302    /// Delete the stored splits with their split tags, then insert the
303    /// replacement splits.
304    async fn replace_splits(&self, conn: &mut PgConnection) -> Result<(), CmdError> {
305        let Some(new_splits) = &self.splits else {
306            return Ok(());
307        };
308        let stored = self.stored_splits(conn).await?;
309        sqlx::query_file!(
310            "sql/delete/split_tags/by_transaction.sql",
311            self.transaction_id
312        )
313        .execute(&mut *conn)
314        .await?;
315        sqlx::query_file!("sql/delete/splits/by_transaction.sql", self.transaction_id)
316            .execute(&mut *conn)
317            .await?;
318        for entity in new_splits {
319            if let FinanceEntity::Split(split) = entity {
320                let (reconcile_state, reconcile_date, lot_id) =
321                    match (self.keep_stored.get(&split.id), stored.get(&split.id)) {
322                        (Some(keep), Some(stored)) => keep.state(split, stored),
323                        _ => (split.reconcile_state, split.reconcile_date, split.lot_id),
324                    };
325                sqlx::query_file!(
326                    "sql/insert/splits/split.sql",
327                    split.id,
328                    split.tx_id,
329                    split.account_id,
330                    split.commodity_id,
331                    reconcile_state,
332                    reconcile_date,
333                    split.value_num,
334                    split.value_denom,
335                    lot_id
336                )
337                .execute(&mut *conn)
338                .await
339                .map_err(|err| account_gone(err.into()))?;
340            }
341        }
342        Ok(())
343    }
344
345    /// The stored splits by id, read only when a replacement keeps a field.
346    async fn stored_splits(
347        &self,
348        conn: &mut PgConnection,
349    ) -> Result<HashMap<Uuid, Split>, CmdError> {
350        if self.keep_stored.is_empty() {
351            return Ok(HashMap::new());
352        }
353        Ok(sqlx::query_file_as!(
354            Split,
355            "sql/select/splits/by_transaction.sql",
356            self.transaction_id
357        )
358        .fetch_all(conn)
359        .await?
360        .into_iter()
361        .map(|split| (split.id, split))
362        .collect())
363    }
364
365    /// Every linked split of a new price must belong to this transaction's
366    /// post-update split set; the FK alone would accept a foreign split.
367    async fn validate_prices(
368        &self,
369        conn: &mut PgConnection,
370        new_split_ids: Option<HashSet<Uuid>>,
371    ) -> Result<(), CmdError> {
372        let Some(new_prices) = &self.prices else {
373            return Ok(());
374        };
375        let valid_split_ids = match new_split_ids {
376            Some(ids) => ids,
377            None => sqlx::query_file!("sql/select/splits/by_transaction.sql", self.transaction_id)
378                .fetch_all(&mut *conn)
379                .await?
380                .into_iter()
381                .map(|row| row.id)
382                .collect(),
383        };
384        for entity in new_prices {
385            let FinanceEntity::Price(price) = entity else {
386                return Err(CmdError::Args("Invalid entity type in prices".to_string()));
387            };
388            let foreign = [price.commodity_split, price.currency_split]
389                .into_iter()
390                .flatten()
391                .any(|split_id| !valid_split_ids.contains(&split_id));
392            if foreign {
393                return Err(CmdError::Args(
394                    "Price references a split that is not part of this transaction".to_string(),
395                ));
396            }
397        }
398        Ok(())
399    }
400
401    async fn insert_prices(&self, conn: &mut PgConnection) -> Result<(), CmdError> {
402        for entity in self.prices.iter().flatten() {
403            if let FinanceEntity::Price(price) = entity {
404                sqlx::query_file!(
405                    "sql/insert/prices/price.sql",
406                    price.id,
407                    price.commodity_id,
408                    price.currency_id,
409                    price.commodity_split,
410                    price.currency_split,
411                    price.date,
412                    price.value_num,
413                    price.value_denom
414                )
415                .execute(&mut *conn)
416                .await?;
417            }
418        }
419        Ok(())
420    }
421
422    /// Replace the note tag; a blank note removes it.
423    async fn write_note(&self, conn: &mut PgConnection) -> Result<(), CmdError> {
424        let Some(note_value) = &self.note else {
425            return Ok(());
426        };
427        unlink_tags(conn, self.transaction_id, true).await?;
428        if !note_value.trim().is_empty() {
429            let note_tag_id = note_tag(note_value).commit(&mut *conn).await?;
430            sqlx::query_file!(
431                "sql/insert/transaction_tags/transaction_tag.sql",
432                self.transaction_id,
433                note_tag_id
434            )
435            .execute(&mut *conn)
436            .await?;
437        }
438        Ok(())
439    }
440}