1
//! Maps the CLI's select input (id, label or alias) to option ids before a submit.
2

            
3
use forms::{Form, FormValues, Kind, Row, Source, escape_str};
4
use rpc::Session;
5

            
6
use super::{FormOption, parse_option_list};
7
use crate::CommandError;
8
use crate::transaction::eval_text;
9

            
10
/// The `form-options` fetched per source.
11
pub type Fetched = Vec<(Source, Vec<FormOption>)>;
12

            
13
/// The id of the option `input` names: an own id, an exact label, or a unique
14
/// alias; `|` stands for `¦`, and commodities compare case-insensitively.
15
///
16
/// # Errors
17
/// [`CommandError::Argument`] naming `flag` when nothing matches, or listing
18
/// the candidate labels when several do.
19
1110
pub fn resolve(
20
1110
    options: &[FormOption],
21
1110
    source: Source,
22
1110
    flag: &str,
23
1110
    input: &str,
24
1110
) -> Result<String, CommandError> {
25
2030
    if let Some(own) = options.iter().find(|o| o.id.eq_ignore_ascii_case(input)) {
26
366
        return Ok(own.id.clone());
27
744
    }
28
744
    let wanted = fold(source, input);
29
744
    let by_label: Vec<_> = options
30
744
        .iter()
31
1278
        .filter(|o| fold(source, &o.label) == wanted)
32
        .collect();
33
744
    let candidates = match by_label.is_empty() {
34
131
        true => options
35
131
            .iter()
36
251
            .filter(|o| fold(source, &o.alias) == wanted)
37
            .collect(),
38
613
        false => by_label,
39
    };
40
744
    match candidates.as_slice() {
41
580
        [only] => Ok(only.id.clone()),
42
122
        [] => Err(CommandError::Argument(format!(
43
122
            "{flag}: '{input}' matches no entry"
44
122
        ))),
45
42
        many => Err(CommandError::Argument(format!(
46
42
            "{flag}: '{input}' is ambiguous, use one of: {}",
47
42
            many.iter()
48
84
                .map(|o| o.label.as_str())
49
                .collect::<Vec<_>>()
50
42
                .join(", ")
51
        ))),
52
    }
53
1110
}
54

            
55
2273
fn fold(source: Source, text: &str) -> String {
56
2273
    let text = text.replace('|', "¦");
57
2273
    match source {
58
617
        Source::Commodities => text.to_lowercase(),
59
1656
        Source::Accounts | Source::Templates | Source::Scripts => text,
60
    }
61
2273
}
62

            
63
/// `values` with every non-empty select value replaced by its option id, over
64
/// one `form-options` fetch per source; the session sees no submit on failure.
65
///
66
/// # Errors
67
/// [`CommandError::Argument`] for an unknown or ambiguous value, or the
68
/// server's refusal of the fetch.
69
543
pub async fn map_references(
70
543
    session: &mut Session,
71
543
    form: &Form,
72
543
    values: &FormValues,
73
543
) -> Result<FormValues, CommandError> {
74
543
    let mut fetched = Fetched::new();
75
543
    for source in sources_used(form, values) {
76
225
        let call = format!("(form-options {})", escape_str(source.name()));
77
225
        let options = parse_option_list(&eval_text(session, &call).await?);
78
225
        fetched.push((source, options));
79
    }
80
543
    map_values(form, values, &fetched, "--")
81
543
}
82

            
83
/// The option sources `values` has a select value in.
84
#[must_use]
85
1755
pub fn sources_used(form: &Form, values: &FormValues) -> Vec<Source> {
86
1755
    let mut used = Vec::new();
87
1755
    for field in form.fields {
88
6786
        let sources = match field.kind {
89
1713
            Kind::Select { source, .. } => values.text(field.key).map(|_| vec![source]),
90
457
            Kind::Rows { fields, .. } => values.rows(field.key).map(|rows| {
91
114
                rows.iter()
92
488
                    .flat_map(|row| row.keys().filter_map(|k| select_source(fields, k)))
93
                    .collect()
94
114
            }),
95
4616
            _ => None,
96
        };
97
6786
        for source in sources.unwrap_or_default() {
98
1529
            if !used.contains(&source) {
99
1053
                used.push(source);
100
476
            }
101
        }
102
    }
103
1755
    used
104
1755
}
105

            
106
969
fn select_source(fields: &[forms::Field], key: &str) -> Option<Source> {
107
3420
    match fields.iter().find(|f| f.key == key)?.kind {
108
594
        Kind::Select { source, .. } => Some(source),
109
375
        _ => None,
110
    }
111
969
}
112

            
113
/// `values` with every non-empty select value replaced by its id in `fetched`;
114
/// errors name a field as `{flag_prefix}{key}`.
115
///
116
/// # Errors
117
/// [`CommandError::Argument`] for an unknown or ambiguous value.
118
1541
pub fn map_values(
119
1541
    form: &Form,
120
1541
    values: &FormValues,
121
1541
    fetched: &Fetched,
122
1541
    flag_prefix: &str,
123
1541
) -> Result<FormValues, CommandError> {
124
1541
    let mut mapped = FormValues::default();
125
1541
    for field in form.fields {
126
5636
        match field.kind {
127
            Kind::Select { source, .. } => {
128
1462
                if let Some(text) = values.text(field.key) {
129
979
                    let flag = format!("{flag_prefix}{}", field.key);
130
979
                    mapped.set(field.key, &map_one(fetched, source, &flag, text)?);
131
483
                }
132
            }
133
            Kind::Rows { fields, .. } => {
134
453
                if let Some(rows) = values.rows(field.key) {
135
114
                    mapped.set_rows(field.key);
136
114
                    for row in rows {
137
122
                        mapped.push_row(field.key, map_row(fields, row, fetched, flag_prefix)?);
138
                    }
139
339
                }
140
            }
141
            _ => {
142
3721
                if let Some(text) = values.text(field.key) {
143
1106
                    mapped.set(field.key, text);
144
2615
                }
145
            }
146
        }
147
    }
148
1419
    Ok(mapped)
149
1541
}
150

            
151
122
fn map_row(
152
122
    fields: &[forms::Field],
153
122
    row: &Row,
154
122
    fetched: &Fetched,
155
122
    flag_prefix: &str,
156
122
) -> Result<Row, CommandError> {
157
122
    row.iter()
158
481
        .map(|(key, text)| {
159
481
            let flag = format!("{flag_prefix}row {key}");
160
481
            let text = match select_source(fields, key) {
161
295
                Some(source) => map_one(fetched, source, &flag, text)?,
162
186
                None => text.clone(),
163
            };
164
477
            Ok((key.clone(), text))
165
481
        })
166
        .collect()
167
122
}
168

            
169
1274
fn map_one(
170
1274
    fetched: &Fetched,
171
1274
    source: Source,
172
1274
    flag: &str,
173
1274
    text: &str,
174
1274
) -> Result<String, CommandError> {
175
1274
    if text.is_empty() {
176
312
        return Ok(String::new());
177
962
    }
178
962
    let options = fetched
179
962
        .iter()
180
1061
        .find(|(s, _)| *s == source)
181
962
        .map_or(&[][..], |(_, options)| options.as_slice());
182
962
    resolve(options, source, flag, text)
183
1274
}