1
//! `CreateTransaction`.
2

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

            
16
use crate::attempt::{Attempt, Tries};
17
use crate::script::TransactionState;
18
use crate::tag::lock::{bound_waits, destination_keys, lock_keys};
19
use crate::user::User;
20
use std::convert::identity;
21

            
22
use crate::command::transaction::account_gone;
23
use crate::command::transaction_edit::validate_edit_tags;
24
use crate::command::{CmdError, CmdResult, FinanceEntity, connection};
25

            
26
command! {
27
    CreateTransaction {
28
        #[required]
29
        user_id: Uuid,
30
        #[required]
31
        splits: Vec<FinanceEntity>,
32
        #[required]
33
        id: Uuid,
34
        #[required]
35
        post_date: DateTime<Utc>,
36
        #[required]
37
        enter_date: DateTime<Utc>,
38
        #[optional]
39
        prices: Vec<FinanceEntity>,
40
        #[optional]
41
        note: String,
42
        #[optional]
43
        split_tags: Vec<(Uuid, Tag)>,
44
        // Same semantics as `UpdateTransaction::tags`; the note goes through `note`.
45
        #[optional]
46
        tags: HashMap<String, FinanceEntity>,
47
    } => {
48
        validate_edit_tags(tags.as_ref(), split_tags.as_deref())?;
49

            
50
        let user = User { id: user_id };
51

            
52
        let tx = Transaction {
53
            id,
54
            post_date,
55
            enter_date,
56
        };
57

            
58
        let entry = {
59
            let scripts = enabled_scripts(&user).await?;
60

            
61
            let state = TransactionState::new(tx)
62
                .with(splits)
63
                .with(prices.unwrap_or_default())
64
30330
                .with(tags.map(|t| t.into_values().collect()).unwrap_or_default())
65
                .with_note(note)
66
                .with_split_tags(split_tags.unwrap_or_default());
67

            
68
            let state = if scripts.is_empty() {
69
                state
70
            } else {
71
5
                let report = tokio::task::spawn_blocking(move || {
72
5
                    let executor = ScriptExecutor::try_new()?;
73
5
                    state.run_scripts(&executor, &scripts)
74
5
                })
75
                .await
76
                .map_err(|e| CmdError::Script(format!("{e:?}")))?
77
                .map_err(|e| {
78
                    tracing::error!("{}", t!("Script execution failed: %{err}", err = e : {:?}));
79
                    CmdError::Script(format!("{e:?}"))
80
                })?;
81
                for failure in &report.failures {
82
                    tracing::error!(
83
                        "{}",
84
                        t!(
85
                            "Script %{id} failed: %{code}: %{message}",
86
                            id = failure.script_id,
87
                            code = failure.code,
88
                            message = failure.message
89
                        )
90
                    );
91
                }
92
                report.state
93
            };
94

            
95
            Entry {
96
                transaction: state.transaction,
97
                splits: state.splits,
98
                prices: state.prices,
99
                transaction_tags: state.transaction_tags,
100
                split_tags: state.split_tags,
101
            }
102
        };
103

            
104
        entry.validate_prices()?;
105
        let mut conn = connection(&user).await?;
106
        let mut tries = Tries::default();
107
        while tries
108
            .step(Attempt::of(
109
                entry.store(&mut conn).await.map(Ok),
110
                CmdError::is_retryable,
111
                identity,
112
            ))?
113
            .is_none()
114
        {}
115
        Ok(Some(CmdResult::Entity(FinanceEntity::Transaction(
116
            entry.transaction,
117
        ))))
118
    }
119
1272825
}
120

            
121
/// The enabled automation scripts, read on a connection released before they
122
/// run, so a slow script holds no pool slot.
123
162084
async fn enabled_scripts(user: &User) -> Result<Vec<(Uuid, Vec<u8>)>, CmdError> {
124
162084
    let mut conn = connection(user).await?;
125
162084
    Ok(sqlx::query_file!("sql/select/artifacts/enabled.sql")
126
162084
        .fetch_all(&mut *conn)
127
162084
        .await?
128
        .into_iter()
129
6
        .map(|row| (row.id, row.bytecode))
130
        .collect())
131
162084
}
132

            
133
/// What `CreateTransaction` stores once its scripts ran.
134
struct Entry {
135
    transaction: Transaction,
136
    splits: Vec<Split>,
137
    prices: Vec<Price>,
138
    transaction_tags: Vec<Tag>,
139
    split_tags: Vec<(Uuid, Tag)>,
140
}
141

            
142
impl Entry {
143
    /// Every linked split a price references must belong to this transaction's
144
    /// own split set; the FK alone would accept a foreign or stale split id.
145
162084
    fn validate_prices(&self) -> Result<(), CmdError> {
146
339719
        let valid_split_ids: HashSet<Uuid> = self.splits.iter().map(|split| split.id).collect();
147
162084
        let foreign = self
148
162084
            .prices
149
162084
            .iter()
150
11737
            .flat_map(|price| [price.commodity_split, price.currency_split])
151
            .flatten()
152
23474
            .any(|split_id| !valid_split_ids.contains(&split_id));
153
162084
        match foreign {
154
1
            true => Err(CmdError::Args(
155
1
                "Price references a split that is not part of this transaction".to_string(),
156
1
            )),
157
162083
            false => Ok(()),
158
        }
159
162084
    }
160

            
161
    /// Store the transaction in one DB transaction, its tag keys locked first.
162
162084
    async fn store(&self, conn: &mut PgConnection) -> Result<(), CmdError> {
163
162084
        let mut ticket = self.transaction.enter(&mut *conn).await?;
164
162084
        let keys = destination_keys(
165
162084
            self.transaction_tags
166
162084
                .iter()
167
162084
                .chain(self.split_tags.iter().map(|(_, tag)| tag)),
168
        );
169
162084
        ticket
170
324168
            .execute(async |conn| {
171
162084
                bound_waits(conn).await?;
172
162084
                lock_keys(conn, &keys).await
173
324168
            })
174
162084
            .await?;
175

            
176
162084
        let split_refs: Vec<_> = self.splits.iter().collect();
177
162084
        ticket
178
162084
            .add_splits(&split_refs)
179
162084
            .await
180
182
            .map_err(|err| account_gone(err.into()))?;
181
161902
        if !self.prices.is_empty() {
182
11555
            let price_refs: Vec<_> = self.prices.iter().collect();
183
11555
            ticket.add_conversions(&price_refs).await?;
184
150347
        }
185
161902
        if !self.transaction_tags.is_empty() {
186
67257
            let tag_refs: Vec<_> = self.transaction_tags.iter().collect();
187
67257
            ticket.add_tags(&tag_refs).await?;
188
94645
        }
189
161902
        if !self.split_tags.is_empty() {
190
29447
            ticket.add_split_tags(&self.split_tags).await?;
191
132455
        }
192
161901
        ticket.commit().await?;
193
161901
        Ok(())
194
162084
    }
195
}