1
//! Template commands over the template forms and `form-options "templates"`.
2

            
3
use forms::{FormValues, TEMPLATE_CREATE, TEMPLATE_EDIT, TEMPLATE_TEST, escape_str};
4
use nomiscript::{Value, list_to_vec};
5
use rpc::Session;
6

            
7
use crate::CommandError;
8
use crate::eval::{plist_field, plist_field_raw};
9
use crate::flat::{Reply, edit as edit_form, load_values, submit};
10
use crate::forms::{FormOption, parse_option_list};
11
use crate::transaction::{eval_text, eval_value, submit_call};
12

            
13
72
pub(crate) async fn options(
14
72
    session: &mut Session,
15
72
    source: &str,
16
72
) -> Result<Vec<FormOption>, CommandError> {
17
72
    let call = format!("(form-options {})", escape_str(source));
18
72
    Ok(parse_option_list(&eval_text(session, &call).await?))
19
72
}
20

            
21
/// One line per stored template: its id and name.
22
///
23
/// # Errors
24
/// The server error.
25
53
pub async fn list(session: &mut Session) -> Result<Vec<String>, CommandError> {
26
53
    let templates = options(session, "templates").await?;
27
53
    Ok(templates
28
53
        .iter()
29
27
        .map(|template| format!("{}  {}", template.id, template.label))
30
        .collect())
31
53
}
32

            
33
56
fn stored_id(reply: Reply) -> Result<String, CommandError> {
34
56
    match reply {
35
56
        Reply::Entity(id) => Ok(id),
36
        other => Err(CommandError::Command(format!(
37
            "unexpected template reply: {other:?}"
38
        ))),
39
    }
40
56
}
41

            
42
60
fn values_of(name: Option<&str>, source: Option<&str>) -> FormValues {
43
60
    let mut values = FormValues::default();
44
60
    name.into_iter().for_each(|name| values.set("name", name));
45
60
    source
46
60
        .into_iter()
47
59
        .for_each(|source| values.set("source", source));
48
60
    values
49
60
}
50

            
51
/// Store a new template and return its id.
52
///
53
/// # Errors
54
/// [`CommandError::FormInvalid`] for a source that does not compile, or the server error.
55
55
pub async fn create(
56
55
    session: &mut Session,
57
55
    name: Option<&str>,
58
55
    source: &str,
59
55
) -> Result<String, CommandError> {
60
55
    let values = values_of(name, Some(source));
61
55
    stored_id(submit(session, &TEMPLATE_CREATE, &values).await?.reply)
62
55
}
63

            
64
/// Replace the given fields of template `id`, keeping the rest as stored.
65
///
66
/// # Errors
67
/// The server's refusal of the load, [`CommandError::FormInvalid`] for a
68
/// source that does not compile or a stale revision.
69
2
pub async fn edit(
70
2
    session: &mut Session,
71
2
    id: &str,
72
2
    name: Option<&str>,
73
2
    source: Option<&str>,
74
2
) -> Result<String, CommandError> {
75
2
    let values = values_of(name, source);
76
2
    stored_id(edit_form(session, &TEMPLATE_EDIT, id, &values).await?.reply)
77
2
}
78

            
79
/// The stored source of template `id`.
80
///
81
/// # Errors
82
/// The server's refusal of the load.
83
3
pub async fn stored_source(session: &mut Session, id: &str) -> Result<String, CommandError> {
84
3
    let loaded = load_values(session, &TEMPLATE_EDIT, id).await?;
85
3
    Ok(loaded.text("source").unwrap_or_default().to_string())
86
3
}
87

            
88
/// The read-only printout of `source` rendered against the user's data.
89
///
90
/// # Errors
91
/// [`CommandError::FormInvalid`] with the server's message at `source`
92
/// when it does not compile or render.
93
3
pub async fn test(session: &mut Session, source: &str) -> Result<Vec<String>, CommandError> {
94
3
    let values = values_of(None, Some(source));
95
3
    let draft = eval_value(session, &submit_call(&TEMPLATE_TEST, &values)).await?;
96
2
    let accounts = options(session, "accounts").await?;
97
2
    let commodities = options(session, "commodities").await?;
98
2
    render_draft(&draft, &accounts, &commodities)
99
3
}
100

            
101
154
fn label_of(options: &[FormOption], id: &str) -> String {
102
154
    options
103
154
        .iter()
104
192
        .find(|option| option.id == id)
105
154
        .map_or_else(|| id.to_string(), |option| option.label.clone())
106
154
}
107

            
108
182
fn items(value: Option<Value>) -> Vec<Value> {
109
182
    value.as_ref().and_then(list_to_vec).unwrap_or_default()
110
182
}
111

            
112
76
fn tag_text(tag: &Value) -> Option<String> {
113
76
    Some(format!(
114
        "{}={}",
115
76
        plist_field(tag, ":name")?,
116
76
        plist_field(tag, ":value")?
117
    ))
118
76
}
119

            
120
129
fn tags_text(tags: Option<Value>) -> Vec<String> {
121
129
    items(tags).iter().filter_map(tag_text).collect()
122
129
}
123

            
124
78
fn split_line(
125
78
    split: &Value,
126
78
    accounts: &[FormOption],
127
78
    commodities: &[FormOption],
128
78
) -> Option<String> {
129
78
    let account = label_of(accounts, &plist_field(split, ":account")?);
130
77
    let commodity = label_of(commodities, &plist_field(split, ":commodity")?);
131
77
    let amount = plist_field(split, ":amount")?;
132
77
    let tags = tags_text(plist_field_raw(split, ":tags")).join(", ");
133
77
    let line = format!("split: {account}  {amount} {commodity}");
134
77
    Some(match tags.is_empty() {
135
39
        true => line,
136
38
        false => format!("{line}  [{tags}]"),
137
    })
138
78
}
139

            
140
104
fn optional_line(label: &str, value: Option<Value>) -> Option<String> {
141
104
    match value? {
142
76
        Value::String(text) => Some(format!("{label}: {text}")),
143
28
        _ => None,
144
    }
145
104
}
146

            
147
52
fn prefillable_line(draft: &Value) -> String {
148
52
    match (
149
52
        plist_field_raw(draft, ":prefillable"),
150
52
        plist_field_raw(draft, ":reason"),
151
52
    ) {
152
38
        (Some(Value::T), _) => "prefillable: yes".to_string(),
153
14
        (_, Some(Value::String(reason))) => format!("prefillable: no: {reason}"),
154
        _ => "prefillable: no".to_string(),
155
    }
156
52
}
157

            
158
/// The lines of a `template-test` draft, accounts and commodities by label.
159
///
160
/// # Errors
161
/// [`CommandError::Command`] when `draft` is not a draft plist.
162
53
pub fn render_draft(
163
53
    draft: &Value,
164
53
    accounts: &[FormOption],
165
53
    commodities: &[FormOption],
166
53
) -> Result<Vec<String>, CommandError> {
167
1
    let malformed = || {
168
1
        CommandError::Command(format!(
169
1
            "malformed template draft: {}",
170
1
            nomiscript::format_value(draft)
171
1
        ))
172
1
    };
173
53
    let splits = items(plist_field_raw(draft, ":splits"))
174
53
        .iter()
175
78
        .map(|split| split_line(split, accounts, commodities))
176
        .collect::<Option<Vec<_>>>()
177
53
        .ok_or_else(malformed)?;
178
52
    let tags = tags_text(plist_field_raw(draft, ":tags"));
179
52
    let mut lines = Vec::new();
180
52
    lines.extend(optional_line("note", plist_field_raw(draft, ":note")));
181
52
    lines.extend(optional_line("date", plist_field_raw(draft, ":date")));
182
52
    lines.extend(splits);
183
52
    if !tags.is_empty() {
184
38
        lines.push(format!("tags: {}", tags.join(", ")));
185
14
    }
186
52
    lines.push(prefillable_line(draft));
187
52
    Ok(lines)
188
53
}
189

            
190
#[cfg(test)]
191
mod tests;