1
//! `DeleteTransaction` and the single transaction tag commands.
2

            
3
use crate::command::connection;
4
use finance::tag::Tag;
5
use sqlx::{PgConnection, types::Uuid};
6
use std::fmt::Debug;
7
use supp_macro::command;
8

            
9
use crate::attempt::{Attempt, Tries};
10
use crate::command::split::map_server_err;
11
use crate::command::transaction::refuse_cross_price;
12
use crate::command::transaction_edit::lock_tag_keys;
13
use crate::tag::lock::{KeyChanged, begin};
14
use crate::tag::user::delete_tag_if_orphaned;
15
use crate::user::User;
16
use std::convert::identity;
17

            
18
use crate::command::{CmdError, CmdResult};
19

            
20
command! {
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
6732
}
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.
47
1732
async fn delete(
48
1732
    conn: &mut PgConnection,
49
1732
    transaction_id: Uuid,
50
1732
) -> Result<Result<(), KeyChanged>, CmdError> {
51
1552
    let mut tx = begin(conn).await?;
52
1552
    sqlx::query_file!("sql/select/transactions/by_id_locked.sql", transaction_id)
53
1552
        .fetch_optional(&mut *tx)
54
1552
        .await?
55
801
        .ok_or_else(|| CmdError::NotFound("Transaction not found".to_string()))?;
56
751
    refuse_cross_price(&mut tx, transaction_id).await?;
57
749
    let linked = match lock_tag_keys(&mut tx, transaction_id, &[]).await? {
58
744
        Ok(linked) => linked,
59
        Err(changed) => {
60
5
            tx.rollback().await?;
61
5
            return Ok(Err(changed));
62
        }
63
    };
64

            
65
744
    sqlx::query_file!("sql/delete/split_tags/by_transaction.sql", transaction_id)
66
744
        .execute(&mut *tx)
67
744
        .await?;
68
744
    sqlx::query_file!("sql/delete/prices/by_splits.sql", transaction_id)
69
744
        .execute(&mut *tx)
70
744
        .await?;
71
744
    sqlx::query_file!(
72
        "sql/delete/transaction_tags/by_transaction.sql",
73
        transaction_id
74
    )
75
744
    .execute(&mut *tx)
76
744
    .await?;
77
744
    for tag_id in linked {
78
1359
        delete_tag_if_orphaned(&mut tx, tag_id).await?;
79
    }
80
744
    sqlx::query_file!("sql/delete/splits/by_transaction.sql", transaction_id)
81
744
        .execute(&mut *tx)
82
744
        .await?;
83
744
    sqlx::query_file!("sql/delete/transactions/by_id.sql", transaction_id)
84
744
        .execute(&mut *tx)
85
744
        .await?;
86
744
    tx.commit().await?;
87
744
    Ok(Ok(()))
88
1552
}
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.
93
command! {
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
2
        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
5495
}
120

            
121
// Looks up a single tag value by name on a transaction. Returns
122
// `CmdResult::String("")` when absent (matches `GetSplitTag`).
123
command! {
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
15
}