Lines
96.33 %
Functions
68.42 %
Branches
100 %
//! `transaction show`: the stored transaction rendered for humans.
use std::collections::HashMap;
use nomiscript::{Value, list_to_vec};
use rpc::Session;
use crate::CommandError;
use crate::eval::{next_id, plist_field, plist_field_raw, render_error_to_command};
use crate::render::{WireValue, parse_wire, reparse_list};
use forms::escape_str;
type Labels = HashMap<String, String>;
/// The `get-transaction-detail` lines of `id`.
///
/// # Errors
/// [`CommandError::Command`] for an unknown id or an unreadable reply.
pub async fn show(session: &mut Session, id: &str) -> Result<Vec<String>, CommandError> {
let frame = format!("(:id {} :form {})", next_id(), detail_form(id));
render_detail_reply(&session.handle_form(&frame).await)?
.ok_or_else(|| CommandError::Command(format!("no transaction {id}")))
}
/// One form that answers with the detail and both label lists, for clients
/// that cannot make three round trips; render its reply with [`render_detail_reply`].
#[must_use]
pub fn detail_form(id: &str) -> String {
format!(
r#"(list (get-transaction-detail {}) (form-options "accounts") (form-options "commodities"))"#,
escape_str(id)
)
/// The `show` lines of a [`detail_form`] wire reply; `None` when the transaction does not exist.
/// [`CommandError::Command`] for a server error or a reply of another shape.
pub fn render_detail_reply(wire: &str) -> Result<Option<Vec<String>>, CommandError> {
let WireValue::Value(value) = parse_wire(wire).map_err(render_error_to_command)?;
let parts = list_to_vec(&value).unwrap_or_default();
if let [Value::Nil, Value::String(_), Value::String(_)] = parts.as_slice() {
return Ok(None);
let [
Value::String(detail),
Value::String(accounts),
Value::String(commodities),
] = parts.as_slice()
else {
return Err(CommandError::Command(format!(
"malformed detail reply: {wire}"
)));
};
render_detail(
detail,
&parse_labels(accounts)?,
&parse_labels(commodities)?,
.map(Some)
fn parse_labels(text: &str) -> Result<Labels, CommandError> {
let malformed = || CommandError::Command(format!("malformed options: {text}"));
let options = reparse_list(text).map_err(|_| malformed())?;
let Some(items) = list_to_vec(&options) else {
return Ok(Labels::new());
items
.iter()
.map(|item| Some((plist_field(item, ":id")?, plist_field(item, ":label")?)))
.collect::<Option<_>>()
.ok_or_else(malformed)
fn amount_of(value: Option<Value>) -> Option<String> {
match value? {
Value::Number(n) => {
let value = n.value();
Some(amount::display(*value.numer(), *value.denom()))
_ => None,
fn items_of(detail: &Value, key: &str) -> Option<Vec<Value>> {
list_to_vec(&plist_field_raw(detail, key)?)
fn name<'a>(labels: &'a Labels, id: &'a str) -> &'a str {
labels.get(id).map_or(id, String::as_str)
fn tag_lines(owner: &Value, indent: &str) -> Option<Vec<String>> {
items_of(owner, ":tags")?
.map(|tag| {
let (name, value) = (plist_field(tag, ":name")?, plist_field(tag, ":value")?);
Some(match plist_field(tag, ":description") {
Some(description) => format!("{indent}{name}={value} ({description})"),
None => format!("{indent}{name}={value}"),
})
.collect()
fn split_lines(split: &Value, accounts: &Labels, commodities: &Labels) -> Option<Vec<String>> {
let account = plist_field(split, ":account-id")?;
let commodity = plist_field(split, ":commodity-id")?;
let value = amount_of(plist_field_raw(split, ":value"))?;
let mut lines = vec![format!(
" {} {value} {}",
name(accounts, &account),
name(commodities, &commodity)
)];
lines.extend(tag_lines(split, " ")?);
Some(lines)
fn price_line(price: &Value, commodities: &Labels) -> Option<String> {
let commodity = plist_field(price, ":commodity-id")?;
let currency = plist_field(price, ":currency-id")?;
let rate = amount::display(
plist_field(price, ":value-num")?.parse().ok()?,
plist_field(price, ":value-denom")?.parse().ok()?,
);
Some(format!(
" 1 {} = {rate} {} {}",
name(commodities, &commodity),
name(commodities, ¤cy),
plist_field(price, ":date-text")?
))
/// [`CommandError::Command`] when `text` is not a transaction detail plist.
pub fn render_detail(
text: &str,
accounts: &Labels,
commodities: &Labels,
) -> Result<Vec<String>, CommandError> {
let malformed = || CommandError::Command(format!("no such transaction or bad reply: {text}"));
let detail = reparse_list(text).map_err(|_| malformed())?;
let mut lines = vec![
"Transaction {}",
plist_field(&detail, ":id").ok_or_else(malformed)?
),
"Date: {}",
plist_field(&detail, ":post-date-text").ok_or_else(malformed)?
"Note: {}",
plist_field(&detail, ":note").unwrap_or_default()
];
let tags = tag_lines(&detail, " ").ok_or_else(malformed)?;
if !tags.is_empty() {
lines.push("Tags:".to_string());
lines.extend(tags);
lines.push("Splits:".to_string());
for split in items_of(&detail, ":splits").ok_or_else(malformed)? {
lines.extend(split_lines(&split, accounts, commodities).ok_or_else(malformed)?);
let prices = items_of(&detail, ":prices").ok_or_else(malformed)?;
if !prices.is_empty() {
lines.push("Prices:".to_string());
for price in prices {
lines.push(price_line(&price, commodities).ok_or_else(malformed)?);
Ok(lines)