Skip to main content

server/command/transaction/
create.rs

1//! `CreateTransaction`.
2
3use finance::{price::Price, split::Split, tag::Tag, transaction::Transaction};
4use scripting::ScriptExecutor;
5use sqlx::{
6    PgConnection,
7    types::Uuid,
8    types::chrono::{DateTime, Utc},
9};
10use std::{
11    collections::{HashMap, HashSet},
12    fmt::Debug,
13};
14use supp_macro::command;
15
16use crate::attempt::{Attempt, Tries};
17use crate::script::TransactionState;
18use crate::tag::lock::{bound_waits, destination_keys, lock_keys};
19use crate::user::User;
20use std::convert::identity;
21
22use crate::command::transaction::account_gone;
23use crate::command::transaction_edit::validate_edit_tags;
24use crate::command::{CmdError, CmdResult, FinanceEntity, connection};
25
26command! {
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                .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                let report = tokio::task::spawn_blocking(move || {
72                    let executor = ScriptExecutor::try_new()?;
73                    state.run_scripts(&executor, &scripts)
74                })
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}
120
121/// The enabled automation scripts, read on a connection released before they
122/// run, so a slow script holds no pool slot.
123async fn enabled_scripts(user: &User) -> Result<Vec<(Uuid, Vec<u8>)>, CmdError> {
124    let mut conn = connection(user).await?;
125    Ok(sqlx::query_file!("sql/select/artifacts/enabled.sql")
126        .fetch_all(&mut *conn)
127        .await?
128        .into_iter()
129        .map(|row| (row.id, row.bytecode))
130        .collect())
131}
132
133/// What `CreateTransaction` stores once its scripts ran.
134struct 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
142impl 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    fn validate_prices(&self) -> Result<(), CmdError> {
146        let valid_split_ids: HashSet<Uuid> = self.splits.iter().map(|split| split.id).collect();
147        let foreign = self
148            .prices
149            .iter()
150            .flat_map(|price| [price.commodity_split, price.currency_split])
151            .flatten()
152            .any(|split_id| !valid_split_ids.contains(&split_id));
153        match foreign {
154            true => Err(CmdError::Args(
155                "Price references a split that is not part of this transaction".to_string(),
156            )),
157            false => Ok(()),
158        }
159    }
160
161    /// Store the transaction in one DB transaction, its tag keys locked first.
162    async fn store(&self, conn: &mut PgConnection) -> Result<(), CmdError> {
163        let mut ticket = self.transaction.enter(&mut *conn).await?;
164        let keys = destination_keys(
165            self.transaction_tags
166                .iter()
167                .chain(self.split_tags.iter().map(|(_, tag)| tag)),
168        );
169        ticket
170            .execute(async |conn| {
171                bound_waits(conn).await?;
172                lock_keys(conn, &keys).await
173            })
174            .await?;
175
176        let split_refs: Vec<_> = self.splits.iter().collect();
177        ticket
178            .add_splits(&split_refs)
179            .await
180            .map_err(|err| account_gone(err.into()))?;
181        if !self.prices.is_empty() {
182            let price_refs: Vec<_> = self.prices.iter().collect();
183            ticket.add_conversions(&price_refs).await?;
184        }
185        if !self.transaction_tags.is_empty() {
186            let tag_refs: Vec<_> = self.transaction_tags.iter().collect();
187            ticket.add_tags(&tag_refs).await?;
188        }
189        if !self.split_tags.is_empty() {
190            ticket.add_split_tags(&self.split_tags).await?;
191        }
192        ticket.commit().await?;
193        Ok(())
194    }
195}