1
//! `transaction show`: the stored transaction rendered for humans.
2

            
3
use std::collections::HashMap;
4

            
5
use nomiscript::{Value, list_to_vec};
6
use rpc::Session;
7

            
8
use crate::CommandError;
9
use crate::eval::{next_id, plist_field, plist_field_raw, render_error_to_command};
10
use crate::render::{WireValue, parse_wire, reparse_list};
11
use forms::escape_str;
12

            
13
type Labels = HashMap<String, String>;
14

            
15
/// The `get-transaction-detail` lines of `id`.
16
///
17
/// # Errors
18
/// [`CommandError::Command`] for an unknown id or an unreadable reply.
19
21
pub async fn show(session: &mut Session, id: &str) -> Result<Vec<String>, CommandError> {
20
21
    let frame = format!("(:id {} :form {})", next_id(), detail_form(id));
21
21
    render_detail_reply(&session.handle_form(&frame).await)?
22
1
        .ok_or_else(|| CommandError::Command(format!("no transaction {id}")))
23
21
}
24

            
25
/// One form that answers with the detail and both label lists, for clients
26
/// that cannot make three round trips; render its reply with [`render_detail_reply`].
27
#[must_use]
28
453
pub fn detail_form(id: &str) -> String {
29
453
    format!(
30
        r#"(list (get-transaction-detail {}) (form-options "accounts") (form-options "commodities"))"#,
31
453
        escape_str(id)
32
    )
33
453
}
34

            
35
/// The `show` lines of a [`detail_form`] wire reply; `None` when the transaction does not exist.
36
///
37
/// # Errors
38
/// [`CommandError::Command`] for a server error or a reply of another shape.
39
371
pub fn render_detail_reply(wire: &str) -> Result<Option<Vec<String>>, CommandError> {
40
371
    let WireValue::Value(value) = parse_wire(wire).map_err(render_error_to_command)?;
41
347
    let parts = list_to_vec(&value).unwrap_or_default();
42
347
    if let [Value::Nil, Value::String(_), Value::String(_)] = parts.as_slice() {
43
26
        return Ok(None);
44
321
    }
45
    let [
46
        Value::String(detail),
47
        Value::String(accounts),
48
        Value::String(commodities),
49
321
    ] = parts.as_slice()
50
    else {
51
1
        return Err(CommandError::Command(format!(
52
1
            "malformed detail reply: {wire}"
53
1
        )));
54
    };
55
320
    render_detail(
56
320
        detail,
57
320
        &parse_labels(accounts)?,
58
320
        &parse_labels(commodities)?,
59
    )
60
320
    .map(Some)
61
371
}
62

            
63
640
fn parse_labels(text: &str) -> Result<Labels, CommandError> {
64
    let malformed = || CommandError::Command(format!("malformed options: {text}"));
65
640
    let options = reparse_list(text).map_err(|_| malformed())?;
66
640
    let Some(items) = list_to_vec(&options) else {
67
        return Ok(Labels::new());
68
    };
69
640
    items
70
640
        .iter()
71
680
        .map(|item| Some((plist_field(item, ":id")?, plist_field(item, ":label")?)))
72
        .collect::<Option<_>>()
73
640
        .ok_or_else(malformed)
74
640
}
75

            
76
1308
fn amount_of(value: Option<Value>) -> Option<String> {
77
1308
    match value? {
78
        Value::Number(n) => {
79
1308
            let value = n.value();
80
1308
            Some(amount::display(*value.numer(), *value.denom()))
81
        }
82
        _ => None,
83
    }
84
1308
}
85

            
86
2277
fn items_of(detail: &Value, key: &str) -> Option<Vec<Value>> {
87
2277
    list_to_vec(&plist_field_raw(detail, key)?)
88
2277
}
89

            
90
2626
fn name<'a>(labels: &'a Labels, id: &'a str) -> &'a str {
91
2626
    labels.get(id).map_or(id, String::as_str)
92
2626
}
93

            
94
1631
fn tag_lines(owner: &Value, indent: &str) -> Option<Vec<String>> {
95
1631
    items_of(owner, ":tags")?
96
        .iter()
97
25
        .map(|tag| {
98
25
            let (name, value) = (plist_field(tag, ":name")?, plist_field(tag, ":value")?);
99
25
            Some(match plist_field(tag, ":description") {
100
1
                Some(description) => format!("{indent}{name}={value} ({description})"),
101
24
                None => format!("{indent}{name}={value}"),
102
            })
103
25
        })
104
        .collect()
105
1631
}
106

            
107
1308
fn split_lines(split: &Value, accounts: &Labels, commodities: &Labels) -> Option<Vec<String>> {
108
1308
    let account = plist_field(split, ":account-id")?;
109
1308
    let commodity = plist_field(split, ":commodity-id")?;
110
1308
    let value = amount_of(plist_field_raw(split, ":value"))?;
111
1308
    let mut lines = vec![format!(
112
1308
        "  {}  {value} {}",
113
1308
        name(accounts, &account),
114
1308
        name(commodities, &commodity)
115
    )];
116
1308
    lines.extend(tag_lines(split, "    ")?);
117
1308
    Some(lines)
118
1308
}
119

            
120
5
fn price_line(price: &Value, commodities: &Labels) -> Option<String> {
121
5
    let commodity = plist_field(price, ":commodity-id")?;
122
5
    let currency = plist_field(price, ":currency-id")?;
123
5
    let rate = amount::display(
124
5
        plist_field(price, ":value-num")?.parse().ok()?,
125
5
        plist_field(price, ":value-denom")?.parse().ok()?,
126
    );
127
5
    Some(format!(
128
5
        "  1 {} = {rate} {}  {}",
129
5
        name(commodities, &commodity),
130
5
        name(commodities, &currency),
131
5
        plist_field(price, ":date-text")?
132
    ))
133
5
}
134

            
135
/// # Errors
136
/// [`CommandError::Command`] when `text` is not a transaction detail plist.
137
323
pub fn render_detail(
138
323
    text: &str,
139
323
    accounts: &Labels,
140
323
    commodities: &Labels,
141
323
) -> Result<Vec<String>, CommandError> {
142
    let malformed = || CommandError::Command(format!("no such transaction or bad reply: {text}"));
143
323
    let detail = reparse_list(text).map_err(|_| malformed())?;
144
323
    let mut lines = vec![
145
323
        format!(
146
            "Transaction {}",
147
323
            plist_field(&detail, ":id").ok_or_else(malformed)?
148
        ),
149
323
        format!(
150
            "Date: {}",
151
323
            plist_field(&detail, ":post-date-text").ok_or_else(malformed)?
152
        ),
153
323
        format!(
154
            "Note: {}",
155
323
            plist_field(&detail, ":note").unwrap_or_default()
156
        ),
157
    ];
158
323
    let tags = tag_lines(&detail, "  ").ok_or_else(malformed)?;
159
323
    if !tags.is_empty() {
160
17
        lines.push("Tags:".to_string());
161
17
        lines.extend(tags);
162
306
    }
163
323
    lines.push("Splits:".to_string());
164
323
    for split in items_of(&detail, ":splits").ok_or_else(malformed)? {
165
1308
        lines.extend(split_lines(&split, accounts, commodities).ok_or_else(malformed)?);
166
    }
167
323
    let prices = items_of(&detail, ":prices").ok_or_else(malformed)?;
168
323
    if !prices.is_empty() {
169
5
        lines.push("Prices:".to_string());
170
318
    }
171
323
    for price in prices {
172
5
        lines.push(price_line(&price, commodities).ok_or_else(malformed)?);
173
    }
174
323
    Ok(lines)
175
323
}