1
use crate::error::{FinanceError, TransactionError};
2
use crate::price::Price;
3
use crate::split::Split;
4
use crate::tag::Tag;
5
use itertools::Itertools;
6
use num_rational::Rational64;
7
use num_traits::{CheckedAdd, CheckedMul, Signed};
8
use sqlx::types::Uuid;
9
use sqlx::types::chrono::{DateTime, Utc};
10
use sqlx::{Connection, Postgres, query_file};
11
use std::collections::{HashMap, HashSet};
12
use 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")]
28
pub 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.
37
pub(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.
44
pub(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.
54
632063
pub(crate) fn ratio(num: i64, denom: i64) -> Result<Rational64, FinanceError> {
55
632063
    match denom > 0 {
56
632061
        true => Ok(Rational64::new(num, denom)),
57
2
        false => Err(FinanceError::Transaction(TransactionError::Build(
58
2
            t!("Value denominator must be positive").to_string(),
59
2
        ))),
60
    }
61
632063
}
62

            
63
5
fn price_error(message: &str) -> FinanceError {
64
5
    FinanceError::Transaction(TransactionError::Build(message.to_string()))
65
5
}
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.
70
19112
fn conversion(price: &PriceLink, held: &HashMap<Uuid, Uuid>) -> Result<Conversion, FinanceError> {
71
19112
    if !price.rate.is_positive() {
72
3
        return Err(price_error(&t!("Price rate must be positive")));
73
19109
    }
74
38217
    let side = |split: Option<Uuid>, commodity: Uuid| -> Result<Option<Uuid>, FinanceError> {
75
38217
        match split {
76
            None => Ok(None),
77
38217
            Some(id) if held.get(&id) == Some(&commodity) => Ok(Some(id)),
78
1
            Some(_) => Err(price_error(&t!(
79
1
                "Price commodities do not match the linked splits"
80
1
            ))),
81
        }
82
38217
    };
83
19109
    let commodity = side(price.commodity_split, price.commodity_id)?;
84
19108
    let currency = side(price.currency_split, price.currency_id)?;
85
19108
    match (commodity, currency) {
86
19108
        (Some(split), _) => Ok(Conversion {
87
19108
            split,
88
19108
            into: price.currency_id,
89
19108
            rate: price.rate,
90
19108
        }),
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
19112
}
99

            
100
/// The conversions of `prices`, each split linked by at most one price.
101
18730
pub(crate) fn conversions(
102
18730
    prices: &[PriceLink],
103
18730
    held: &HashMap<Uuid, Uuid>,
104
18730
) -> Result<Vec<Conversion>, FinanceError> {
105
18730
    let mut linked: HashSet<Uuid> = HashSet::new();
106
18730
    for split in prices
107
18730
        .iter()
108
19114
        .flat_map(|p| [p.commodity_split, p.currency_split])
109
        .flatten()
110
    {
111
38226
        if !linked.insert(split) {
112
1
            return Err(price_error(&t!("Split is linked by several prices")));
113
38225
        }
114
    }
115
19112
    prices.iter().map(|p| conversion(p, held)).collect()
116
18730
}
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.
123
18731
pub(crate) fn balances(legs: &[(Uuid, Uuid, Rational64)], conversions: &[Conversion]) -> bool {
124
18731
    let mut sums: HashMap<Uuid, Rational64> = HashMap::new();
125
18731
    for (split, commodity, value) in legs {
126
60778
        let converted = match conversions.iter().find(|c| c.split == *split) {
127
19112
            Some(conversion) => value
128
19112
                .checked_mul(&conversion.rate)
129
19111
                .map(|amount| (conversion.into, amount)),
130
40520
            None => Some((*commodity, *value)),
131
        };
132
59632
        let Some((into, amount)) = converted else {
133
1
            return false;
134
        };
135
59631
        let sum = sums.entry(into).or_default();
136
59631
        let Some(total) = sum.checked_add(&amount) else {
137
            return false;
138
        };
139
59631
        *sum = total;
140
    }
141
18731
    sums.values().all(|sum| *sum == Rational64::from_integer(0))
142
18731
}
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.
153
pub struct TransactionTicket<'t, 's> {
154
    sqltx: Option<sqlx::Transaction<'s, Postgres>>,
155
    tx: &'t Transaction,
156
}
157

            
158
impl<'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
291481
    pub async fn commit(&mut self) -> Result<&'t Transaction, FinanceError> {
168
161925
        if let Some(mut sqltx) = self.sqltx.take() {
169
161925
            let splits = query_file!("sql/transaction_select_splits.sql", &self.tx.id)
170
161925
                .fetch_all(&mut *sqltx)
171
161925
                .await?;
172

            
173
            let distinct_commodities: Vec<Uuid> =
174
339408
                splits.iter().map(|s| s.commodity_id).unique().collect();
175

            
176
161925
            if distinct_commodities.is_empty() {
177
1
                return Err(FinanceError::Internal(
178
1
                    t!("No splits found for this transaction").to_string(),
179
1
                ));
180
161924
            }
181

            
182
161924
            if distinct_commodities.len() == 1 {
183
150362
                let sum_splits = splits
184
150362
                    .iter()
185
307567
                    .map(|s| ratio(s.value_num, s.value_denom))
186
                    .collect::<Result<Vec<_>, _>>()?
187
                    .into_iter()
188
307567
                    .try_fold(Rational64::default(), |a, b| a.checked_add(&b))
189
                    .ok_or_else(|| FinanceError::Internal(t!("Erroneous split").to_string()))?;
190

            
191
150362
                if sum_splits != 0.into() {
192
2
                    return Err(FinanceError::Transaction(TransactionError::Build(
193
2
                        t!("Unbalanced Transaction: sum of splits is non-zero").to_string(),
194
2
                    )));
195
150360
                }
196
            } else {
197
31841
                let split_ids: Vec<Uuid> = splits.iter().map(|s| s.id).collect();
198
11562
                let prices = query_file!("sql/transaction_select_prices_by_splits.sql", &split_ids)
199
11562
                    .fetch_all(&mut *sqltx)
200
11562
                    .await?;
201
11562
                let links = prices
202
11562
                    .iter()
203
11745
                    .map(|p| {
204
                        Ok(PriceLink {
205
11745
                            commodity_id: p.commodity_id,
206
11745
                            currency_id: p.currency_id,
207
11745
                            commodity_split: p.commodity_split_id,
208
11745
                            currency_split: p.currency_split_id,
209
11745
                            rate: ratio(p.value_num, p.value_denom)?,
210
                        })
211
11745
                    })
212
                    .collect::<Result<Vec<_>, FinanceError>>()?;
213
                let held: HashMap<Uuid, Uuid> =
214
31841
                    splits.iter().map(|s| (s.id, s.commodity_id)).collect();
215
11562
                let conversions = conversions(&links, &held)?;
216
11560
                let legs = splits
217
11560
                    .iter()
218
31835
                    .map(|s| Ok((s.id, s.commodity_id, ratio(s.value_num, s.value_denom)?)))
219
                    .collect::<Result<Vec<_>, FinanceError>>()?;
220
11560
                if !balances(&legs, &conversions) {
221
1
                    return Err(FinanceError::Transaction(TransactionError::Build(
222
1
                        t!("Unbalanced Transaction after conversion: sum != 0").to_string(),
223
1
                    )));
224
11559
                }
225
            }
226

            
227
161919
            sqltx.commit().await?;
228
161919
            Ok(self.tx)
229
        } else {
230
            Err(FinanceError::Internal(
231
                t!("Attempt to commit the empty ticket").to_string(),
232
            ))
233
        }
234
161925
    }
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
1
    pub async fn rollback(&mut self) -> Result<&'t Transaction, FinanceError> {
244
1
        if let Some(sqltx) = self.sqltx.take() {
245
1
            sqltx.rollback().await?;
246
1
            Ok(self.tx)
247
        } else {
248
            Err(FinanceError::Internal(
249
                t!("Attempt to rollback the empty ticket").to_string(),
250
            ))
251
        }
252
1
    }
253

            
254
292245
    pub async fn add_splits(&mut self, splits: &[&Split]) -> Result<&'t Transaction, FinanceError> {
255
162108
        if let Some(sqltx) = &mut self.sqltx {
256
162108
            for s in splits {
257
339775
                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
339775
                }
262
339775
                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
339775
                .execute(&mut **sqltx)
275
339775
                .await?;
276
            }
277
161925
            Ok(self.tx)
278
        } else {
279
            Err(FinanceError::Internal(
280
                t!("Adding splits failed").to_string(),
281
            ))
282
        }
283
162108
    }
284

            
285
18917
    pub async fn add_conversions(
286
18917
        &mut self,
287
18917
        prices: &[&Price],
288
18917
    ) -> Result<&'t Transaction, FinanceError> {
289
11563
        if let Some(sqltx) = &mut self.sqltx {
290
11563
            for p in prices {
291
11746
                p.commit(&mut **sqltx).await?;
292
            }
293
11563
            Ok(self.tx)
294
        } else {
295
            Err(FinanceError::Internal(
296
                t!("Adding conversions failed").to_string(),
297
            ))
298
        }
299
11563
    }
300

            
301
93593
    pub async fn add_tags(&mut self, tags: &[&Tag]) -> Result<&'t Transaction, FinanceError> {
302
67260
        if let Some(sqltx) = &mut self.sqltx {
303
67260
            for t in tags {
304
94570
                let tag_id = t.commit(&mut **sqltx).await?;
305
94570
                query_file!("sql/transaction_tag_set.sql", self.tx.id, tag_id)
306
94570
                    .execute(&mut **sqltx)
307
94570
                    .await?;
308
            }
309
67260
            Ok(self.tx)
310
        } else {
311
            Err(FinanceError::Internal(t!("Adding tags failed").to_string()))
312
        }
313
67260
    }
314

            
315
51572
    pub async fn add_split_tags(
316
51572
        &mut self,
317
51572
        split_tags: &[(Uuid, Tag)],
318
51572
    ) -> Result<&'t Transaction, FinanceError> {
319
29449
        if let Some(sqltx) = &mut self.sqltx {
320
29449
            crate::tag::insert_split_tags(sqltx, split_tags).await?;
321
29448
            Ok(self.tx)
322
        } else {
323
            Err(FinanceError::Internal(
324
                t!("Adding split tags failed").to_string(),
325
            ))
326
        }
327
29449
    }
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
162084
    pub async fn execute<F, T>(&mut self, f: F) -> Result<T, FinanceError>
334
162084
    where
335
162084
        F: AsyncFnOnce(&mut sqlx::PgConnection) -> Result<T, sqlx::Error>,
336
162084
    {
337
162084
        if let Some(sqltx) = &mut self.sqltx {
338
162084
            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
162084
    }
345
}
346

            
347
impl<'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
162110
    pub async fn enter<'p, E>(
364
162110
        &'t self,
365
162110
        conn: &'p mut E,
366
162110
    ) -> Result<TransactionTicket<'t, 'p>, FinanceError>
367
162110
    where
368
162110
        E: Connection<Database = sqlx::Postgres>,
369
162110
    {
370
162110
        let mut tr = conn.begin().await?;
371

            
372
162110
        sqlx::query_file!(
373
            "sql/transaction_insert.sql",
374
            &self.id,
375
            &self.post_date,
376
            &self.enter_date
377
        )
378
162110
        .execute(&mut *tr)
379
162110
        .await?;
380

            
381
162110
        Ok(TransactionTicket {
382
162110
            sqltx: Some(tr),
383
162110
            tx: self,
384
162110
        })
385
162110
    }
386
}