1
//! Palette command builders.
2
//!
3
//! Every leaf parses its `key=value` args through [`parse_args`]. Eval-able
4
//! leaves build a nomiscript form string for
5
//! [`crate::app::App::submit_console_form`]; reports, account merge, account
6
//! balance and transaction list build values the caller resolves and runs.
7
//! Leaves that open modals or switch tabs take no args.
8

            
9
use cli_core::CommandError;
10
use cli_core::eval::escape_str;
11
use cli_core::forms::{FormOption, resolve};
12
use forms::{ACCOUNT_MERGE, CONFIG_SET, Field, FormValues, Kind, Source, TRANSACTION_QUERY};
13

            
14
use crate::tabs::reports::ReportKind;
15

            
16
/// A `reports <kind>` palette command: the typed args as form values.
17
pub struct ReportRequest {
18
    pub kind: ReportKind,
19
    /// Choice values resolved to their keys; select values as typed until looked up.
20
    pub values: FormValues,
21
    /// A bare `reports <kind>` asks for its form, not a run.
22
    pub interactive: bool,
23
}
24

            
25
/// Whether every field the report requires holds a value.
26
#[must_use]
27
31
pub fn report_ready(kind: ReportKind, values: &FormValues) -> bool {
28
31
    kind.descriptor()
29
31
        .fields
30
31
        .iter()
31
125
        .filter(|field| field.required)
32
15
        .all(|field| values.text(field.key).is_some_and(|text| !text.is_empty()))
33
31
}
34

            
35
/// The keys a report accepts as palette args: its single-value fields.
36
74
pub fn report_arg_keys(kind: ReportKind) -> impl Iterator<Item = &'static str> {
37
74
    kind.descriptor()
38
74
        .fields
39
74
        .iter()
40
372
        .filter(|field| takes_arg(field))
41
352
        .map(|field| field.key)
42
74
}
43

            
44
684
fn takes_arg(field: &Field) -> bool {
45
684
    !matches!(field.kind, Kind::Rows { .. } | Kind::Hidden)
46
684
}
47

            
48
/// Resolve a `reports <kind>` palette command; `Ok(None)` for any other path.
49
///
50
/// # Errors
51
///
52
/// Returns an error for a key the report does not take or a choice value that
53
/// is not one of its options.
54
74
pub fn build_report_request(
55
74
    path: &[String],
56
74
    args: &[(String, String)],
57
74
) -> Result<Option<ReportRequest>, CommandError> {
58
74
    let kind = match path_key(path).as_str() {
59
45
        "reports balance" => ReportKind::Balance,
60
19
        "reports activity" => ReportKind::Activity,
61
9
        "reports breakdown" => ReportKind::Breakdown,
62
1
        _ => return Ok(None),
63
    };
64
73
    let keys: Vec<&str> = report_arg_keys(kind).collect();
65
73
    let mut values = FormValues::default();
66
73
    let given = parse_args(&keys, args)?;
67
312
    for field in kind.descriptor().fields.iter().filter(|f| takes_arg(f)) {
68
317
        let Some(&(key, value)) = given.iter().find(|(key, _)| *key == field.key) else {
69
232
            continue;
70
        };
71
66
        match field.kind {
72
10
            Kind::Choice { options, .. } => values.set(key, &resolve_choice(key, options, value)?),
73
56
            _ => values.set(key, value),
74
        }
75
    }
76
61
    Ok(Some(ReportRequest {
77
61
        kind,
78
61
        values,
79
61
        interactive: args.is_empty(),
80
61
    }))
81
74
}
82

            
83
10
fn resolve_choice(
84
10
    key: &str,
85
10
    options: &[(&str, &str)],
86
10
    input: &str,
87
10
) -> Result<String, CommandError> {
88
10
    let options: Vec<FormOption> = options
89
10
        .iter()
90
        .map(|&(id, label)| FormOption {
91
40
            id: id.to_string(),
92
40
            label: label.to_string(),
93
40
            alias: String::new(),
94
40
            commodity: None,
95
40
        })
96
        .collect();
97
10
    resolve(&options, Source::Accounts, key, input)
98
10
}
99

            
100
/// The non-empty `key=value` args, each key allowed and given once. An empty
101
/// value means the key is not given.
102
///
103
/// # Errors
104
///
105
/// Returns an error for a key outside `allowed` or one given twice.
106
209
pub fn parse_args<'a>(
107
209
    allowed: &[&str],
108
209
    args: &'a [(String, String)],
109
209
) -> Result<Vec<(&'a str, &'a str)>, CommandError> {
110
209
    let mut parsed: Vec<(&str, &str)> = Vec::new();
111
209
    let mut seen: Vec<&str> = Vec::new();
112
209
    for (key, value) in args {
113
191
        if !allowed.contains(&key.as_str()) {
114
39
            return Err(CommandError::Argument(format!("unknown arg: {key}")));
115
152
        }
116
152
        if seen.contains(&key.as_str()) {
117
15
            return Err(CommandError::Argument(format!("duplicate arg: {key}")));
118
137
        }
119
137
        seen.push(key);
120
137
        if !value.is_empty() {
121
131
            parsed.push((key, value));
122
6
        }
123
    }
124
155
    Ok(parsed)
125
209
}
126

            
127
33
fn values_of(parsed: &[(&str, &str)]) -> FormValues {
128
33
    let mut values = FormValues::default();
129
33
    parsed
130
33
        .iter()
131
31
        .for_each(|(key, value)| values.set(key, value));
132
33
    values
133
33
}
134

            
135
13
fn require<'a>(parsed: &[(&str, &'a str)], key: &str) -> Result<&'a str, CommandError> {
136
13
    parsed
137
13
        .iter()
138
6
        .find(|(k, _)| *k == key)
139
        .map(|&(_, value)| value)
140
7
        .ok_or_else(|| CommandError::Argument(format!("missing required arg: {key}")))
141
13
}
142

            
143
/// The args a leaf takes; `None` for the leaves with their own builder.
144
113
fn leaf_arg_keys(leaf: &str) -> Option<Vec<&'static str>> {
145
113
    match leaf {
146
        "version" | "account create" | "account edit" | "account list" | "commodity create"
147
        | "commodity edit" | "commodity convert" | "commodity list" | "transaction create" => {
148
52
            Some(Vec::new())
149
        }
150
7
        "config get" => Some(vec!["key"]),
151
16
        "config set" => Some(CONFIG_SET.fields.iter().map(|field| field.key).collect()),
152
2
        "ssh-key add" => Some(vec!["key"]),
153
2
        "ssh-key list" => Some(Vec::new()),
154
4
        "ssh-key remove" => Some(vec!["fingerprint"]),
155
38
        _ => None,
156
    }
157
113
}
158

            
159
/// Attempt to build a nomiscript form for the leaf at `path` given `args`.
160
///
161
/// Returns `Ok(Some(form))` for eval-able leaves, `Ok(None)` when the
162
/// leaf is handled outside the eval path (modal, tab switch or its own
163
/// builder), and `Err` for an unknown, repeated or missing arg.
164
113
pub fn build_form(
165
113
    path: &[String],
166
113
    args: &[(String, String)],
167
113
) -> Result<Option<String>, CommandError> {
168
113
    let leaf = path_key(path);
169
113
    let Some(allowed) = leaf_arg_keys(&leaf) else {
170
38
        return Ok(None);
171
    };
172
75
    let parsed = parse_args(&allowed, args)?;
173
48
    match leaf.as_str() {
174
7
        "version" => Ok(Some("(get-version)".to_string())),
175
3
        "config get" => Ok(Some(format!(
176
            "(get-config {})",
177
3
            escape_str(require(&parsed, "key")?)
178
        ))),
179
38
        _ => Ok(None),
180
    }
181
113
}
182

            
183
pub const BALANCE_ACCOUNT: &str = "account";
184

            
185
/// The args of `account balance`, resolved like a form's select values.
186
pub const BALANCE_ARGS: forms::Form = forms::Form {
187
    name: "account-balance",
188
    title: "Account balance",
189
    fields: &[Field {
190
        key: BALANCE_ACCOUNT,
191
        label: "Account",
192
        kind: Kind::Select {
193
            source: Source::Accounts,
194
            fills: None,
195
            empty: None,
196
        },
197
        required: true,
198
    }],
199
    action: forms::Action::Query,
200
};
201

            
202
/// The account label or id `account balance` names.
203
///
204
/// # Errors
205
///
206
/// Returns an error for an unknown or repeated key, or no `account`.
207
14
pub fn build_account_balance(args: &[(String, String)]) -> Result<String, CommandError> {
208
14
    let parsed = parse_args(&[BALANCE_ACCOUNT], args)?;
209
10
    require(&parsed, BALANCE_ACCOUNT).map(str::to_string)
210
14
}
211

            
212
/// The `account merge` args as form values: `from` and `into`, each at most once.
213
///
214
/// # Errors
215
///
216
/// Returns an error for an unknown or repeated key.
217
20
pub fn build_account_merge(args: &[(String, String)]) -> Result<FormValues, CommandError> {
218
40
    let keys: Vec<&str> = ACCOUNT_MERGE.fields.iter().map(|field| field.key).collect();
219
20
    parse_args(&keys, args).map(|parsed| values_of(&parsed))
220
20
}
221

            
222
/// The `transaction list` args as filter values; the accepted keys are the
223
/// `transaction-query` descriptor's, paging ones aside.
224
///
225
/// # Errors
226
///
227
/// Returns an error for a key that does not filter transactions or is repeated.
228
26
pub fn build_transaction_filter(args: &[(String, String)]) -> Result<FormValues, CommandError> {
229
26
    let keys: Vec<&str> = TRANSACTION_QUERY
230
26
        .filter_fields()
231
78
        .map(|field| field.key)
232
        .collect();
233
26
    parse_args(&keys, args).map(|parsed| values_of(&parsed))
234
26
}
235

            
236
/// Flatten `path` into a space-joined key for matching.
237
187
fn path_key(path: &[String]) -> String {
238
187
    path.join(" ")
239
187
}
240

            
241
#[cfg(test)]
242
mod tests;