1use forms::{Form, FormValues, Kind, Row, Source, escape_str};
4use rpc::Session;
5
6use super::{FormOption, parse_option_list};
7use crate::CommandError;
8use crate::transaction::eval_text;
9
10pub type Fetched = Vec<(Source, Vec<FormOption>)>;
12
13pub fn resolve(
20 options: &[FormOption],
21 source: Source,
22 flag: &str,
23 input: &str,
24) -> Result<String, CommandError> {
25 if let Some(own) = options.iter().find(|o| o.id.eq_ignore_ascii_case(input)) {
26 return Ok(own.id.clone());
27 }
28 let wanted = fold(source, input);
29 let by_label: Vec<_> = options
30 .iter()
31 .filter(|o| fold(source, &o.label) == wanted)
32 .collect();
33 let candidates = match by_label.is_empty() {
34 true => options
35 .iter()
36 .filter(|o| fold(source, &o.alias) == wanted)
37 .collect(),
38 false => by_label,
39 };
40 match candidates.as_slice() {
41 [only] => Ok(only.id.clone()),
42 [] => Err(CommandError::Argument(format!(
43 "{flag}: '{input}' matches no entry"
44 ))),
45 many => Err(CommandError::Argument(format!(
46 "{flag}: '{input}' is ambiguous, use one of: {}",
47 many.iter()
48 .map(|o| o.label.as_str())
49 .collect::<Vec<_>>()
50 .join(", ")
51 ))),
52 }
53}
54
55fn fold(source: Source, text: &str) -> String {
56 let text = text.replace('|', "¦");
57 match source {
58 Source::Commodities => text.to_lowercase(),
59 Source::Accounts | Source::Templates | Source::Scripts => text,
60 }
61}
62
63pub async fn map_references(
70 session: &mut Session,
71 form: &Form,
72 values: &FormValues,
73) -> Result<FormValues, CommandError> {
74 let mut fetched = Fetched::new();
75 for source in sources_used(form, values) {
76 let call = format!("(form-options {})", escape_str(source.name()));
77 let options = parse_option_list(&eval_text(session, &call).await?);
78 fetched.push((source, options));
79 }
80 map_values(form, values, &fetched, "--")
81}
82
83#[must_use]
85pub fn sources_used(form: &Form, values: &FormValues) -> Vec<Source> {
86 let mut used = Vec::new();
87 for field in form.fields {
88 let sources = match field.kind {
89 Kind::Select { source, .. } => values.text(field.key).map(|_| vec![source]),
90 Kind::Rows { fields, .. } => values.rows(field.key).map(|rows| {
91 rows.iter()
92 .flat_map(|row| row.keys().filter_map(|k| select_source(fields, k)))
93 .collect()
94 }),
95 _ => None,
96 };
97 for source in sources.unwrap_or_default() {
98 if !used.contains(&source) {
99 used.push(source);
100 }
101 }
102 }
103 used
104}
105
106fn select_source(fields: &[forms::Field], key: &str) -> Option<Source> {
107 match fields.iter().find(|f| f.key == key)?.kind {
108 Kind::Select { source, .. } => Some(source),
109 _ => None,
110 }
111}
112
113pub fn map_values(
119 form: &Form,
120 values: &FormValues,
121 fetched: &Fetched,
122 flag_prefix: &str,
123) -> Result<FormValues, CommandError> {
124 let mut mapped = FormValues::default();
125 for field in form.fields {
126 match field.kind {
127 Kind::Select { source, .. } => {
128 if let Some(text) = values.text(field.key) {
129 let flag = format!("{flag_prefix}{}", field.key);
130 mapped.set(field.key, &map_one(fetched, source, &flag, text)?);
131 }
132 }
133 Kind::Rows { fields, .. } => {
134 if let Some(rows) = values.rows(field.key) {
135 mapped.set_rows(field.key);
136 for row in rows {
137 mapped.push_row(field.key, map_row(fields, row, fetched, flag_prefix)?);
138 }
139 }
140 }
141 _ => {
142 if let Some(text) = values.text(field.key) {
143 mapped.set(field.key, text);
144 }
145 }
146 }
147 }
148 Ok(mapped)
149}
150
151fn map_row(
152 fields: &[forms::Field],
153 row: &Row,
154 fetched: &Fetched,
155 flag_prefix: &str,
156) -> Result<Row, CommandError> {
157 row.iter()
158 .map(|(key, text)| {
159 let flag = format!("{flag_prefix}row {key}");
160 let text = match select_source(fields, key) {
161 Some(source) => map_one(fetched, source, &flag, text)?,
162 None => text.clone(),
163 };
164 Ok((key.clone(), text))
165 })
166 .collect()
167}
168
169fn map_one(
170 fetched: &Fetched,
171 source: Source,
172 flag: &str,
173 text: &str,
174) -> Result<String, CommandError> {
175 if text.is_empty() {
176 return Ok(String::new());
177 }
178 let options = fetched
179 .iter()
180 .find(|(s, _)| *s == source)
181 .map_or(&[][..], |(_, options)| options.as_slice());
182 resolve(options, source, flag, text)
183}