Skip to main content

server/command/transaction/
delete.rs

1//! `DeleteTransaction` and the single transaction tag commands.
2
3use crate::command::connection;
4use finance::tag::Tag;
5use sqlx::{PgConnection, types::Uuid};
6use std::fmt::Debug;
7use supp_macro::command;
8
9use crate::attempt::{Attempt, Tries};
10use crate::command::split::map_server_err;
11use crate::command::transaction::refuse_cross_price;
12use crate::command::transaction_edit::lock_tag_keys;
13use crate::tag::lock::{KeyChanged, begin};
14use crate::tag::user::delete_tag_if_orphaned;
15use crate::user::User;
16use std::convert::identity;
17
18use crate::command::{CmdError, CmdResult};
19
20command! {
21    DeleteTransaction {
22        #[required]
23        user_id: Uuid,
24        #[required]
25        transaction_id: Uuid,
26    } => {
27        let user = User { id: user_id };
28        let mut conn = connection(&user).await?;
29        let mut tries = Tries::default();
30        while tries
31            .step(Attempt::of(
32                delete(&mut conn, transaction_id).await,
33                CmdError::is_retryable,
34                identity,
35            ))?
36            .is_none()
37        {}
38        Ok(Some(CmdResult::String(
39            "Transaction deleted successfully".to_string(),
40        )))
41    }
42}
43
44/// Delete the transaction in one DB transaction: its row lock, then the keys
45/// of its linked tags through the tag lock protocol, then the links, the tag
46/// rows nothing references any more, the splits and the row.
47async fn delete(
48    conn: &mut PgConnection,
49    transaction_id: Uuid,
50) -> Result<Result<(), KeyChanged>, CmdError> {
51    let mut tx = begin(conn).await?;
52    sqlx::query_file!("sql/select/transactions/by_id_locked.sql", transaction_id)
53        .fetch_optional(&mut *tx)
54        .await?
55        .ok_or_else(|| CmdError::NotFound("Transaction not found".to_string()))?;
56    refuse_cross_price(&mut tx, transaction_id).await?;
57    let linked = match lock_tag_keys(&mut tx, transaction_id, &[]).await? {
58        Ok(linked) => linked,
59        Err(changed) => {
60            tx.rollback().await?;
61            return Ok(Err(changed));
62        }
63    };
64
65    sqlx::query_file!("sql/delete/split_tags/by_transaction.sql", transaction_id)
66        .execute(&mut *tx)
67        .await?;
68    sqlx::query_file!("sql/delete/prices/by_splits.sql", transaction_id)
69        .execute(&mut *tx)
70        .await?;
71    sqlx::query_file!(
72        "sql/delete/transaction_tags/by_transaction.sql",
73        transaction_id
74    )
75    .execute(&mut *tx)
76    .await?;
77    for tag_id in linked {
78        delete_tag_if_orphaned(&mut tx, tag_id).await?;
79    }
80    sqlx::query_file!("sql/delete/splits/by_transaction.sql", transaction_id)
81        .execute(&mut *tx)
82        .await?;
83    sqlx::query_file!("sql/delete/transactions/by_id.sql", transaction_id)
84        .execute(&mut *tx)
85        .await?;
86    tx.commit().await?;
87    Ok(Ok(()))
88}
89
90// Idempotent set: replace any existing (tx, tag_name) link with the
91// supplied `tag_value`. Mirrors `SetSplitTag` and `SetAccountTag` so
92// the script-side `set-transaction-tag` native reads symmetrically.
93command! {
94    SetTransactionTag {
95        #[required]
96        user_id: Uuid,
97        #[required]
98        transaction_id: Uuid,
99        #[required]
100        tag_name: String,
101        #[required]
102        tag_value: String,
103        #[optional]
104        description: String,
105    } => {
106        let user = User { id: user_id };
107        let desc = description.filter(|text| !text.trim().is_empty());
108        let tag = Tag {
109            id: Uuid::new_v4(),
110            tag_name,
111            tag_value,
112            description: desc,
113        };
114        user.set_transaction_tag(transaction_id, &tag)
115            .await
116            .map_err(map_server_err)?;
117        Ok(Some(CmdResult::String("ok".to_string())))
118    }
119}
120
121// Looks up a single tag value by name on a transaction. Returns
122// `CmdResult::String("")` when absent (matches `GetSplitTag`).
123command! {
124    GetTransactionTag {
125        #[required]
126        user_id: Uuid,
127        #[required]
128        transaction_id: Uuid,
129        #[required]
130        tag_name: String,
131    } => {
132        let user = User { id: user_id };
133        user.require_transaction(transaction_id)
134            .await
135            .map_err(map_server_err)?;
136        let tags = user
137            .get_transaction_tags(transaction_id)
138            .await
139            .map_err(map_server_err)?;
140        let value = tags
141            .into_iter()
142            .find(|t| t.tag_name == tag_name)
143            .map(|t| t.tag_value)
144            .unwrap_or_default();
145        Ok(Some(CmdResult::String(value)))
146    }
147}