1
use finance::price::Price;
2
use scripting::runtime::{alloc_entity_via_export, alloc_pair_chain, alloc_string_ref};
3
use server::command::{CmdError, CmdResult, FinanceEntity};
4
use server::logical::note_value;
5
use server::timezone::{Tz, display};
6
use wasmtime::{AnyRef, Caller, Rooted, StructRef, Val};
7

            
8
use super::logical_view::render_tags;
9
use crate::forms::{StoredSplit, TransactionDetail};
10
use crate::host_failure::cmd_failure;
11
use crate::session::SessionData;
12

            
13
/// One listed transaction: `(id, note, amount, post-date)`.
14
pub(super) type TransactionEntry = (String, Option<String>, Option<String>, String);
15

            
16
1444
pub(super) fn list_transaction_entries(
17
1444
    name: &str,
18
1444
    result: Result<Option<CmdResult>, CmdError>,
19
1444
) -> wasmtime::Result<Vec<TransactionEntry>> {
20
1444
    match result {
21
1284
        Ok(Some(CmdResult::TaggedTransactions { entities, .. })) => Ok(entities
22
1284
            .into_iter()
23
1924
            .filter_map(|(entity, tags, amount)| match entity {
24
1924
                FinanceEntity::Transaction(tx) => Some((
25
1924
                    tx.id.to_string(),
26
1924
                    note_value(&tags).map(str::to_string),
27
1924
                    amount,
28
1924
                    tx.post_date.to_rfc3339(),
29
1924
                )),
30
                _ => None,
31
1924
            })
32
            .collect()),
33
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
34
            "{name}: expected TaggedTransactions, got {other:?}"
35
        ))),
36
160
        Ok(None) => Ok(Vec::new()),
37
        Err(err) => Err(cmd_failure(name, err)),
38
    }
39
1444
}
40

            
41
1920
pub(super) async fn alloc_transaction_entity(
42
1920
    caller: &mut Caller<'_, SessionData>,
43
1920
    id: &str,
44
1920
    note: Option<&str>,
45
1920
    amount: Option<&str>,
46
1920
    post_date: Option<&str>,
47
1920
) -> wasmtime::Result<Rooted<StructRef>> {
48
1920
    let id_ref = alloc_string_ref(caller, id.as_bytes())?;
49
1920
    let note_ref = note
50
1280
        .map(|s| alloc_string_ref(caller, s.as_bytes()))
51
        .transpose()?;
52
1920
    let amount_ref = amount
53
1920
        .map(|s| alloc_string_ref(caller, s.as_bytes()))
54
        .transpose()?;
55
1920
    let date_ref = post_date
56
1920
        .map(|s| alloc_string_ref(caller, s.as_bytes()))
57
        .transpose()?;
58
    let args = [
59
1920
        Val::AnyRef(Some(id_ref.to_anyref())),
60
1920
        Val::AnyRef(note_ref.map(|r| r.to_anyref())),
61
1920
        Val::AnyRef(amount_ref.map(|r| r.to_anyref())),
62
1920
        Val::AnyRef(date_ref.map(|r| r.to_anyref())),
63
    ];
64
1920
    alloc_entity_via_export(caller, "alloc_transaction", &args).await
65
1920
}
66

            
67
1120
pub(super) async fn alloc_transaction_chain(
68
1120
    caller: &mut Caller<'_, SessionData>,
69
1120
    entries: Vec<TransactionEntry>,
70
1120
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
71
1120
    let mut anyrefs: Vec<Option<Rooted<AnyRef>>> = Vec::with_capacity(entries.len());
72
1120
    for (id, note, amount, post_date) in entries {
73
1760
        let entity_ref = alloc_transaction_entity(
74
1760
            caller,
75
1760
            &id,
76
1760
            note.as_deref(),
77
1760
            amount.as_deref(),
78
1760
            Some(&post_date),
79
1760
        )
80
1760
        .await?;
81
1760
        anyrefs.push(Some(entity_ref.to_anyref()));
82
    }
83
1120
    alloc_pair_chain(caller, anyrefs).await
84
1120
}
85

            
86
/// Escape a string for nomiscript plist output.
87
6634
pub(super) fn quote_string(s: &str) -> String {
88
6634
    let mut q = String::with_capacity(s.len() + 2);
89
6634
    q.push('"');
90
6634
    for ch in s.chars() {
91
32687
        match ch {
92
12
            '"' => q.push_str("\\\""),
93
320
            '\\' => q.push_str("\\\\"),
94
32355
            other => q.push(other),
95
        }
96
    }
97
6634
    q.push('"');
98
6634
    q
99
6634
}
100

            
101
7696
fn render_split(name: &str, split: &StoredSplit) -> wasmtime::Result<String> {
102
7696
    let s = &split.split;
103
7696
    let value = amount::wire_token(s.value_num, s.value_denom).ok_or_else(|| {
104
        wasmtime::Error::msg(format!("{name}: split {} has a zero denominator", s.id))
105
    })?;
106
7696
    Ok(format!(
107
7696
        "(:id \"{}\" :account-id \"{}\" :commodity-id \"{}\" :value {} :tags {})",
108
7696
        s.id,
109
7696
        s.account_id,
110
7696
        s.commodity_id,
111
7696
        value,
112
7696
        render_tags(&split.tags),
113
7696
    ))
114
7696
}
115

            
116
802
fn render_price(price: &Price, zone: Tz) -> Option<String> {
117
802
    let (commodity_split, currency_split) = (price.commodity_split?, price.currency_split?);
118
802
    Some(format!(
119
802
        "(:id \"{}\" :commodity-id \"{}\" :currency-id \"{}\" \
120
802
         :commodity-split \"{}\" :currency-split \"{}\" \
121
802
         :value-num {} :value-denom {} :date \"{}\" :date-text \"{}\")",
122
802
        price.id,
123
802
        price.commodity_id,
124
802
        price.currency_id,
125
802
        commodity_split,
126
802
        currency_split,
127
802
        price.value_num,
128
802
        price.value_denom,
129
802
        price.date.to_rfc3339(),
130
802
        display(price.date, zone),
131
802
    ))
132
802
}
133

            
134
/// Render a full transaction plist from one [`TransactionDetail`].
135
///
136
/// Backs the `get-transaction-detail` native: the reply is a string plist
137
/// carrying the transaction header plus its physical `:splits` and `:prices`,
138
/// with split/price keys symmetric to what create/update-transaction parse.
139
/// Every transaction and split plist ends with `:tags` (empty list when
140
/// untagged); the transaction's `note` tag is `:note`, not repeated there,
141
/// while a split tag named `note` stays in the split's `:tags`.
142
3368
pub(super) fn render_full_transaction(
143
3368
    name: &str,
144
3368
    detail: &TransactionDetail,
145
3368
    zone: Tz,
146
3368
) -> wasmtime::Result<String> {
147
3368
    let tx = &detail.transaction;
148
3368
    let note = detail
149
3368
        .note
150
3368
        .as_deref()
151
3366
        .map(|n| format!(" :note {}", quote_string(n)))
152
        .unwrap_or_default();
153
3368
    let splits = detail
154
3368
        .splits
155
3368
        .iter()
156
7696
        .map(|split| render_split(name, split))
157
        .collect::<wasmtime::Result<Vec<_>>>()?;
158
3368
    let prices: Vec<String> = detail
159
3368
        .prices
160
3368
        .iter()
161
802
        .filter_map(|price| render_price(price, zone))
162
        .collect();
163
3368
    Ok(format!(
164
3368
        "(:id \"{}\" :post-date \"{}\" :post-date-text \"{}\" :enter-date \"{}\"{note} :splits ({}) :prices ({}) :tags {})",
165
3368
        tx.id,
166
3368
        tx.post_date.to_rfc3339(),
167
3368
        display(tx.post_date, zone),
168
3368
        tx.enter_date.to_rfc3339(),
169
3368
        splits.join(""),
170
3368
        prices.join(""),
171
3368
        render_tags(&detail.tags),
172
3368
    ))
173
3368
}
174

            
175
/// Test-only legacy renderer; production paths now ship typed
176
/// `pair<transaction>` / `EntityRef(Transaction)` via the alloc helpers.
177
/// Retained for the existing format-assertion tests until A6 collapses
178
/// the streaming-string capture protocol.
179
#[cfg(test)]
180
5
pub(super) fn format_tagged_transactions(
181
5
    entities: &[(
182
5
        FinanceEntity,
183
5
        std::collections::HashMap<String, FinanceEntity>,
184
5
    )],
185
5
    pagination: Option<&server::command::PaginationInfo>,
186
5
) -> String {
187
5
    let mut out = String::from("(:transactions (");
188
5
    for (idx, (entity, tags)) in entities.iter().enumerate() {
189
3
        if idx > 0 {
190
            out.push(' ');
191
3
        }
192
3
        match entity {
193
            FinanceEntity::Transaction(tx) => {
194
3
                out.push_str(&format!(
195
3
                    "(:id \"{}\" :post-date \"{}\" :enter-date \"{}\"",
196
3
                    tx.id,
197
3
                    tx.post_date.to_rfc3339(),
198
3
                    tx.enter_date.to_rfc3339()
199
3
                ));
200
3
                if let Some(note) = note_value(tags) {
201
2
                    out.push_str(&format!(" :note {}", quote_string(note)));
202
1
                }
203
3
                out.push(')');
204
            }
205
            other => {
206
                out.push_str(&format!("(:error \"unexpected entity {other:?}\")"));
207
            }
208
        }
209
    }
210
5
    out.push_str(") :pagination ");
211
5
    match pagination {
212
2
        Some(p) => out.push_str(&format!(
213
            "(:total {} :limit {} :offset {} :has-more {})",
214
2
            p.total_count,
215
2
            p.limit,
216
2
            p.offset,
217
2
            if p.has_more { "t" } else { "nil" }
218
        )),
219
3
        None => out.push_str("nil"),
220
    }
221
5
    out.push(')');
222
5
    out
223
5
}