cli_core/transaction/
show.rs1use std::collections::HashMap;
4
5use nomiscript::{Value, list_to_vec};
6use rpc::Session;
7
8use crate::CommandError;
9use crate::eval::{next_id, plist_field, plist_field_raw, render_error_to_command};
10use crate::render::{WireValue, parse_wire, reparse_list};
11use forms::escape_str;
12
13type Labels = HashMap<String, String>;
14
15pub async fn show(session: &mut Session, id: &str) -> Result<Vec<String>, CommandError> {
20 let frame = format!("(:id {} :form {})", next_id(), detail_form(id));
21 render_detail_reply(&session.handle_form(&frame).await)?
22 .ok_or_else(|| CommandError::Command(format!("no transaction {id}")))
23}
24
25#[must_use]
28pub fn detail_form(id: &str) -> String {
29 format!(
30 r#"(list (get-transaction-detail {}) (form-options "accounts") (form-options "commodities"))"#,
31 escape_str(id)
32 )
33}
34
35pub fn render_detail_reply(wire: &str) -> Result<Option<Vec<String>>, CommandError> {
40 let WireValue::Value(value) = parse_wire(wire).map_err(render_error_to_command)?;
41 let parts = list_to_vec(&value).unwrap_or_default();
42 if let [Value::Nil, Value::String(_), Value::String(_)] = parts.as_slice() {
43 return Ok(None);
44 }
45 let [
46 Value::String(detail),
47 Value::String(accounts),
48 Value::String(commodities),
49 ] = parts.as_slice()
50 else {
51 return Err(CommandError::Command(format!(
52 "malformed detail reply: {wire}"
53 )));
54 };
55 render_detail(
56 detail,
57 &parse_labels(accounts)?,
58 &parse_labels(commodities)?,
59 )
60 .map(Some)
61}
62
63fn parse_labels(text: &str) -> Result<Labels, CommandError> {
64 let malformed = || CommandError::Command(format!("malformed options: {text}"));
65 let options = reparse_list(text).map_err(|_| malformed())?;
66 let Some(items) = list_to_vec(&options) else {
67 return Ok(Labels::new());
68 };
69 items
70 .iter()
71 .map(|item| Some((plist_field(item, ":id")?, plist_field(item, ":label")?)))
72 .collect::<Option<_>>()
73 .ok_or_else(malformed)
74}
75
76fn amount_of(value: Option<Value>) -> Option<String> {
77 match value? {
78 Value::Number(n) => {
79 let value = n.value();
80 Some(amount::display(*value.numer(), *value.denom()))
81 }
82 _ => None,
83 }
84}
85
86fn items_of(detail: &Value, key: &str) -> Option<Vec<Value>> {
87 list_to_vec(&plist_field_raw(detail, key)?)
88}
89
90fn name<'a>(labels: &'a Labels, id: &'a str) -> &'a str {
91 labels.get(id).map_or(id, String::as_str)
92}
93
94fn tag_lines(owner: &Value, indent: &str) -> Option<Vec<String>> {
95 items_of(owner, ":tags")?
96 .iter()
97 .map(|tag| {
98 let (name, value) = (plist_field(tag, ":name")?, plist_field(tag, ":value")?);
99 Some(match plist_field(tag, ":description") {
100 Some(description) => format!("{indent}{name}={value} ({description})"),
101 None => format!("{indent}{name}={value}"),
102 })
103 })
104 .collect()
105}
106
107fn split_lines(split: &Value, accounts: &Labels, commodities: &Labels) -> Option<Vec<String>> {
108 let account = plist_field(split, ":account-id")?;
109 let commodity = plist_field(split, ":commodity-id")?;
110 let value = amount_of(plist_field_raw(split, ":value"))?;
111 let mut lines = vec![format!(
112 " {} {value} {}",
113 name(accounts, &account),
114 name(commodities, &commodity)
115 )];
116 lines.extend(tag_lines(split, " ")?);
117 Some(lines)
118}
119
120fn price_line(price: &Value, commodities: &Labels) -> Option<String> {
121 let commodity = plist_field(price, ":commodity-id")?;
122 let currency = plist_field(price, ":currency-id")?;
123 let rate = amount::display(
124 plist_field(price, ":value-num")?.parse().ok()?,
125 plist_field(price, ":value-denom")?.parse().ok()?,
126 );
127 Some(format!(
128 " 1 {} = {rate} {} {}",
129 name(commodities, &commodity),
130 name(commodities, ¤cy),
131 plist_field(price, ":date-text")?
132 ))
133}
134
135pub fn render_detail(
138 text: &str,
139 accounts: &Labels,
140 commodities: &Labels,
141) -> Result<Vec<String>, CommandError> {
142 let malformed = || CommandError::Command(format!("no such transaction or bad reply: {text}"));
143 let detail = reparse_list(text).map_err(|_| malformed())?;
144 let mut lines = vec![
145 format!(
146 "Transaction {}",
147 plist_field(&detail, ":id").ok_or_else(malformed)?
148 ),
149 format!(
150 "Date: {}",
151 plist_field(&detail, ":post-date-text").ok_or_else(malformed)?
152 ),
153 format!(
154 "Note: {}",
155 plist_field(&detail, ":note").unwrap_or_default()
156 ),
157 ];
158 let tags = tag_lines(&detail, " ").ok_or_else(malformed)?;
159 if !tags.is_empty() {
160 lines.push("Tags:".to_string());
161 lines.extend(tags);
162 }
163 lines.push("Splits:".to_string());
164 for split in items_of(&detail, ":splits").ok_or_else(malformed)? {
165 lines.extend(split_lines(&split, accounts, commodities).ok_or_else(malformed)?);
166 }
167 let prices = items_of(&detail, ":prices").ok_or_else(malformed)?;
168 if !prices.is_empty() {
169 lines.push("Prices:".to_string());
170 }
171 for price in prices {
172 lines.push(price_line(&price, commodities).ok_or_else(malformed)?);
173 }
174 Ok(lines)
175}