Skip to main content

finance/
transaction.rs

1use crate::error::{FinanceError, TransactionError};
2use crate::price::Price;
3use crate::split::Split;
4use crate::tag::Tag;
5use itertools::Itertools;
6use num_rational::Rational64;
7use num_traits::{CheckedAdd, CheckedMul, Signed};
8use sqlx::types::Uuid;
9use sqlx::types::chrono::{DateTime, Utc};
10use sqlx::{Connection, Postgres, query_file};
11use std::collections::{HashMap, HashSet};
12use supp_macro::Builder;
13
14/// The Transaction which is a start point of all the accounting.
15///
16/// A `Transaction` keeps id of a financial event and is used to group `Split`s
17/// using all the features provided.
18///
19/// # Attributes
20/// - `id`: A unique identifier for the transaction.
21/// - `commodity`: A reference to the `Commodity` associated of this transaction.
22/// - `num`: An optional number or code associated with the transaction.
23/// - `post_date`: The date the transaction is performed.
24/// - `enter_date`: The date the transaction is entered.
25/// - `description`: An optional description of the transaction.
26#[derive(Debug, sqlx::FromRow, Builder)]
27#[builder(error_kind = "FinanceError")]
28pub struct Transaction {
29    pub id: Uuid,
30    pub post_date: DateTime<Utc>,
31    pub enter_date: DateTime<Utc>,
32}
33
34/// A price turning the value of one of its splits into the other side's
35/// commodity `into`: the commodity split by the rate, else the currency split
36/// by its inverse.
37pub(crate) struct Conversion {
38    pub(crate) split: Uuid,
39    pub(crate) into: Uuid,
40    pub(crate) rate: Rational64,
41}
42
43/// A stored price with the splits it links, its rate already a valid rational.
44pub(crate) struct PriceLink {
45    pub(crate) commodity_id: Uuid,
46    pub(crate) currency_id: Uuid,
47    pub(crate) commodity_split: Option<Uuid>,
48    pub(crate) currency_split: Option<Uuid>,
49    pub(crate) rate: Rational64,
50}
51
52/// A rational from stored parts; a non-positive denominator is an error,
53/// never a panic.
54pub(crate) fn ratio(num: i64, denom: i64) -> Result<Rational64, FinanceError> {
55    match denom > 0 {
56        true => Ok(Rational64::new(num, denom)),
57        false => Err(FinanceError::Transaction(TransactionError::Build(
58            t!("Value denominator must be positive").to_string(),
59        ))),
60    }
61}
62
63fn price_error(message: &str) -> FinanceError {
64    FinanceError::Transaction(TransactionError::Build(message.to_string()))
65}
66
67/// Checks a price against the transaction splits (`held`: split to
68/// commodity) and returns the conversion it defines. The commodity split is
69/// converted by the rate; a currency-only price by the inverse rate.
70fn conversion(price: &PriceLink, held: &HashMap<Uuid, Uuid>) -> Result<Conversion, FinanceError> {
71    if !price.rate.is_positive() {
72        return Err(price_error(&t!("Price rate must be positive")));
73    }
74    let side = |split: Option<Uuid>, commodity: Uuid| -> Result<Option<Uuid>, FinanceError> {
75        match split {
76            None => Ok(None),
77            Some(id) if held.get(&id) == Some(&commodity) => Ok(Some(id)),
78            Some(_) => Err(price_error(&t!(
79                "Price commodities do not match the linked splits"
80            ))),
81        }
82    };
83    let commodity = side(price.commodity_split, price.commodity_id)?;
84    let currency = side(price.currency_split, price.currency_id)?;
85    match (commodity, currency) {
86        (Some(split), _) => Ok(Conversion {
87            split,
88            into: price.currency_id,
89            rate: price.rate,
90        }),
91        (None, Some(split)) => Ok(Conversion {
92            split,
93            into: price.commodity_id,
94            rate: price.rate.recip(),
95        }),
96        (None, None) => Err(price_error(&t!("Price is not linked to a split"))),
97    }
98}
99
100/// The conversions of `prices`, each split linked by at most one price.
101pub(crate) fn conversions(
102    prices: &[PriceLink],
103    held: &HashMap<Uuid, Uuid>,
104) -> Result<Vec<Conversion>, FinanceError> {
105    let mut linked: HashSet<Uuid> = HashSet::new();
106    for split in prices
107        .iter()
108        .flat_map(|p| [p.commodity_split, p.currency_split])
109        .flatten()
110    {
111        if !linked.insert(split) {
112            return Err(price_error(&t!("Split is linked by several prices")));
113        }
114    }
115    prices.iter().map(|p| conversion(p, held)).collect()
116}
117
118/// Whether `(split, commodity, value)` legs sum to zero in every commodity
119/// once each split a price converts is counted in the price's other
120/// commodity; the other splits count in their own, so a converted pair
121/// balances beside any same-commodity pairs.
122/// An overflowing sum or conversion does not balance.
123pub(crate) fn balances(legs: &[(Uuid, Uuid, Rational64)], conversions: &[Conversion]) -> bool {
124    let mut sums: HashMap<Uuid, Rational64> = HashMap::new();
125    for (split, commodity, value) in legs {
126        let converted = match conversions.iter().find(|c| c.split == *split) {
127            Some(conversion) => value
128                .checked_mul(&conversion.rate)
129                .map(|amount| (conversion.into, amount)),
130            None => Some((*commodity, *value)),
131        };
132        let Some((into, amount)) = converted else {
133            return false;
134        };
135        let sum = sums.entry(into).or_default();
136        let Some(total) = sum.checked_add(&amount) else {
137            return false;
138        };
139        *sum = total;
140    }
141    sums.values().all(|sum| *sum == Rational64::from_integer(0))
142}
143
144/// An active ticket for a semi-entered transaction.
145///
146/// A `TransactionTicket` manages the lifecycle of the `Transaction`, allowing
147/// for explicit commit or rollback operations. It ensures that any changes
148/// made within the transaction are properly finalized or reverted.
149///
150/// # Generic Lifetimes
151/// - `'t`: Lifetime of the referenced `Transaction`.
152/// - `'s`: Lifetime of the `SQLx` transaction.
153pub struct TransactionTicket<'t, 's> {
154    sqltx: Option<sqlx::Transaction<'s, Postgres>>,
155    tx: &'t Transaction,
156}
157
158impl<'t> TransactionTicket<'t, '_> {
159    /// Validates the inputs and commits the transaction, finalizing all
160    /// changes.
161    ///
162    /// # Returns
163    /// A reference to the original `Transaction` if the commit is successful.
164    ///
165    /// # Errors
166    /// Returns a `FinanceError` if the ticket is empty or the commit operation fails.
167    pub async fn commit(&mut self) -> Result<&'t Transaction, FinanceError> {
168        if let Some(mut sqltx) = self.sqltx.take() {
169            let splits = query_file!("sql/transaction_select_splits.sql", &self.tx.id)
170                .fetch_all(&mut *sqltx)
171                .await?;
172
173            let distinct_commodities: Vec<Uuid> =
174                splits.iter().map(|s| s.commodity_id).unique().collect();
175
176            if distinct_commodities.is_empty() {
177                return Err(FinanceError::Internal(
178                    t!("No splits found for this transaction").to_string(),
179                ));
180            }
181
182            if distinct_commodities.len() == 1 {
183                let sum_splits = splits
184                    .iter()
185                    .map(|s| ratio(s.value_num, s.value_denom))
186                    .collect::<Result<Vec<_>, _>>()?
187                    .into_iter()
188                    .try_fold(Rational64::default(), |a, b| a.checked_add(&b))
189                    .ok_or_else(|| FinanceError::Internal(t!("Erroneous split").to_string()))?;
190
191                if sum_splits != 0.into() {
192                    return Err(FinanceError::Transaction(TransactionError::Build(
193                        t!("Unbalanced Transaction: sum of splits is non-zero").to_string(),
194                    )));
195                }
196            } else {
197                let split_ids: Vec<Uuid> = splits.iter().map(|s| s.id).collect();
198                let prices = query_file!("sql/transaction_select_prices_by_splits.sql", &split_ids)
199                    .fetch_all(&mut *sqltx)
200                    .await?;
201                let links = prices
202                    .iter()
203                    .map(|p| {
204                        Ok(PriceLink {
205                            commodity_id: p.commodity_id,
206                            currency_id: p.currency_id,
207                            commodity_split: p.commodity_split_id,
208                            currency_split: p.currency_split_id,
209                            rate: ratio(p.value_num, p.value_denom)?,
210                        })
211                    })
212                    .collect::<Result<Vec<_>, FinanceError>>()?;
213                let held: HashMap<Uuid, Uuid> =
214                    splits.iter().map(|s| (s.id, s.commodity_id)).collect();
215                let conversions = conversions(&links, &held)?;
216                let legs = splits
217                    .iter()
218                    .map(|s| Ok((s.id, s.commodity_id, ratio(s.value_num, s.value_denom)?)))
219                    .collect::<Result<Vec<_>, FinanceError>>()?;
220                if !balances(&legs, &conversions) {
221                    return Err(FinanceError::Transaction(TransactionError::Build(
222                        t!("Unbalanced Transaction after conversion: sum != 0").to_string(),
223                    )));
224                }
225            }
226
227            sqltx.commit().await?;
228            Ok(self.tx)
229        } else {
230            Err(FinanceError::Internal(
231                t!("Attempt to commit the empty ticket").to_string(),
232            ))
233        }
234    }
235
236    /// Rolls back the transaction, reverting all changes.
237    ///
238    /// # Returns
239    /// A reference to the original `Transaction` if the rollback is successful.
240    ///
241    /// # Errors
242    /// Returns a `FinanceError` if the ticket is empty or the rollback operation fails.
243    pub async fn rollback(&mut self) -> Result<&'t Transaction, FinanceError> {
244        if let Some(sqltx) = self.sqltx.take() {
245            sqltx.rollback().await?;
246            Ok(self.tx)
247        } else {
248            Err(FinanceError::Internal(
249                t!("Attempt to rollback the empty ticket").to_string(),
250            ))
251        }
252    }
253
254    pub async fn add_splits(&mut self, splits: &[&Split]) -> Result<&'t Transaction, FinanceError> {
255        if let Some(sqltx) = &mut self.sqltx {
256            for s in splits {
257                if s.tx_id != self.tx.id {
258                    return Err(FinanceError::Transaction(TransactionError::WrongSplit(
259                        t!("Attempt to apply split from another transaction").to_string(),
260                    )));
261                }
262                query_file!(
263                    "sql/split_insert.sql",
264                    &s.id,
265                    &s.tx_id,
266                    &s.account_id,
267                    &s.commodity_id,
268                    s.reconcile_state,
269                    s.reconcile_date,
270                    &s.value_num,
271                    &s.value_denom,
272                    s.lot_id
273                )
274                .execute(&mut **sqltx)
275                .await?;
276            }
277            Ok(self.tx)
278        } else {
279            Err(FinanceError::Internal(
280                t!("Adding splits failed").to_string(),
281            ))
282        }
283    }
284
285    pub async fn add_conversions(
286        &mut self,
287        prices: &[&Price],
288    ) -> Result<&'t Transaction, FinanceError> {
289        if let Some(sqltx) = &mut self.sqltx {
290            for p in prices {
291                p.commit(&mut **sqltx).await?;
292            }
293            Ok(self.tx)
294        } else {
295            Err(FinanceError::Internal(
296                t!("Adding conversions failed").to_string(),
297            ))
298        }
299    }
300
301    pub async fn add_tags(&mut self, tags: &[&Tag]) -> Result<&'t Transaction, FinanceError> {
302        if let Some(sqltx) = &mut self.sqltx {
303            for t in tags {
304                let tag_id = t.commit(&mut **sqltx).await?;
305                query_file!("sql/transaction_tag_set.sql", self.tx.id, tag_id)
306                    .execute(&mut **sqltx)
307                    .await?;
308            }
309            Ok(self.tx)
310        } else {
311            Err(FinanceError::Internal(t!("Adding tags failed").to_string()))
312        }
313    }
314
315    pub async fn add_split_tags(
316        &mut self,
317        split_tags: &[(Uuid, Tag)],
318    ) -> Result<&'t Transaction, FinanceError> {
319        if let Some(sqltx) = &mut self.sqltx {
320            crate::tag::insert_split_tags(sqltx, split_tags).await?;
321            Ok(self.tx)
322        } else {
323            Err(FinanceError::Internal(
324                t!("Adding split tags failed").to_string(),
325            ))
326        }
327    }
328
329    /// Execute an arbitrary async operation within this ticket's DB transaction.
330    ///
331    /// This enables custom operations (like adding split tags) without adding
332    /// specific methods for each entity type.
333    pub async fn execute<F, T>(&mut self, f: F) -> Result<T, FinanceError>
334    where
335        F: AsyncFnOnce(&mut sqlx::PgConnection) -> Result<T, sqlx::Error>,
336    {
337        if let Some(sqltx) = &mut self.sqltx {
338            f(sqltx).await.map_err(Into::into)
339        } else {
340            Err(FinanceError::Internal(
341                t!("Cannot execute on empty ticket").to_string(),
342            ))
343        }
344    }
345}
346
347impl<'t> Transaction {
348    /// Inserts the transaction into the database and starts data input.
349    ///
350    /// This method begins a new database transaction, inserts the transaction
351    /// details into the DB, and returns a `TransactionTicket` to manage the
352    /// rest of data (`Split`s, `Tag`s, and so on). The DB transaction must be
353    /// committed (or rolled back) from via the `TransactionTicket` returned.
354    ///
355    /// # Parameters
356    /// - `conn`: A connection to the database.
357    ///
358    /// # Returns
359    /// A `TransactionTicket` for managing the transaction.
360    ///
361    /// # Errors
362    /// Returns a `FinanceError` if the database operation fails.
363    pub async fn enter<'p, E>(
364        &'t self,
365        conn: &'p mut E,
366    ) -> Result<TransactionTicket<'t, 'p>, FinanceError>
367    where
368        E: Connection<Database = sqlx::Postgres>,
369    {
370        let mut tr = conn.begin().await?;
371
372        sqlx::query_file!(
373            "sql/transaction_insert.sql",
374            &self.id,
375            &self.post_date,
376            &self.enter_date
377        )
378        .execute(&mut *tr)
379        .await?;
380
381        Ok(TransactionTicket {
382            sqltx: Some(tr),
383            tx: self,
384        })
385    }
386}