1
use server::command::transaction::{
2
    CreateTransaction, DeleteTransaction, GetTransaction, GetTransactionTag, ListTransactions,
3
    SetTransactionTag, UpdateTransaction,
4
};
5
use server::command::{CmdResult, FinanceEntity};
6
use uuid::Uuid;
7
use wasmtime::{Caller, Rooted, StructRef};
8

            
9
use super::parse::{
10
    parse_account_filter_arg, parse_create_transaction_payload, parse_transaction_id_arg,
11
    parse_update_transaction_payload,
12
};
13
use super::render::{
14
    TransactionEntry, alloc_transaction_entity, list_transaction_entries, render_full_transaction,
15
};
16
use crate::forms::{self, Failure, user_zone};
17
use crate::host_failure::cmd_failure;
18
use crate::natives::args::{args_error, present, required, tag_name_arg, uuid_arg};
19
use crate::natives::forms::native_failure;
20
use crate::session::SessionData;
21

            
22
/// `set-transaction-tag` upsert (idempotent). Mirrors `set-split-tag`
23
/// and `set-account-tag` — the wasm-side native returns `t` on success
24
/// (ADR-0033 Phase 5); this host fn's own return stays `i32` (1), which
25
/// the compiler's `bool` token maps onto the same wire ABI.
26
pub(super) async fn run_set_transaction_tag(
27
    user_id: Uuid,
28
    id_arg: Option<String>,
29
    name_arg: Option<String>,
30
    value_arg: Option<String>,
31
) -> wasmtime::Result<i32> {
32
    let transaction_id = uuid_arg("set-transaction-tag", "transaction-id", id_arg)?;
33
    let tag_name = tag_name_arg("set-transaction-tag", name_arg)?;
34
    let tag_value = present("set-transaction-tag", "tag-value", value_arg)?;
35
    SetTransactionTag::new()
36
        .user_id(user_id)
37
        .transaction_id(transaction_id)
38
        .tag_name(tag_name)
39
        .tag_value(tag_value)
40
        .run()
41
        .await
42
        .map(|_| 1)
43
        .map_err(|err| cmd_failure("set-transaction-tag", err))
44
}
45

            
46
/// `get-transaction-tag` lookup. Empty-string return when the tag is unset —
47
/// same shape as `get-split-tag`; a missing transaction fails as not-found.
48
pub(super) async fn run_get_transaction_tag(
49
    user_id: Uuid,
50
    id_arg: Option<String>,
51
    name_arg: Option<String>,
52
) -> wasmtime::Result<String> {
53
    let transaction_id = uuid_arg("get-transaction-tag", "transaction-id", id_arg)?;
54
    let tag_name = tag_name_arg("get-transaction-tag", name_arg)?;
55
    match GetTransactionTag::new()
56
        .user_id(user_id)
57
        .transaction_id(transaction_id)
58
        .tag_name(tag_name)
59
        .run()
60
        .await
61
    {
62
        Ok(Some(CmdResult::String(s))) => Ok(s),
63
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
64
            "get-transaction-tag: expected String, got {other:?}"
65
        ))),
66
        Ok(None) => Ok(String::new()),
67
        Err(err) => Err(cmd_failure("get-transaction-tag", err)),
68
    }
69
}
70

            
71
/// Companion to create-transaction. Payload mirrors the create shape but
72
/// `:transaction-id` is required (the row being updated) and every other
73
/// field is optional — caller only supplies what they want changed.
74
/// Splits when present REPLACE the existing set; a replacement with a stored
75
/// split's `:id` keeps the reconcile state, reconcile date and lot it omits.
76
169
pub(super) async fn run_update_transaction(
77
169
    user_id: Uuid,
78
169
    payload_arg: Option<String>,
79
169
) -> wasmtime::Result<String> {
80
169
    let payload = required("update-transaction", "payload", payload_arg)?;
81
168
    let input = parse_update_transaction_payload(&payload)
82
        .map_err(|err| args_error(format!("update-transaction: {err}")))?;
83
168
    let mut runner = UpdateTransaction::new()
84
168
        .user_id(user_id)
85
168
        .transaction_id(input.transaction_id);
86
168
    if let Some(post_date) = input.post_date {
87
        runner = runner.post_date(post_date);
88
168
    }
89
168
    if let Some(enter_date) = input.enter_date {
90
        runner = runner.enter_date(enter_date);
91
168
    }
92
168
    if let Some(note) = input.note {
93
160
        runner = runner.note(note);
94
8
    }
95
168
    if let Some(splits) = input.splits {
96
14
        let keep_stored = splits.iter().map(|(s, keep)| (s.id, *keep)).collect();
97
7
        let entities: Vec<FinanceEntity> = splits
98
7
            .into_iter()
99
14
            .map(|(mut s, _)| {
100
14
                s.tx_id = input.transaction_id;
101
14
                FinanceEntity::Split(s)
102
14
            })
103
            .collect();
104
7
        runner = runner.splits(entities).keep_stored(keep_stored);
105
161
    }
106
168
    if !input.prices.is_empty() {
107
        let price_entities: Vec<FinanceEntity> =
108
3
            input.prices.into_iter().map(FinanceEntity::Price).collect();
109
3
        runner = runner.prices(price_entities);
110
165
    }
111
168
    match runner.run().await {
112
7
        Ok(Some(CmdResult::Entity(FinanceEntity::Transaction(tx)))) => Ok(tx.id.to_string()),
113
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
114
            "update-transaction: expected Transaction entity, got {other:?}"
115
        ))),
116
        Ok(None) => Err(wasmtime::Error::msg(
117
            "update-transaction: command returned no entity",
118
        )),
119
161
        Err(err) => Err(cmd_failure("update-transaction", err)),
120
    }
121
169
}
122

            
123
4963
pub(super) async fn run_create_transaction(
124
4963
    user_id: Uuid,
125
4963
    payload_arg: Option<String>,
126
4963
) -> wasmtime::Result<String> {
127
4963
    let payload = required("create-transaction", "payload", payload_arg)?;
128
4962
    let input = parse_create_transaction_payload(&payload)
129
1
        .map_err(|err| args_error(format!("create-transaction: {err}")))?;
130
4961
    let splits: Vec<FinanceEntity> = input
131
4961
        .splits
132
4961
        .into_iter()
133
10082
        .map(|mut s| {
134
10082
            s.tx_id = input.id;
135
10082
            FinanceEntity::Split(s)
136
10082
        })
137
        .collect();
138
4961
    let mut runner = CreateTransaction::new()
139
4961
        .user_id(user_id)
140
4961
        .id(input.id)
141
4961
        .post_date(input.post_date)
142
4961
        .enter_date(input.enter_date)
143
4961
        .splits(splits);
144
4961
    if let Some(note) = input.note {
145
3520
        runner = runner.note(note);
146
1441
    }
147
4961
    if !input.prices.is_empty() {
148
        let price_entities: Vec<FinanceEntity> =
149
320
            input.prices.into_iter().map(FinanceEntity::Price).collect();
150
320
        runner = runner.prices(price_entities);
151
4641
    }
152
4961
    match runner.run().await {
153
4961
        Ok(Some(CmdResult::Entity(FinanceEntity::Transaction(tx)))) => Ok(tx.id.to_string()),
154
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
155
            "create-transaction: expected Transaction entity, got {other:?}"
156
        ))),
157
        Ok(None) => Err(wasmtime::Error::msg(
158
            "create-transaction: command returned no entity",
159
        )),
160
        Err(err) => Err(cmd_failure("create-transaction", err)),
161
    }
162
4963
}
163

            
164
/// Removes the transaction by UUID along with its splits, prices, and
165
/// owned tags. Not idempotent — server returns an error when the row
166
/// isn't there. Returns `t` on success.
167
642
pub(super) async fn run_delete_transaction(
168
642
    user_id: Uuid,
169
642
    id_arg: Option<String>,
170
642
) -> wasmtime::Result<i32> {
171
642
    let transaction_id = uuid_arg("delete-transaction", "transaction-id", id_arg)?;
172
640
    DeleteTransaction::new()
173
640
        .user_id(user_id)
174
640
        .transaction_id(transaction_id)
175
640
        .run()
176
640
        .await
177
        .map(|_| 1)
178
320
        .map_err(|err| cmd_failure("delete-transaction", err))
179
642
}
180

            
181
320
pub(super) async fn run_get_transaction(
182
320
    caller: &mut Caller<'_, SessionData>,
183
320
    user_id: Uuid,
184
320
    id_arg: Option<String>,
185
320
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
186
320
    let transaction_id = parse_transaction_id_arg(id_arg)?;
187
320
    let result = GetTransaction::new()
188
320
        .user_id(user_id)
189
320
        .transaction_id(transaction_id)
190
320
        .run()
191
320
        .await;
192
320
    let entries = list_transaction_entries("get-transaction", result)?;
193
320
    match entries.into_iter().next() {
194
        Some((id, note, amount, post_date)) => Ok(Some(
195
160
            alloc_transaction_entity(
196
160
                caller,
197
160
                &id,
198
160
                note.as_deref(),
199
160
                amount.as_deref(),
200
160
                Some(&post_date),
201
160
            )
202
160
            .await?,
203
        )),
204
160
        None => Ok(None),
205
    }
206
320
}
207

            
208
/// `get-transaction-detail` — returns the full transaction as a string
209
/// plist (`:id :post-date :enter-date :note :splits :prices`) so a client
210
/// can reconstruct + edit it. Empty `:prices ()` when single-currency.
211
3529
pub(super) async fn run_get_transaction_detail(
212
3529
    user_id: Uuid,
213
3529
    id_arg: Option<String>,
214
3529
) -> wasmtime::Result<Option<String>> {
215
3529
    let transaction_id = parse_transaction_id_arg(id_arg)?;
216
3529
    match forms::detail(user_id, transaction_id).await {
217
        Ok(detail) => {
218
3368
            let zone = user_zone(user_id).await.map_err(native_failure)?;
219
3368
            render_full_transaction("get-transaction-detail", &detail, zone).map(Some)
220
        }
221
161
        Err(Failure::Missing(_)) => Ok(None),
222
        Err(other) => Err(native_failure(other)),
223
    }
224
3529
}
225

            
226
1121
pub(super) async fn run_list_transactions(
227
1121
    user_id: Uuid,
228
1121
    account_arg: Option<String>,
229
1121
) -> wasmtime::Result<Vec<TransactionEntry>> {
230
1121
    let mut cmd = ListTransactions::new().user_id(user_id);
231
1121
    if let Some(account_id) = parse_account_filter_arg(account_arg)? {
232
160
        cmd = cmd.account(account_id);
233
961
    }
234
1121
    let result = cmd.run().await;
235
1121
    list_transaction_entries("list-transactions", result)
236
1121
}