Lines
99.09 %
Functions
48.88 %
Branches
100 %
//! `UpdateTransaction`.
use crate::command::connection;
use finance::{split::Split, tag::Tag, transaction::Transaction};
use num_rational::Rational64;
use sqlx::{
PgConnection,
types::Uuid,
types::chrono::{DateTime, Utc},
};
use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use supp_macro::command;
use crate::attempt::{Attempt, Tries};
use crate::command::transaction::{account_gone, refuse_cross_price};
use crate::tag::lock::{KeyChanged, begin};
use crate::tag::user::delete_tag_if_orphaned;
use crate::user::User;
use std::convert::identity;
use crate::command::transaction_edit::{
add_split_tags, lock_edit_tags, note_tag, replace_transaction_tags, stored_split_tags,
stored_state, unlink_tags, validate_edit_tags,
use crate::command::{CmdError, CmdResult, FinanceEntity};
command! {
UpdateTransaction {
#[required]
user_id: Uuid,
transaction_id: Uuid,
#[optional]
splits: Vec<FinanceEntity>,
post_date: DateTime<Utc>,
enter_date: DateTime<Utc>,
note: String,
// `prices` replaces the prices linked to this transaction's splits; without it they
// stay, unless `splits` is given, which drops them with the old splits.
prices: Vec<FinanceEntity>,
// `tags` replaces all non-note transaction tags; the note changes only via `note`.
tags: HashMap<String, FinanceEntity>,
// `split_tags` are added to the splits as they exist after `splits` is applied.
split_tags: Vec<(Uuid, Tag)>,
// Refuse the update unless the locked transaction still has this revision.
expected_revision: String,
// Refuse, after the revision check, a transaction the logical form cannot keep.
refuse_unkeepable: bool,
// Per replacement split id, the fields that keep the stored split's value.
keep_stored: HashMap<Uuid, KeepStored>,
} => {
let user = User { id: user_id };
let mut conn = connection(&user).await?;
let edit = Edit {
transaction_id,
splits,
post_date,
enter_date,
note,
prices,
tags,
split_tags,
expected_revision,
refuse_unkeepable: refuse_unkeepable == Some(true),
keep_stored: keep_stored.unwrap_or_default(),
let mut tries = Tries::default();
loop {
let outcome = Attempt::of(
edit.attempt(&mut conn).await,
CmdError::is_retryable,
identity,
);
if let Some(updated) = tries.step(outcome)? {
return Ok(Some(CmdResult::Entity(FinanceEntity::Transaction(updated))));
}
/// The fields of a replacement split that keep the value of the stored split
/// with its id. A lot is kept only while the split stays in its account, the
/// reconcile state and date only while its account and amount are unchanged;
/// a split with no stored namesake keeps nothing.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct KeepStored {
pub reconcile_state: bool,
pub reconcile_date: bool,
pub lot_id: bool,
/// A split's reconcile state, reconcile date and lot.
type SplitState = (Option<bool>, Option<DateTime<Utc>>, Option<Uuid>);
impl KeepStored {
/// The state of `split`, each kept field taken from `stored` while it
/// still applies, else unset.
fn state(self, split: &Split, stored: &Split) -> SplitState {
let same_account = split.account_id == stored.account_id;
let same_amount = same_account
&& i128::from(split.value_num) * i128::from(stored.value_denom)
== i128::from(stored.value_num) * i128::from(split.value_denom);
(
kept(
self.reconcile_state,
same_amount,
split.reconcile_state,
stored.reconcile_state,
),
self.reconcile_date,
split.reconcile_date,
stored.reconcile_date,
kept(self.lot_id, same_account, split.lot_id, stored.lot_id),
)
/// `new` unless `keep`; when kept, `old` while it still `applies`, else unset.
fn kept<T>(keep: bool, applies: bool, new: Option<T>, old: Option<T>) -> Option<T> {
match (keep, applies) {
(false, _) => new,
(true, true) => old,
(true, false) => None,
/// The arguments of one `UpdateTransaction`, applied once per attempt.
struct Edit {
splits: Option<Vec<FinanceEntity>>,
post_date: Option<DateTime<Utc>>,
enter_date: Option<DateTime<Utc>>,
note: Option<String>,
prices: Option<Vec<FinanceEntity>>,
tags: Option<HashMap<String, FinanceEntity>>,
split_tags: Option<Vec<(Uuid, Tag)>>,
expected_revision: Option<String>,
impl Edit {
/// Apply the edit in one DB transaction: the transaction row lock, then
/// the tag lock protocol, then the guards, the writes and the deletion of
/// the tag rows the edit left unreferenced.
async fn attempt(
&self,
conn: &mut PgConnection,
) -> Result<Result<Transaction, KeyChanged>, CmdError> {
let mut tx = begin(conn).await?;
let existing = sqlx::query_file!(
"sql/select/transactions/by_id_locked.sql",
self.transaction_id
.fetch_optional(&mut *tx)
.await?
.ok_or_else(|| CmdError::NotFound("Transaction not found".to_string()))?;
refuse_cross_price(&mut tx, self.transaction_id).await?;
let linked = match lock_edit_tags(
&mut tx,
self.transaction_id,
self.tags.as_ref(),
self.split_tags.as_deref(),
self.note.as_deref(),
{
Ok(linked) => linked,
Err(changed) => {
tx.rollback().await?;
return Ok(Err(changed));
self.check_guards(&mut tx, existing.post_date).await?;
let updated = Transaction {
id: self.transaction_id,
post_date: self.post_date.unwrap_or(existing.post_date),
enter_date: self.enter_date.unwrap_or(existing.enter_date),
let new_split_ids = self.validate_splits()?;
sqlx::query_file!(
"sql/update/transactions/update.sql",
updated.id,
updated.post_date,
updated.enter_date
.execute(&mut *tx)
.await?;
let stored_split_tags = match self.split_tags {
Some(_) => stored_split_tags(&mut tx, self.transaction_id).await?,
None => Vec::new(),
self.clear_prices(&mut tx).await?;
self.replace_splits(&mut tx).await?;
self.validate_prices(&mut tx, new_split_ids).await?;
validate_edit_tags(self.tags.as_ref(), self.split_tags.as_deref())?;
self.insert_prices(&mut tx).await?;
if let Some(new_tags) = &self.tags {
replace_transaction_tags(&mut tx, self.transaction_id, new_tags).await?;
if let Some(new_split_tags) = &self.split_tags {
add_split_tags(
new_split_tags,
&stored_split_tags,
self.write_note(&mut tx).await?;
for tag_id in linked {
delete_tag_if_orphaned(&mut tx, tag_id).await?;
tx.commit().await?;
Ok(Ok(updated))
/// Refuse a stale revision or, when asked, an unkeepable transaction.
async fn check_guards(
) -> Result<(), CmdError> {
if self.expected_revision.is_none() && !self.refuse_unkeepable {
return Ok(());
let stored = stored_state(conn, self.transaction_id, post_date).await?;
if self
.expected_revision
.as_ref()
.is_some_and(|expected| stored.revision != *expected)
return Err(CmdError::Args(crate::logical::STALE_REVISION.to_string()));
if self.refuse_unkeepable {
stored.ensure_keepable()?;
Ok(())
/// The ids of the replacement splits, checked to belong to this
/// transaction and, for a single commodity, to sum to zero.
fn validate_splits(&self) -> Result<Option<HashSet<Uuid>>, CmdError> {
let Some(new_splits) = &self.splits else {
return Ok(None);
let mut commodity_sums: HashMap<Uuid, Rational64> = HashMap::new();
let mut ids = HashSet::new();
for entity in new_splits {
let FinanceEntity::Split(split) = entity else {
return Err(CmdError::Args("Invalid entity type in splits".to_string()));
if split.tx_id != self.transaction_id {
return Err(CmdError::Args("Split transaction ID mismatch".to_string()));
ids.insert(split.id);
*commodity_sums.entry(split.commodity_id).or_default() +=
Rational64::new(split.value_num, split.value_denom);
// A multi-currency transaction balances through its prices, not per commodity.
if commodity_sums.len() == 1
&& commodity_sums
.values()
.any(|sum| *sum != Rational64::default())
return Err(CmdError::Args("Splits must sum to zero".to_string()));
Ok(Some(ids))
/// Delete the stored prices of this transaction's splits when either the
/// prices or the splits are replaced.
async fn clear_prices(&self, conn: &mut PgConnection) -> Result<(), CmdError> {
if self.prices.is_none() && self.splits.is_none() {
sqlx::query_file!("sql/delete/prices/by_splits.sql", self.transaction_id)
.execute(&mut *conn)
/// Delete the stored splits with their split tags, then insert the
/// replacement splits.
async fn replace_splits(&self, conn: &mut PgConnection) -> Result<(), CmdError> {
let stored = self.stored_splits(conn).await?;
"sql/delete/split_tags/by_transaction.sql",
sqlx::query_file!("sql/delete/splits/by_transaction.sql", self.transaction_id)
if let FinanceEntity::Split(split) = entity {
let (reconcile_state, reconcile_date, lot_id) =
match (self.keep_stored.get(&split.id), stored.get(&split.id)) {
(Some(keep), Some(stored)) => keep.state(split, stored),
_ => (split.reconcile_state, split.reconcile_date, split.lot_id),
"sql/insert/splits/split.sql",
split.id,
split.tx_id,
split.account_id,
split.commodity_id,
reconcile_state,
reconcile_date,
split.value_num,
split.value_denom,
lot_id
.await
.map_err(|err| account_gone(err.into()))?;
/// The stored splits by id, read only when a replacement keeps a field.
async fn stored_splits(
) -> Result<HashMap<Uuid, Split>, CmdError> {
if self.keep_stored.is_empty() {
return Ok(HashMap::new());
Ok(sqlx::query_file_as!(
Split,
"sql/select/splits/by_transaction.sql",
.fetch_all(conn)
.into_iter()
.map(|split| (split.id, split))
.collect())
/// Every linked split of a new price must belong to this transaction's
/// post-update split set; the FK alone would accept a foreign split.
async fn validate_prices(
new_split_ids: Option<HashSet<Uuid>>,
let Some(new_prices) = &self.prices else {
let valid_split_ids = match new_split_ids {
Some(ids) => ids,
None => sqlx::query_file!("sql/select/splits/by_transaction.sql", self.transaction_id)
.fetch_all(&mut *conn)
.map(|row| row.id)
.collect(),
for entity in new_prices {
let FinanceEntity::Price(price) = entity else {
return Err(CmdError::Args("Invalid entity type in prices".to_string()));
let foreign = [price.commodity_split, price.currency_split]
.flatten()
.any(|split_id| !valid_split_ids.contains(&split_id));
if foreign {
return Err(CmdError::Args(
"Price references a split that is not part of this transaction".to_string(),
));
async fn insert_prices(&self, conn: &mut PgConnection) -> Result<(), CmdError> {
for entity in self.prices.iter().flatten() {
if let FinanceEntity::Price(price) = entity {
"sql/insert/prices/price.sql",
price.id,
price.commodity_id,
price.currency_id,
price.commodity_split,
price.currency_split,
price.date,
price.value_num,
price.value_denom
/// Replace the note tag; a blank note removes it.
async fn write_note(&self, conn: &mut PgConnection) -> Result<(), CmdError> {
let Some(note_value) = &self.note else {
unlink_tags(conn, self.transaction_id, true).await?;
if !note_value.trim().is_empty() {
let note_tag_id = note_tag(note_value).commit(&mut *conn).await?;
"sql/insert/transaction_tags/transaction_tag.sql",
note_tag_id