Lines
92.31 %
Functions
70.73 %
Branches
100 %
use finance::price::Price;
use scripting::runtime::{alloc_entity_via_export, alloc_pair_chain, alloc_string_ref};
use server::command::{CmdError, CmdResult, FinanceEntity};
use server::logical::note_value;
use server::timezone::{Tz, display};
use wasmtime::{AnyRef, Caller, Rooted, StructRef, Val};
use super::logical_view::render_tags;
use crate::forms::{StoredSplit, TransactionDetail};
use crate::host_failure::cmd_failure;
use crate::session::SessionData;
/// One listed transaction: `(id, note, amount, post-date)`.
pub(super) type TransactionEntry = (String, Option<String>, Option<String>, String);
pub(super) fn list_transaction_entries(
name: &str,
result: Result<Option<CmdResult>, CmdError>,
) -> wasmtime::Result<Vec<TransactionEntry>> {
match result {
Ok(Some(CmdResult::TaggedTransactions { entities, .. })) => Ok(entities
.into_iter()
.filter_map(|(entity, tags, amount)| match entity {
FinanceEntity::Transaction(tx) => Some((
tx.id.to_string(),
note_value(&tags).map(str::to_string),
amount,
tx.post_date.to_rfc3339(),
)),
_ => None,
})
.collect()),
Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
"{name}: expected TaggedTransactions, got {other:?}"
))),
Ok(None) => Ok(Vec::new()),
Err(err) => Err(cmd_failure(name, err)),
}
pub(super) async fn alloc_transaction_entity(
caller: &mut Caller<'_, SessionData>,
id: &str,
note: Option<&str>,
amount: Option<&str>,
post_date: Option<&str>,
) -> wasmtime::Result<Rooted<StructRef>> {
let id_ref = alloc_string_ref(caller, id.as_bytes())?;
let note_ref = note
.map(|s| alloc_string_ref(caller, s.as_bytes()))
.transpose()?;
let amount_ref = amount
let date_ref = post_date
let args = [
Val::AnyRef(Some(id_ref.to_anyref())),
Val::AnyRef(note_ref.map(|r| r.to_anyref())),
Val::AnyRef(amount_ref.map(|r| r.to_anyref())),
Val::AnyRef(date_ref.map(|r| r.to_anyref())),
];
alloc_entity_via_export(caller, "alloc_transaction", &args).await
pub(super) async fn alloc_transaction_chain(
entries: Vec<TransactionEntry>,
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
let mut anyrefs: Vec<Option<Rooted<AnyRef>>> = Vec::with_capacity(entries.len());
for (id, note, amount, post_date) in entries {
let entity_ref = alloc_transaction_entity(
caller,
&id,
note.as_deref(),
amount.as_deref(),
Some(&post_date),
)
.await?;
anyrefs.push(Some(entity_ref.to_anyref()));
alloc_pair_chain(caller, anyrefs).await
/// Escape a string for nomiscript plist output.
pub(super) fn quote_string(s: &str) -> String {
let mut q = String::with_capacity(s.len() + 2);
q.push('"');
for ch in s.chars() {
match ch {
'"' => q.push_str("\\\""),
'\\' => q.push_str("\\\\"),
other => q.push(other),
q
fn render_split(name: &str, split: &StoredSplit) -> wasmtime::Result<String> {
let s = &split.split;
let value = amount::wire_token(s.value_num, s.value_denom).ok_or_else(|| {
wasmtime::Error::msg(format!("{name}: split {} has a zero denominator", s.id))
})?;
Ok(format!(
"(:id \"{}\" :account-id \"{}\" :commodity-id \"{}\" :value {} :tags {})",
s.id,
s.account_id,
s.commodity_id,
value,
render_tags(&split.tags),
))
fn render_price(price: &Price, zone: Tz) -> Option<String> {
let (commodity_split, currency_split) = (price.commodity_split?, price.currency_split?);
Some(format!(
"(:id \"{}\" :commodity-id \"{}\" :currency-id \"{}\" \
:commodity-split \"{}\" :currency-split \"{}\" \
:value-num {} :value-denom {} :date \"{}\" :date-text \"{}\")",
price.id,
price.commodity_id,
price.currency_id,
commodity_split,
currency_split,
price.value_num,
price.value_denom,
price.date.to_rfc3339(),
display(price.date, zone),
/// Render a full transaction plist from one [`TransactionDetail`].
///
/// Backs the `get-transaction-detail` native: the reply is a string plist
/// carrying the transaction header plus its physical `:splits` and `:prices`,
/// with split/price keys symmetric to what create/update-transaction parse.
/// Every transaction and split plist ends with `:tags` (empty list when
/// untagged); the transaction's `note` tag is `:note`, not repeated there,
/// while a split tag named `note` stays in the split's `:tags`.
pub(super) fn render_full_transaction(
detail: &TransactionDetail,
zone: Tz,
) -> wasmtime::Result<String> {
let tx = &detail.transaction;
let note = detail
.note
.as_deref()
.map(|n| format!(" :note {}", quote_string(n)))
.unwrap_or_default();
let splits = detail
.splits
.iter()
.map(|split| render_split(name, split))
.collect::<wasmtime::Result<Vec<_>>>()?;
let prices: Vec<String> = detail
.prices
.filter_map(|price| render_price(price, zone))
.collect();
"(:id \"{}\" :post-date \"{}\" :post-date-text \"{}\" :enter-date \"{}\"{note} :splits ({}) :prices ({}) :tags {})",
tx.id,
display(tx.post_date, zone),
tx.enter_date.to_rfc3339(),
splits.join(""),
prices.join(""),
render_tags(&detail.tags),
/// Test-only legacy renderer; production paths now ship typed
/// `pair<transaction>` / `EntityRef(Transaction)` via the alloc helpers.
/// Retained for the existing format-assertion tests until A6 collapses
/// the streaming-string capture protocol.
#[cfg(test)]
pub(super) fn format_tagged_transactions(
entities: &[(
FinanceEntity,
std::collections::HashMap<String, FinanceEntity>,
)],
pagination: Option<&server::command::PaginationInfo>,
) -> String {
let mut out = String::from("(:transactions (");
for (idx, (entity, tags)) in entities.iter().enumerate() {
if idx > 0 {
out.push(' ');
match entity {
FinanceEntity::Transaction(tx) => {
out.push_str(&format!(
"(:id \"{}\" :post-date \"{}\" :enter-date \"{}\"",
tx.enter_date.to_rfc3339()
));
if let Some(note) = note_value(tags) {
out.push_str(&format!(" :note {}", quote_string(note)));
out.push(')');
other => {
out.push_str(&format!("(:error \"unexpected entity {other:?}\")"));
out.push_str(") :pagination ");
match pagination {
Some(p) => out.push_str(&format!(
"(:total {} :limit {} :offset {} :has-more {})",
p.total_count,
p.limit,
p.offset,
if p.has_more { "t" } else { "nil" }
None => out.push_str("nil"),
out