1use forms::{FormValues, TEMPLATE_CREATE, TEMPLATE_EDIT, TEMPLATE_TEST, escape_str};
4use nomiscript::{Value, list_to_vec};
5use rpc::Session;
6
7use crate::CommandError;
8use crate::eval::{plist_field, plist_field_raw};
9use crate::flat::{Reply, edit as edit_form, load_values, submit};
10use crate::forms::{FormOption, parse_option_list};
11use crate::transaction::{eval_text, eval_value, submit_call};
12
13pub(crate) async fn options(
14 session: &mut Session,
15 source: &str,
16) -> Result<Vec<FormOption>, CommandError> {
17 let call = format!("(form-options {})", escape_str(source));
18 Ok(parse_option_list(&eval_text(session, &call).await?))
19}
20
21pub async fn list(session: &mut Session) -> Result<Vec<String>, CommandError> {
26 let templates = options(session, "templates").await?;
27 Ok(templates
28 .iter()
29 .map(|template| format!("{} {}", template.id, template.label))
30 .collect())
31}
32
33fn stored_id(reply: Reply) -> Result<String, CommandError> {
34 match reply {
35 Reply::Entity(id) => Ok(id),
36 other => Err(CommandError::Command(format!(
37 "unexpected template reply: {other:?}"
38 ))),
39 }
40}
41
42fn values_of(name: Option<&str>, source: Option<&str>) -> FormValues {
43 let mut values = FormValues::default();
44 name.into_iter().for_each(|name| values.set("name", name));
45 source
46 .into_iter()
47 .for_each(|source| values.set("source", source));
48 values
49}
50
51pub async fn create(
56 session: &mut Session,
57 name: Option<&str>,
58 source: &str,
59) -> Result<String, CommandError> {
60 let values = values_of(name, Some(source));
61 stored_id(submit(session, &TEMPLATE_CREATE, &values).await?.reply)
62}
63
64pub async fn edit(
70 session: &mut Session,
71 id: &str,
72 name: Option<&str>,
73 source: Option<&str>,
74) -> Result<String, CommandError> {
75 let values = values_of(name, source);
76 stored_id(edit_form(session, &TEMPLATE_EDIT, id, &values).await?.reply)
77}
78
79pub async fn stored_source(session: &mut Session, id: &str) -> Result<String, CommandError> {
84 let loaded = load_values(session, &TEMPLATE_EDIT, id).await?;
85 Ok(loaded.text("source").unwrap_or_default().to_string())
86}
87
88pub async fn test(session: &mut Session, source: &str) -> Result<Vec<String>, CommandError> {
94 let values = values_of(None, Some(source));
95 let draft = eval_value(session, &submit_call(&TEMPLATE_TEST, &values)).await?;
96 let accounts = options(session, "accounts").await?;
97 let commodities = options(session, "commodities").await?;
98 render_draft(&draft, &accounts, &commodities)
99}
100
101fn label_of(options: &[FormOption], id: &str) -> String {
102 options
103 .iter()
104 .find(|option| option.id == id)
105 .map_or_else(|| id.to_string(), |option| option.label.clone())
106}
107
108fn items(value: Option<Value>) -> Vec<Value> {
109 value.as_ref().and_then(list_to_vec).unwrap_or_default()
110}
111
112fn tag_text(tag: &Value) -> Option<String> {
113 Some(format!(
114 "{}={}",
115 plist_field(tag, ":name")?,
116 plist_field(tag, ":value")?
117 ))
118}
119
120fn tags_text(tags: Option<Value>) -> Vec<String> {
121 items(tags).iter().filter_map(tag_text).collect()
122}
123
124fn split_line(
125 split: &Value,
126 accounts: &[FormOption],
127 commodities: &[FormOption],
128) -> Option<String> {
129 let account = label_of(accounts, &plist_field(split, ":account")?);
130 let commodity = label_of(commodities, &plist_field(split, ":commodity")?);
131 let amount = plist_field(split, ":amount")?;
132 let tags = tags_text(plist_field_raw(split, ":tags")).join(", ");
133 let line = format!("split: {account} {amount} {commodity}");
134 Some(match tags.is_empty() {
135 true => line,
136 false => format!("{line} [{tags}]"),
137 })
138}
139
140fn optional_line(label: &str, value: Option<Value>) -> Option<String> {
141 match value? {
142 Value::String(text) => Some(format!("{label}: {text}")),
143 _ => None,
144 }
145}
146
147fn prefillable_line(draft: &Value) -> String {
148 match (
149 plist_field_raw(draft, ":prefillable"),
150 plist_field_raw(draft, ":reason"),
151 ) {
152 (Some(Value::T), _) => "prefillable: yes".to_string(),
153 (_, Some(Value::String(reason))) => format!("prefillable: no: {reason}"),
154 _ => "prefillable: no".to_string(),
155 }
156}
157
158pub fn render_draft(
163 draft: &Value,
164 accounts: &[FormOption],
165 commodities: &[FormOption],
166) -> Result<Vec<String>, CommandError> {
167 let malformed = || {
168 CommandError::Command(format!(
169 "malformed template draft: {}",
170 nomiscript::format_value(draft)
171 ))
172 };
173 let splits = items(plist_field_raw(draft, ":splits"))
174 .iter()
175 .map(|split| split_line(split, accounts, commodities))
176 .collect::<Option<Vec<_>>>()
177 .ok_or_else(malformed)?;
178 let tags = tags_text(plist_field_raw(draft, ":tags"));
179 let mut lines = Vec::new();
180 lines.extend(optional_line("note", plist_field_raw(draft, ":note")));
181 lines.extend(optional_line("date", plist_field_raw(draft, ":date")));
182 lines.extend(splits);
183 if !tags.is_empty() {
184 lines.push(format!("tags: {}", tags.join(", ")));
185 }
186 lines.push(prefillable_line(draft));
187 Ok(lines)
188}
189
190#[cfg(test)]
191mod tests;