1
//! `UpdateTransaction`.
2

            
3
use crate::command::connection;
4
use finance::{split::Split, tag::Tag, transaction::Transaction};
5
use num_rational::Rational64;
6
use sqlx::{
7
    PgConnection,
8
    types::Uuid,
9
    types::chrono::{DateTime, Utc},
10
};
11
use std::collections::{HashMap, HashSet};
12
use std::fmt::Debug;
13
use supp_macro::command;
14

            
15
use crate::attempt::{Attempt, Tries};
16
use crate::command::transaction::{account_gone, refuse_cross_price};
17
use crate::tag::lock::{KeyChanged, begin};
18
use crate::tag::user::delete_tag_if_orphaned;
19
use crate::user::User;
20
use std::convert::identity;
21

            
22
use 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
};
26
use crate::command::{CmdError, CmdResult, FinanceEntity};
27

            
28
command! {
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
214939
}
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)]
96
pub 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.
103
type SplitState = (Option<bool>, Option<DateTime<Utc>>, Option<Uuid>);
104

            
105
impl KeepStored {
106
    /// The state of `split`, each kept field taken from `stored` while it
107
    /// still applies, else unset.
108
1620
    fn state(self, split: &Split, stored: &Split) -> SplitState {
109
1620
        let same_account = split.account_id == stored.account_id;
110
1620
        let same_amount = same_account
111
1260
            && i128::from(split.value_num) * i128::from(stored.value_denom)
112
1260
                == i128::from(stored.value_num) * i128::from(split.value_denom);
113
1620
        (
114
1620
            kept(
115
1620
                self.reconcile_state,
116
1620
                same_amount,
117
1620
                split.reconcile_state,
118
1620
                stored.reconcile_state,
119
1620
            ),
120
1620
            kept(
121
1620
                self.reconcile_date,
122
1620
                same_amount,
123
1620
                split.reconcile_date,
124
1620
                stored.reconcile_date,
125
1620
            ),
126
1620
            kept(self.lot_id, same_account, split.lot_id, stored.lot_id),
127
1620
        )
128
1620
    }
129
}
130

            
131
/// `new` unless `keep`; when kept, `old` while it still `applies`, else unset.
132
4860
fn kept<T>(keep: bool, applies: bool, new: Option<T>, old: Option<T>) -> Option<T> {
133
4860
    match (keep, applies) {
134
540
        (false, _) => new,
135
2520
        (true, true) => old,
136
1800
        (true, false) => None,
137
    }
138
4860
}
139

            
140
/// The arguments of one `UpdateTransaction`, applied once per attempt.
141
struct 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

            
155
impl 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
23848
    async fn attempt(
160
23848
        &self,
161
23848
        conn: &mut PgConnection,
162
23848
    ) -> Result<Result<Transaction, KeyChanged>, CmdError> {
163
6620
        let mut tx = begin(conn).await?;
164
6620
        let existing = sqlx::query_file!(
165
6620
            "sql/select/transactions/by_id_locked.sql",
166
            self.transaction_id
167
        )
168
6620
        .fetch_optional(&mut *tx)
169
6620
        .await?
170
161
        .ok_or_else(|| CmdError::NotFound("Transaction not found".to_string()))?;
171

            
172
6459
        refuse_cross_price(&mut tx, self.transaction_id).await?;
173
6456
        let linked = match lock_edit_tags(
174
6456
            &mut tx,
175
6456
            self.transaction_id,
176
6456
            self.tags.as_ref(),
177
6456
            self.split_tags.as_deref(),
178
6456
            self.note.as_deref(),
179
6456
        )
180
6456
        .await?
181
        {
182
6436
            Ok(linked) => linked,
183
            Err(changed) => {
184
20
                tx.rollback().await?;
185
20
                return Ok(Err(changed));
186
            }
187
        };
188
6436
        self.check_guards(&mut tx, existing.post_date).await?;
189

            
190
6097
        let updated = Transaction {
191
6097
            id: self.transaction_id,
192
6097
            post_date: self.post_date.unwrap_or(existing.post_date),
193
6097
            enter_date: self.enter_date.unwrap_or(existing.enter_date),
194
6097
        };
195
6097
        let new_split_ids = self.validate_splits()?;
196

            
197
6094
        sqlx::query_file!(
198
            "sql/update/transactions/update.sql",
199
            updated.id,
200
            updated.post_date,
201
            updated.enter_date
202
        )
203
6094
        .execute(&mut *tx)
204
6094
        .await?;
205

            
206
6094
        let stored_split_tags = match self.split_tags {
207
4247
            Some(_) => stored_split_tags(&mut tx, self.transaction_id).await?,
208
1847
            None => Vec::new(),
209
        };
210
6094
        self.clear_prices(&mut tx).await?;
211
6094
        self.replace_splits(&mut tx).await?;
212
6089
        self.validate_prices(&mut tx, new_split_ids).await?;
213
6087
        validate_edit_tags(self.tags.as_ref(), self.split_tags.as_deref())?;
214
6081
        self.insert_prices(&mut tx).await?;
215

            
216
6081
        if let Some(new_tags) = &self.tags {
217
5838
            replace_transaction_tags(&mut tx, self.transaction_id, new_tags).await?;
218
243
        }
219
6081
        if let Some(new_split_tags) = &self.split_tags {
220
4246
            add_split_tags(
221
4246
                &mut tx,
222
4246
                self.transaction_id,
223
4246
                new_split_tags,
224
4246
                &stored_split_tags,
225
4246
            )
226
4246
            .await?;
227
1835
        }
228
6080
        self.write_note(&mut tx).await?;
229
6080
        for tag_id in linked {
230
27386
            delete_tag_if_orphaned(&mut tx, tag_id).await?;
231
        }
232

            
233
6080
        tx.commit().await?;
234
6080
        Ok(Ok(updated))
235
6620
    }
236

            
237
    /// Refuse a stale revision or, when asked, an unkeepable transaction.
238
23644
    async fn check_guards(
239
23644
        &self,
240
23644
        conn: &mut PgConnection,
241
23644
        post_date: DateTime<Utc>,
242
23644
    ) -> Result<(), CmdError> {
243
6436
        if self.expected_revision.is_none() && !self.refuse_unkeepable {
244
423
            return Ok(());
245
6013
        }
246
6013
        let stored = stored_state(conn, self.transaction_id, post_date).await?;
247
6013
        if self
248
6013
            .expected_revision
249
6013
            .as_ref()
250
5837
            .is_some_and(|expected| stored.revision != *expected)
251
        {
252
336
            return Err(CmdError::Args(crate::logical::STALE_REVISION.to_string()));
253
5677
        }
254
5677
        if self.refuse_unkeepable {
255
5674
            stored.ensure_keepable()?;
256
3
        }
257
5674
        Ok(())
258
6436
    }
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
20759
    fn validate_splits(&self) -> Result<Option<HashSet<Uuid>>, CmdError> {
263
20759
        let Some(new_splits) = &self.splits else {
264
844
            return Ok(None);
265
        };
266
19915
        let mut commodity_sums: HashMap<Uuid, Rational64> = HashMap::new();
267
19915
        let mut ids = HashSet::new();
268
19915
        for entity in new_splits {
269
53508
            let FinanceEntity::Split(split) = entity else {
270
1
                return Err(CmdError::Args("Invalid entity type in splits".to_string()));
271
            };
272
53507
            if split.tx_id != self.transaction_id {
273
1
                return Err(CmdError::Args("Split transaction ID mismatch".to_string()));
274
53506
            }
275
53506
            ids.insert(split.id);
276
53506
            *commodity_sums.entry(split.commodity_id).or_default() +=
277
53506
                Rational64::new(split.value_num, split.value_denom);
278
        }
279
        // A multi-currency transaction balances through its prices, not per commodity.
280
19913
        if commodity_sums.len() == 1
281
12713
            && commodity_sums
282
12713
                .values()
283
12713
                .any(|sum| *sum != Rational64::default())
284
        {
285
1
            return Err(CmdError::Args("Splits must sum to zero".to_string()));
286
19912
        }
287
19912
        Ok(Some(ids))
288
20759
    }
289

            
290
    /// Delete the stored prices of this transaction's splits when either the
291
    /// prices or the splits are replaced.
292
20756
    async fn clear_prices(&self, conn: &mut PgConnection) -> Result<(), CmdError> {
293
6094
        if self.prices.is_none() && self.splits.is_none() {
294
302
            return Ok(());
295
5792
        }
296
5792
        sqlx::query_file!("sql/delete/prices/by_splits.sql", self.transaction_id)
297
5792
            .execute(&mut *conn)
298
5792
            .await?;
299
5792
        Ok(())
300
6094
    }
301

            
302
    /// Delete the stored splits with their split tags, then insert the
303
    /// replacement splits.
304
20756
    async fn replace_splits(&self, conn: &mut PgConnection) -> Result<(), CmdError> {
305
6094
        let Some(new_splits) = &self.splits else {
306
307
            return Ok(());
307
        };
308
5787
        let stored = self.stored_splits(conn).await?;
309
5787
        sqlx::query_file!(
310
            "sql/delete/split_tags/by_transaction.sql",
311
            self.transaction_id
312
        )
313
5787
        .execute(&mut *conn)
314
5787
        .await?;
315
5787
        sqlx::query_file!("sql/delete/splits/by_transaction.sql", self.transaction_id)
316
5787
            .execute(&mut *conn)
317
5787
            .await?;
318
5787
        for entity in new_splits {
319
18961
            if let FinanceEntity::Split(split) = entity {
320
                let (reconcile_state, reconcile_date, lot_id) =
321
18961
                    match (self.keep_stored.get(&split.id), stored.get(&split.id)) {
322
9
                        (Some(keep), Some(stored)) => keep.state(split, stored),
323
18952
                        _ => (split.reconcile_state, split.reconcile_date, split.lot_id),
324
                    };
325
18961
                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
18961
                .execute(&mut *conn)
338
18961
                .await
339
5
                .map_err(|err| account_gone(err.into()))?;
340
            }
341
        }
342
5782
        Ok(())
343
6094
    }
344

            
345
    /// The stored splits by id, read only when a replacement keeps a field.
346
19912
    async fn stored_splits(
347
19912
        &self,
348
19912
        conn: &mut PgConnection,
349
19912
    ) -> Result<HashMap<Uuid, Split>, CmdError> {
350
5787
        if self.keep_stored.is_empty() {
351
5780
            return Ok(HashMap::new());
352
7
        }
353
7
        Ok(sqlx::query_file_as!(
354
            Split,
355
7
            "sql/select/splits/by_transaction.sql",
356
            self.transaction_id
357
        )
358
7
        .fetch_all(conn)
359
7
        .await?
360
        .into_iter()
361
14
        .map(|split| (split.id, split))
362
        .collect())
363
5787
    }
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
20572
    async fn validate_prices(
368
20572
        &self,
369
20572
        conn: &mut PgConnection,
370
20572
        new_split_ids: Option<HashSet<Uuid>>,
371
20572
    ) -> Result<(), CmdError> {
372
6089
        let Some(new_prices) = &self.prices else {
373
1907
            return Ok(());
374
        };
375
4182
        let valid_split_ids = match new_split_ids {
376
4177
            Some(ids) => ids,
377
5
            None => sqlx::query_file!("sql/select/splits/by_transaction.sql", self.transaction_id)
378
5
                .fetch_all(&mut *conn)
379
5
                .await?
380
                .into_iter()
381
10
                .map(|row| row.id)
382
                .collect(),
383
        };
384
4182
        for entity in new_prices {
385
4184
            let FinanceEntity::Price(price) = entity else {
386
1
                return Err(CmdError::Args("Invalid entity type in prices".to_string()));
387
            };
388
4183
            let foreign = [price.commodity_split, price.currency_split]
389
4183
                .into_iter()
390
4183
                .flatten()
391
8362
                .any(|split_id| !valid_split_ids.contains(&split_id));
392
4183
            if foreign {
393
1
                return Err(CmdError::Args(
394
1
                    "Price references a split that is not part of this transaction".to_string(),
395
1
                ));
396
4182
            }
397
        }
398
4180
        Ok(())
399
6089
    }
400

            
401
20385
    async fn insert_prices(&self, conn: &mut PgConnection) -> Result<(), CmdError> {
402
6081
        for entity in self.prices.iter().flatten() {
403
4182
            if let FinanceEntity::Price(price) = entity {
404
4182
                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
4182
                .execute(&mut *conn)
416
4182
                .await?;
417
            }
418
        }
419
6081
        Ok(())
420
6081
    }
421

            
422
    /// Replace the note tag; a blank note removes it.
423
20384
    async fn write_note(&self, conn: &mut PgConnection) -> Result<(), CmdError> {
424
6080
        let Some(note_value) = &self.note else {
425
566
            return Ok(());
426
        };
427
5514
        unlink_tags(conn, self.transaction_id, true).await?;
428
5514
        if !note_value.trim().is_empty() {
429
5498
            let note_tag_id = note_tag(note_value).commit(&mut *conn).await?;
430
5498
            sqlx::query_file!(
431
                "sql/insert/transaction_tags/transaction_tag.sql",
432
                self.transaction_id,
433
                note_tag_id
434
            )
435
5498
            .execute(&mut *conn)
436
5498
            .await?;
437
16
        }
438
5514
        Ok(())
439
6080
    }
440
}